@gaodefa/daocore 2026.5.29 → 2026.5.30

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 (1068) hide show
  1. package/dist/abort-DI3P6TIb.js +277 -0
  2. package/dist/abort.runtime-B6Z7lDEa.js +2 -0
  3. package/dist/abort.runtime.js +1 -1
  4. package/dist/account-inspect-BFz7X0TX.js +173 -0
  5. package/dist/accounts-BoYYrY7x.js +107 -0
  6. package/dist/accounts-Busq29zW.js +107 -0
  7. package/dist/accounts-CuvH2tuN.js +119 -0
  8. package/dist/accounts-DkIcqvf7.js +2 -0
  9. package/dist/acp-runtime-BA8lzXzf.js +26 -0
  10. package/dist/acp-spawn-DPz2aX3A.js +2 -0
  11. package/dist/acp-spawn-DvVCsWYV.js +1275 -0
  12. package/dist/acp-stateful-target-driver-DcC76aZW.js +89 -0
  13. package/dist/action-kill-D-dVisIX.js +33 -0
  14. package/dist/action-runtime-BEiqwxDD.js +469 -0
  15. package/dist/action-runtime-api-1LzcGjcX.js +2 -0
  16. package/dist/action-send-c3CnDuPg.js +39 -0
  17. package/dist/action-spawn-Dj4kwpWs.js +47 -0
  18. package/dist/actions-qLccmQBc.js +161 -0
  19. package/dist/actions.runtime-B5vYAgNi.js +5 -0
  20. package/dist/agent-command-D6Ds198G.js +1367 -0
  21. package/dist/agent-components.runtime-xquK0B3L.js +10 -0
  22. package/dist/agent-components.runtime.js +1 -1
  23. package/dist/agent-harness-runtime-Dq1fCBOM.js +180 -0
  24. package/dist/agent-harness-task-runtime-DvSEqFkD.js +140 -0
  25. package/dist/agent-lm5ZYOFy.js +3 -0
  26. package/dist/agent-runner-execution-Dbh2pDhQ.js +1713 -0
  27. package/dist/agent-runner-utils-Di3r2T1T.js +266 -0
  28. package/dist/agent-runner.runtime-BW90EcGW.js +3455 -0
  29. package/dist/agent-runner.runtime.js +1 -1
  30. package/dist/agent-runtime-BgIT5Ytc.js +229 -0
  31. package/dist/agent-via-gateway-DMMS8-hK.js +463 -0
  32. package/dist/agent-ylolD8-V.js +2 -0
  33. package/dist/api-BB4vXLtW.js +2 -0
  34. package/dist/api-CUhM3KNB.js +134 -0
  35. package/dist/api-CewRHSbT.js +6 -0
  36. package/dist/api-CfKjNJlW.js +2 -0
  37. package/dist/api-Rsnqui1u.js +3 -0
  38. package/dist/api-k7AvxwHr.js +639 -0
  39. package/dist/apply-DQ4TQNMA.js +54 -0
  40. package/dist/apply-S_75Py4Y.js +41 -0
  41. package/dist/approval-handler.runtime-Cthxrstu.js +130 -0
  42. package/dist/assistant-Cp9pGaBw.js +291 -0
  43. package/dist/attachment-normalize-5R0bLLOj.js +225 -0
  44. package/dist/attempt-execution-DuyyZYsU.js +558 -0
  45. package/dist/attempt-execution.runtime-DF2GPgNh.js +3 -0
  46. package/dist/attempt-execution.runtime.js +1 -1
  47. package/dist/attempt-execution.shared-CwdukA3t.js +38 -0
  48. package/dist/attempt.prompt-helpers-CUqKtIa5.js +475 -0
  49. package/dist/attempt.tool-run-context-BbN4_BYO.js +2094 -0
  50. package/dist/binding-routing-C6Ex2Blu.js +113 -0
  51. package/dist/binding-targets-BqREncSL.js +121 -0
  52. package/dist/bot-DGMEkaIJ.js +7894 -0
  53. package/dist/bot-deps-BltYjeMX.js +2 -0
  54. package/dist/bot-deps-XvGCor9f.js +747 -0
  55. package/dist/bot-message-context.runtime-kK-xvLV7.js +7 -0
  56. package/dist/bot-message-context.runtime.js +1 -1
  57. package/dist/bot-message-context.session.runtime-DpOIJUae.js +12 -0
  58. package/dist/bot-message-context.session.runtime.js +1 -1
  59. package/dist/bot-native-commands.delivery.runtime-D49p5Lc1.js +4 -0
  60. package/dist/bot-native-commands.delivery.runtime.js +1 -1
  61. package/dist/bot-native-commands.runtime-8XBdSpkQ.js +13 -0
  62. package/dist/bot-native-commands.runtime.js +1 -1
  63. package/dist/bridge-server-y_XGduPx.js +113 -0
  64. package/dist/browser-cli-B2jmmTT3.js +230 -0
  65. package/dist/browser-cli-actions-input-JQt5ZQcn.js +473 -0
  66. package/dist/browser-cli-actions-observe-CrfKh6AX.js +81 -0
  67. package/dist/browser-cli-debug-DQACWlvC.js +137 -0
  68. package/dist/browser-cli-inspect-DDnxx0Xw.js +104 -0
  69. package/dist/browser-cli-lEuOnZzs.js +2 -0
  70. package/dist/browser-cli-manage-DogmwtYt.js +443 -0
  71. package/dist/browser-cli-resize-BHuV71VZ.js +26 -0
  72. package/dist/browser-cli-shared-CidShgoF.js +50 -0
  73. package/dist/browser-cli-state-i8cCGbiQ.js +337 -0
  74. package/dist/browser-control-auth-CKfXdXWj.js +2 -0
  75. package/dist/browser-profiles-ATBTvUGh.js +2 -0
  76. package/dist/browser-runtime-KmCT6FuL.js +384 -0
  77. package/dist/build-DOOT6f62.js +257 -0
  78. package/dist/build-info.json +3 -3
  79. package/dist/bundled/boot-md/handler.js +2 -2
  80. package/dist/bundled/session-memory/handler.js +1 -1
  81. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  82. package/dist/capability-cli-DwvrwB-g.js +1782 -0
  83. package/dist/channel-B-wgK1bK.js +481 -0
  84. package/dist/channel-B1e_k1P0.js +867 -0
  85. package/dist/channel-BRDfa5tc.js +1777 -0
  86. package/dist/channel-BVEO1O4p.js +376 -0
  87. package/dist/channel-BYlO5l1d.js +508 -0
  88. package/dist/channel-Bl0sPoNx.js +653 -0
  89. package/dist/channel-C84xtDBy.js +1134 -0
  90. package/dist/channel-CLgKq4Ds.js +1556 -0
  91. package/dist/channel-CZT0qxLh.js +1249 -0
  92. package/dist/channel-CffBHWkb.js +955 -0
  93. package/dist/channel-D34ZJvVB.js +2126 -0
  94. package/dist/channel-DcdXLo_W.js +238 -0
  95. package/dist/channel-DnK5TrXV.js +362 -0
  96. package/dist/channel-Dzj4RHY2.js +740 -0
  97. package/dist/channel-OhZzLZCj.js +562 -0
  98. package/dist/channel-actions.runtime-Cdvhqc9s.js +265 -0
  99. package/dist/channel-actions.runtime.js +1 -1
  100. package/dist/channel-core-Dz9I_R4j.js +5 -0
  101. package/dist/channel-inbound-COGoV_aS.js +80 -0
  102. package/dist/channel-mP6HCIMr.js +1496 -0
  103. package/dist/channel-plugin-runtime-C0R46KeG.js +998 -0
  104. package/dist/channel-quGdgWel.js +808 -0
  105. package/dist/channel-runtime-FvPQoIF9.js +408 -0
  106. package/dist/channel.runtime-2vUz3gij.js +109 -0
  107. package/dist/channel.runtime-BZLDSNuQ.js +254 -0
  108. package/dist/channel.runtime-Bo5jO0Hj.js +4 -0
  109. package/dist/channel.runtime-CDgvrjM2.js +652 -0
  110. package/dist/channel.runtime-COf8SDFn.js +88 -0
  111. package/dist/channel.runtime-C_C1f8lu.js +733 -0
  112. package/dist/channel.runtime-CqPbsg8t.js +2528 -0
  113. package/dist/channel.runtime-DtV85Khx.js +1008 -0
  114. package/dist/channel.runtime-Spt1ukGW.js +21009 -0
  115. package/dist/channel.setup-Bc0LUQS1.js +1098 -0
  116. package/dist/channel.setup-ChTkj2hq.js +343 -0
  117. package/dist/channel.setup-CpMD9F8i.js +10 -0
  118. package/dist/chat-mUsjD5YN.js +2666 -0
  119. package/dist/chrome-u314zcbM.js +1503 -0
  120. package/dist/cli/run-main.js +5 -5
  121. package/dist/cli-CJMoqXrc.js +1341 -0
  122. package/dist/cli-compaction-qGYB7suI.js +347 -0
  123. package/dist/cli-metadata-BBJFpNU9.js +22 -0
  124. package/dist/cli-runner-C0kcts0I.js +540 -0
  125. package/dist/cli-runner-CTm8K6s8.js +2 -0
  126. package/dist/cli-runner.runtime-C8deL5FL.js +3 -0
  127. package/dist/cli-runner.runtime-DDAg1D0L.js +4 -0
  128. package/dist/cli-runner.runtime.js +1 -1
  129. package/dist/cli-startup-metadata.json +8 -8
  130. package/dist/client-CPxpgs4m.js +650 -0
  131. package/dist/client-adapter-CLlqOqfu.js +897 -0
  132. package/dist/client-factory-R7Rr2jwn.js +9 -0
  133. package/dist/command-auth-CkQP1buP.js +135 -0
  134. package/dist/command-handlers-CJEjFyMk.js +1609 -0
  135. package/dist/command-registry-BDgyOqDw.js +4 -0
  136. package/dist/command-registry-BVi5Jn1S.js +9 -0
  137. package/dist/command-registry-core-JCfsVRtz.js +110 -0
  138. package/dist/command-status.runtime-CM1JLzi6.js +90 -0
  139. package/dist/command-status.runtime.js +1 -1
  140. package/dist/commands-acp-C1-I78U6.js +74 -0
  141. package/dist/commands-compact.runtime-DOsNavwp.js +10 -0
  142. package/dist/commands-compact.runtime.js +1 -1
  143. package/dist/commands-handlers.runtime-BD1n2WGw.js +6154 -0
  144. package/dist/commands-handlers.runtime.js +1 -1
  145. package/dist/commands-status-DU_UTQz1.js +16 -0
  146. package/dist/commands-status-DejfTakp.js +3 -0
  147. package/dist/commands-status.runtime-DejfTakp.js +3 -0
  148. package/dist/commands-status.runtime.js +1 -1
  149. package/dist/commands-subagents-control.runtime-D7vo_2Y_.js +3 -0
  150. package/dist/commands-subagents-control.runtime-DGybTjJ6.js +2 -0
  151. package/dist/commands-subagents-control.runtime.js +1 -1
  152. package/dist/commands-system-prompt-BEBXAMea.js +2 -0
  153. package/dist/commands-system-prompt-gj3oQpQO.js +162 -0
  154. package/dist/commands.runtime-CgXX70IN.js +176 -0
  155. package/dist/commands.runtime.js +1 -1
  156. package/dist/commitments/runtime.js +1 -1
  157. package/dist/compact-C41XxMDt.js +480 -0
  158. package/dist/compact-DUVAF9EC.js +1141 -0
  159. package/dist/compact.runtime-COMRg6s3.js +12 -0
  160. package/dist/compact.runtime.js +1 -1
  161. package/dist/completion-cli-CmEYoB9a.js +315 -0
  162. package/dist/computer-use-BwJHu1QF.js +367 -0
  163. package/dist/config-ATBTvUGh.js +2 -0
  164. package/dist/config-DlNgjF8W.js +373 -0
  165. package/dist/config-mutations-tl_OqI6d.js +159 -0
  166. package/dist/context-engine-host-compat-BNPAIK9F.js +288 -0
  167. package/dist/context-engine-host-compat-C69CK7zS.js +2 -0
  168. package/dist/context-engine-lifecycle-iQ8f5a_-.js +1274 -0
  169. package/dist/control-auth-vVxyGKxY.js +114 -0
  170. package/dist/control-service-73nj79EW.js +145 -0
  171. package/dist/control-ui/assets/agents-DdWIz8Vk.js +1008 -0
  172. package/dist/control-ui/assets/channel-config-extras-C7ELhuDi.js +2 -0
  173. package/dist/control-ui/assets/channels-Bsoj-9BS.js +367 -0
  174. package/dist/control-ui/assets/cron-BRTEw1tT.js +1013 -0
  175. package/dist/control-ui/assets/debug-EKl_F8_L.js +97 -0
  176. package/dist/control-ui/assets/index-DSbSO7ys.js +7370 -0
  177. package/dist/control-ui/assets/instances-B1AoYwI5.js +57 -0
  178. package/dist/control-ui/assets/logs-BChOznzh.js +74 -0
  179. package/dist/control-ui/assets/nodes-5yebKh9k.js +436 -0
  180. package/dist/control-ui/assets/sessions-BlDYNThc.js +399 -0
  181. package/dist/control-ui/assets/skills-shared-CNFnf7KU.js +11 -0
  182. package/dist/control-ui/assets/skills-uxTDRmLx.js +314 -0
  183. package/dist/control-ui/index.html +1 -1
  184. package/dist/control-ui/sw.js +1 -1
  185. package/dist/conversation-binding-runtime-CmoTKcY1.js +4 -0
  186. package/dist/conversation-runtime-BxOHxuin.js +31 -0
  187. package/dist/core-D0Y2H55f.js +282 -0
  188. package/dist/core-api-BKlJUtDt.js +5 -0
  189. package/dist/core-api-_fiftUHn.js +2 -0
  190. package/dist/crestodian/crestodian.js +1 -1
  191. package/dist/crestodian/rescue-message.js +1 -1
  192. package/dist/crestodian-BJifoQiR.js +55 -0
  193. package/dist/daocore-tools-BMdF8RwK.js +11727 -0
  194. package/dist/delivery-e2ci_bcX.js +1002 -0
  195. package/dist/dialogue-BXayGhnz.js +37 -0
  196. package/dist/dir-fetch-tool-Cara5mZh.js +565 -0
  197. package/dist/dir-list-tool-CQ8Bo5Ez.js +100 -0
  198. package/dist/direct-dm-CPk6Qm9D.js +64 -0
  199. package/dist/directive-handling.fast-lane-BQ9aXqk8.js +68 -0
  200. package/dist/directive-handling.impl--a5AGurq.js +818 -0
  201. package/dist/directive-handling.impl-C4JqMwle.js +2 -0
  202. package/dist/directive-handling.model-selection-pyTYMIXn.js +122 -0
  203. package/dist/directive-handling.persist.runtime-B7vWT1r9.js +263 -0
  204. package/dist/directive-handling.persist.runtime.js +1 -1
  205. package/dist/dispatch-3Ru_eGq1.js +1640 -0
  206. package/dist/dispatch-acp-transcript.runtime-CYMP-5oE.js +40 -0
  207. package/dist/dispatch-acp-transcript.runtime.js +1 -1
  208. package/dist/dispatch-acp.runtime-BVCiklXk.js +18 -0
  209. package/dist/dispatch-acp.runtime.js +1 -1
  210. package/dist/doctor-B8mR3Sgr.js +2 -0
  211. package/dist/doctor-BJ6DuerV.js +6 -0
  212. package/dist/doctor-config-flow-BdOGs_zn.js +1741 -0
  213. package/dist/doctor-core-checks-CDf0stz-.js +2 -0
  214. package/dist/doctor-core-checks-Cpdnu2XI.js +573 -0
  215. package/dist/doctor-health-0qv_acBu.js +65 -0
  216. package/dist/doctor-health-contributions-Db1FQgFw.js +696 -0
  217. package/dist/doctor-lint-C1g4Llgl.js +94 -0
  218. package/dist/doctor-state-integrity-C8iXFLJ7.js +1231 -0
  219. package/dist/doctor-update-CsPu6p3d.js +58 -0
  220. package/dist/dynamic-tools-YQ0z0YKH.js +486 -0
  221. package/dist/embedded-backend-S0cahIZw.js +579 -0
  222. package/dist/embedded-gateway-stub.runtime-Cjw12ALm.js +12 -0
  223. package/dist/embedded-gateway-stub.runtime.js +1 -1
  224. package/dist/exec-approvals-ArHHjoE-.js +149 -0
  225. package/dist/extensionAPI.js +1 -1
  226. package/dist/extensions/active-memory/index.js +1 -1
  227. package/dist/extensions/admin-http-rpc/index.js +1 -1
  228. package/dist/extensions/browser/browser-bridge.js +1 -1
  229. package/dist/extensions/browser/browser-config.js +4 -4
  230. package/dist/extensions/browser/browser-control-auth.js +2 -2
  231. package/dist/extensions/browser/browser-doctor.js +2 -2
  232. package/dist/extensions/browser/browser-maintenance.js +1 -1
  233. package/dist/extensions/browser/browser-profiles.js +2 -2
  234. package/dist/extensions/browser/browser-runtime-api.js +11 -11
  235. package/dist/extensions/browser/cli-metadata.js +1 -1
  236. package/dist/extensions/browser/index.js +1 -1
  237. package/dist/extensions/browser/plugin-registration.js +1 -1
  238. package/dist/extensions/browser/register.runtime.js +4 -4
  239. package/dist/extensions/browser/runtime-api.js +13 -13
  240. package/dist/extensions/canvas/index.js +1 -1
  241. package/dist/extensions/clickclack/api.js +2 -2
  242. package/dist/extensions/clickclack/channel-plugin-api.js +1 -1
  243. package/dist/extensions/clickclack/runtime-api.js +2 -2
  244. package/dist/extensions/device-pair/api.js +1 -1
  245. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  246. package/dist/extensions/file-transfer/index.js +4 -4
  247. package/dist/extensions/imessage/api.js +2 -2
  248. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  249. package/dist/extensions/imessage/message-tool-api.d.ts +1 -1
  250. package/dist/extensions/imessage/runtime-api.js +3 -3
  251. package/dist/extensions/irc/api.js +2 -2
  252. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  253. package/dist/extensions/llm-task/index.js +1 -1
  254. package/dist/extensions/mattermost/api.js +1 -1
  255. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  256. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  257. package/dist/extensions/mattermost/policy-api.js +1 -1
  258. package/dist/extensions/mattermost/runtime-api.js +2 -2
  259. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  260. package/dist/extensions/memory-core/cli-metadata.js +1 -1
  261. package/dist/extensions/migrate-claude/apply.js +1 -1
  262. package/dist/extensions/migrate-claude/index.js +1 -1
  263. package/dist/extensions/migrate-claude/plan.js +1 -1
  264. package/dist/extensions/migrate-claude/provider.js +1 -1
  265. package/dist/extensions/migrate-claude/targets.js +1 -1
  266. package/dist/extensions/migrate-hermes/apply.js +1 -1
  267. package/dist/extensions/migrate-hermes/index.js +1 -1
  268. package/dist/extensions/migrate-hermes/model.js +1 -1
  269. package/dist/extensions/migrate-hermes/plan.js +1 -1
  270. package/dist/extensions/migrate-hermes/provider.js +1 -1
  271. package/dist/extensions/migrate-hermes/secrets.js +1 -1
  272. package/dist/extensions/migrate-hermes/targets.js +1 -1
  273. package/dist/extensions/policy/api.js +1 -1
  274. package/dist/extensions/policy/index.js +2 -2
  275. package/dist/extensions/signal/api.js +6 -6
  276. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  277. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  278. package/dist/extensions/signal/runtime-api.js +7 -7
  279. package/dist/extensions/skill-workshop/api.js +1 -1
  280. package/dist/extensions/skill-workshop/index.js +2 -2
  281. package/dist/extensions/telegram/account-inspect-api.js +1 -1
  282. package/dist/extensions/telegram/api.js +11 -11
  283. package/dist/extensions/telegram/channel-plugin-api.js +2 -2
  284. package/dist/extensions/telegram/contract-api.js +3 -3
  285. package/dist/extensions/telegram/runtime-api.js +7 -7
  286. package/dist/extensions/telegram/security-audit-contract-api.js +1 -1
  287. package/dist/extensions/telegram/setup-plugin-api.js +1 -1
  288. package/dist/extensions/telegram/test-api.js +2 -2
  289. package/dist/extensions/webhooks/api.js +1 -1
  290. package/dist/extensions/webhooks/index.js +1 -1
  291. package/dist/extensions/xai/index.js +4 -4
  292. package/dist/extensions/xai/realtime-transcription-provider.js +1 -1
  293. package/dist/extensions/xai/speech-provider.js +1 -1
  294. package/dist/extensions/xai/test-api.js +1 -1
  295. package/dist/extensions/xai/tts.js +1 -1
  296. package/dist/extensions/xai/web-search.js +1 -1
  297. package/dist/extensions/xai/xai-oauth.js +1 -1
  298. package/dist/file-fetch-tool-DQpAtjX4.js +124 -0
  299. package/dist/file-write-tool-CkB0oYwe.js +127 -0
  300. package/dist/format-DUJUpMFQ.js +1145 -0
  301. package/dist/gateway-cli-CQo_E4Ka.js +435 -0
  302. package/dist/gateway-method-runtime-1QPgVJH7.js +21 -0
  303. package/dist/get-reply-DfUcsC-O.js +4689 -0
  304. package/dist/get-reply-from-config.runtime-C95MG73O.js +2 -0
  305. package/dist/get-reply-from-config.runtime.js +1 -1
  306. package/dist/graph-users-DPJe0fPs.js +1419 -0
  307. package/dist/group-access-DefaNJ6L.js +112 -0
  308. package/dist/handle-action.guild-admin-C1sy1kGJ.js +288 -0
  309. package/dist/harness-BgPRdmNK.js +61 -0
  310. package/dist/health-DFR9A1YV.js +4 -0
  311. package/dist/heartbeat-runner-BiYVPs25.js +5 -0
  312. package/dist/heartbeat-runner.runtime-Bmaq8WUA.js +4 -0
  313. package/dist/heartbeat-runner.runtime.js +1 -1
  314. package/dist/hooks-CNJDuJUm.js +534 -0
  315. package/dist/inbound-direct-dm-runtime-DFt58p71.js +2 -0
  316. package/dist/inbound-reply-dispatch-kgSDM8ax.js +148 -0
  317. package/dist/index.js +1 -1
  318. package/dist/init-B0zO_U4r.js +59 -0
  319. package/dist/inline-buttons-B6zgQW3J.js +40 -0
  320. package/dist/internal-events-C3Q5t6hg.js +90 -0
  321. package/dist/isolated-agent-CaSU5GCJ.js +2 -0
  322. package/dist/isolated-agent-CnsD2TmP.js +1118 -0
  323. package/dist/lifecycle-i3WZDaIn.js +571 -0
  324. package/dist/list.probe-g0rUiVXW.js +449 -0
  325. package/dist/list.status-command-DG3PrmeO.js +789 -0
  326. package/dist/llm-slug-generator-CHlf69FU.js +78 -0
  327. package/dist/llm-slug-generator.js +1 -1
  328. package/dist/local-dispatch.runtime-CDeHUp_A.js +9 -0
  329. package/dist/local-dispatch.runtime.js +1 -1
  330. package/dist/manager.runtime-BlLMPUTq.js +2714 -0
  331. package/dist/manager.runtime.js +1 -1
  332. package/dist/markdown-to-line-r_mBHMdy.js +811 -0
  333. package/dist/mcp-http-C5UPIJGR.js +555 -0
  334. package/dist/mcp-http-CTy9gpfA.js +2 -0
  335. package/dist/media-understanding-provider-BT6TOuVa.js +339 -0
  336. package/dist/message-actions-BdcjjwFt.js +145 -0
  337. package/dist/message-handler-B29Tj2p2.js +1715 -0
  338. package/dist/message-handler-BhHb1FHI.js +384 -0
  339. package/dist/message-handler.preflight-ouZ_-3o8.js +1125 -0
  340. package/dist/message-handler.process-CrYiBx_F.js +1484 -0
  341. package/dist/model-CLbtocQX.js +74 -0
  342. package/dist/model-selection-BG_vU9Kl.js +272 -0
  343. package/dist/models-4KERn3ya.js +104 -0
  344. package/dist/models-BCa-ipxi.js +2 -0
  345. package/dist/models-cli-DtpGXEsf.js +256 -0
  346. package/dist/monitor-B-egsvmI.js +1657 -0
  347. package/dist/monitor-BJX9Yv7k.js +2 -0
  348. package/dist/monitor-BPrIy3pV.js +715 -0
  349. package/dist/monitor-BWknZZ7N.js +4377 -0
  350. package/dist/monitor-C3y_PtI1.js +60 -0
  351. package/dist/monitor-DCzfdqE4.js +1370 -0
  352. package/dist/monitor-P24epSwE.js +2788 -0
  353. package/dist/monitor-auth-CEG_xldE.js +179 -0
  354. package/dist/monitor-jEePJbbS.js +834 -0
  355. package/dist/monitor-polling.runtime-BzlHK11u.js +883 -0
  356. package/dist/monitor-polling.runtime.js +1 -1
  357. package/dist/monitor-webhook.runtime-vFEhk_Zj.js +387 -0
  358. package/dist/monitor-webhook.runtime.js +1 -1
  359. package/dist/monitor.account-BUIfgWXg.js +5233 -0
  360. package/dist/monitor.runtime-Cp7W4fhb.js +2 -0
  361. package/dist/monitor.runtime.js +1 -1
  362. package/dist/monitor.webhook-DzrbeR4T.js +180 -0
  363. package/dist/node-cli-sessions-CLbI14UA.js +1228 -0
  364. package/dist/openai-http-BM9BIA_g.js +824 -0
  365. package/dist/openresponses-http-CNoW9kk8.js +1173 -0
  366. package/dist/operations-DT4bsxV6.js +805 -0
  367. package/dist/outbound-adapter-CZRUOgY0.js +543 -0
  368. package/dist/outbound-session-route-DneMsGNx.js +45 -0
  369. package/dist/outbound.runtime-CHuoKJJI.js +2 -0
  370. package/dist/outbound.runtime.js +1 -1
  371. package/dist/pi-embedded-1-rsueO_.js +3796 -0
  372. package/dist/pi-embedded-BRfDncVO.js +4 -0
  373. package/dist/pi-embedded.runtime-DEYoa6bW.js +4 -0
  374. package/dist/pi-embedded.runtime.js +1 -1
  375. package/dist/pi-tools-C0P3NgP5.js +2413 -0
  376. package/dist/plan-BQUkjBMY.js +81 -0
  377. package/dist/plan-CRO9_2_k.js +112 -0
  378. package/dist/plugin-BJCmWhnh.js +12396 -0
  379. package/dist/plugin-app-cache-key-CXAg0F7A.js +46 -0
  380. package/dist/plugin-enabled-D93Z9LSo.js +233 -0
  381. package/dist/plugin-registration-BBrTcZnf.js +88 -0
  382. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  383. package/dist/plugin-sdk/acp-runtime-backend.js +1 -1
  384. package/dist/plugin-sdk/acp-runtime.js +2 -2
  385. package/dist/plugin-sdk/agent-harness-runtime.js +6 -6
  386. package/dist/plugin-sdk/agent-harness-task-runtime.js +1 -1
  387. package/dist/plugin-sdk/agent-harness.js +7 -7
  388. package/dist/plugin-sdk/agent-runtime.js +2 -2
  389. package/dist/plugin-sdk/channel-core.js +2 -2
  390. package/dist/plugin-sdk/channel-inbound.js +2 -2
  391. package/dist/plugin-sdk/channel-test-helpers.js +1 -1
  392. package/dist/plugin-sdk/command-auth.js +1 -1
  393. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  394. package/dist/plugin-sdk/compat.js +1 -1
  395. package/dist/plugin-sdk/conversation-binding-runtime.js +2 -2
  396. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  397. package/dist/plugin-sdk/core.js +2 -2
  398. package/dist/plugin-sdk/direct-dm.js +1 -1
  399. package/dist/plugin-sdk/gateway-method-runtime.js +1 -1
  400. package/dist/plugin-sdk/health.js +2 -2
  401. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  402. package/dist/plugin-sdk/index.js +1 -1
  403. package/dist/plugin-sdk/mattermost.js +1 -1
  404. package/dist/plugin-sdk/plugin-test-contracts.js +2 -2
  405. package/dist/plugin-sdk/provider-test-contracts.js +4 -4
  406. package/dist/plugin-sdk/reply-runtime.js +4 -4
  407. package/dist/plugin-sdk/testing.js +2 -2
  408. package/dist/plugin-sdk/zalouser.js +1 -1
  409. package/dist/plugin-service-DnZEPBEA.js +1229 -0
  410. package/dist/plugins/runtime/index.js +4 -4
  411. package/dist/policy-CMv5QMPG.js +138 -0
  412. package/dist/policy-CeoP4t9J.js +680 -0
  413. package/dist/prepare.runtime-DZ55JiTt.js +732 -0
  414. package/dist/prepare.runtime.js +1 -1
  415. package/dist/preview-warnings-O08PZRxu.js +392 -0
  416. package/dist/probe-C6w3bP8X.js +682 -0
  417. package/dist/probe-Cs1_X1NA.js +47 -0
  418. package/dist/probe-Cuee_jyM.js +2204 -0
  419. package/dist/probe-DZxCnDzn.js +2 -0
  420. package/dist/program-C2dT8VHB.js +131 -0
  421. package/dist/provider-C2_vSzYh.js +32 -0
  422. package/dist/provider-DSfTDQbj.js +152 -0
  423. package/dist/provider-U8hrm9h-.js +32 -0
  424. package/dist/provider-_v910H8y.js +8735 -0
  425. package/dist/provider-dispatcher-C3kmmIEC.js +22 -0
  426. package/dist/provider-dispatcher.runtime.js +1 -1
  427. package/dist/provider-session.runtime-Mg0fx5hH.js +9 -0
  428. package/dist/provider-session.runtime.js +1 -1
  429. package/dist/provider.runtime-pSTXuHrq.js +2 -0
  430. package/dist/provider.runtime.js +1 -1
  431. package/dist/public-surface-loader-09t4TTue.js +114 -0
  432. package/dist/pw-ai-DjNqHV3_.js +3029 -0
  433. package/dist/pw-role-snapshot-DoGefdv7.js +333 -0
  434. package/dist/reaction-level-C8Mqxizo.js +19 -0
  435. package/dist/reaction-runtime-api-DOP6xOsm.js +116 -0
  436. package/dist/realtime-transcription-provider-BTGEXXna.js +205 -0
  437. package/dist/register-CbZPpqI3.js +2178 -0
  438. package/dist/register.agent-DrBFuPKh.js +156 -0
  439. package/dist/register.crestodian-DwTbmaK8.js +24 -0
  440. package/dist/register.maintenance-BIeoYBub.js +83 -0
  441. package/dist/register.runtime-B5V9_Dwz.js +54 -0
  442. package/dist/register.subclis-CJE9ISZY.js +31 -0
  443. package/dist/register.subclis-YQsKas8N.js +3 -0
  444. package/dist/register.subclis-core-CjwdGeGU.js +273 -0
  445. package/dist/repair-sequencing-C0jrL5pw.js +640 -0
  446. package/dist/reply-delivery-B28mTIpb.js +196 -0
  447. package/dist/reply-runtime-BqQX7HHw.js +11 -0
  448. package/dist/reply.runtime-C95MG73O.js +2 -0
  449. package/dist/reply.runtime.js +1 -1
  450. package/dist/request-BqoMvXxH.js +54 -0
  451. package/dist/resolve-allowlist-hbKKd_kq.js +220 -0
  452. package/dist/result-fallback-classifier-BrORPoxj.js +79 -0
  453. package/dist/route-HHRgSzVy.js +469 -0
  454. package/dist/route-resolution-C7bafjVc.js +274 -0
  455. package/dist/routes-86XGeo7a.js +2 -0
  456. package/dist/routes-BhVGr9ie.js +3602 -0
  457. package/dist/run-Bb5QP5JV.js +1162 -0
  458. package/dist/run-attempt-CLi0wV7j.js +7704 -0
  459. package/dist/run-command-Be6GAxiW.js +2 -0
  460. package/dist/run-command-Ds4hr3iU.js +23 -0
  461. package/dist/run-embedded.runtime-wX9ORojX.js +4 -0
  462. package/dist/run-embedded.runtime.js +1 -1
  463. package/dist/run-execution-cli.runtime-BmNZVB2N.js +4 -0
  464. package/dist/run-execution-cli.runtime.js +1 -1
  465. package/dist/run-executor.runtime.js +1 -1
  466. package/dist/run-subagent-registry.runtime-Uq5sjftu.js +2 -0
  467. package/dist/run-subagent-registry.runtime.js +1 -1
  468. package/dist/runtime-BktLQ75j.js +1287 -0
  469. package/dist/runtime-C9XdR62_.js +438 -0
  470. package/dist/runtime-CTvWDPx9.js +6179 -0
  471. package/dist/runtime-api-BojB3MUw.js +21 -0
  472. package/dist/runtime-api-C92MlAwp.js +13 -0
  473. package/dist/runtime-api-CFNZE9Xt.js +13 -0
  474. package/dist/runtime-api-Cimpgm5_.js +3 -0
  475. package/dist/runtime-api-D8qG_lUm.js +17 -0
  476. package/dist/runtime-api-DMDMnQEG.js +4 -0
  477. package/dist/runtime-api-DupQdIlE.js +24 -0
  478. package/dist/runtime-api.actions-B8i3elqu.js +3 -0
  479. package/dist/runtime-api.monitor-BntFzf_M.js +6 -0
  480. package/dist/runtime-api.send-CPlmi1jc.js +4 -0
  481. package/dist/runtime-api.threads-D-H_r_Nl.js +2 -0
  482. package/dist/runtime-channel-BGhTxnXZ.js +150 -0
  483. package/dist/runtime-channel-CPFxNapZ.js +2 -0
  484. package/dist/runtime-embedded-pi.runtime-BjnMTurB.js +2 -0
  485. package/dist/runtime-embedded-pi.runtime.js +1 -1
  486. package/dist/sanitize-outbound-BMUv1NeS.js +127 -0
  487. package/dist/sdk-setup-tools-Do3DkQi_.js +8 -0
  488. package/dist/secrets-B8YVPHhk.js +113 -0
  489. package/dist/security-audit-7Gg_nL4o.js +122 -0
  490. package/dist/security-audit-Bk3CREj-.js +118 -0
  491. package/dist/security-audit.runtime-BmSJrdeq.js +2 -0
  492. package/dist/security-audit.runtime.js +1 -1
  493. package/dist/selection-BFGde9-_.js +3 -0
  494. package/dist/selection-DrLFlbgG.js +16157 -0
  495. package/dist/send-4dLa-BQo.js +1631 -0
  496. package/dist/send-CV6gCwYP.js +192 -0
  497. package/dist/send-aGiK3Efu.js +143 -0
  498. package/dist/send-dB3CehAN.js +2 -0
  499. package/dist/send.components-BcG9BlkC.js +2 -0
  500. package/dist/send.components-rLjDlfYU.js +500 -0
  501. package/dist/send.runtime-D20k2MSr.js +2 -0
  502. package/dist/send.runtime.js +1 -1
  503. package/dist/server-BTRx_U1s.js +73 -0
  504. package/dist/server-CY0ymhBg.js +24 -0
  505. package/dist/server-close.runtime.js +1 -1
  506. package/dist/server-context-BxGT8wbK.js +955 -0
  507. package/dist/server-context-DYlbhAaT.js +2 -0
  508. package/dist/server-cron-BB_15lcP.js +2 -0
  509. package/dist/server-cron-CfyJX_a4.js +2989 -0
  510. package/dist/server-methods-Ck2ab6TC.js +16494 -0
  511. package/dist/server-node-events-BdRizF-5.js +596 -0
  512. package/dist/server-plugin-bootstrap-CPUr8NFE.js +70 -0
  513. package/dist/server-plugins-__5AxjzH.js +432 -0
  514. package/dist/server-reload-handlers-BMl9Fx9b.js +714 -0
  515. package/dist/server-restart-sentinel-D11M_ZsH.js +747 -0
  516. package/dist/server-restart-sentinel-DGptQ27c.js +2 -0
  517. package/dist/server-runtime-services-BwtLs-8I.js +2 -0
  518. package/dist/server-runtime-services-aJydixRu.js +267 -0
  519. package/dist/server-startup-plugins-m_P3gY4m.js +113 -0
  520. package/dist/server-startup-post-attach-DuXQ1AXL.js +716 -0
  521. package/dist/server-ws-runtime-mXmxB1W8.js +349 -0
  522. package/dist/server.impl-fuV8aKSP.js +2586 -0
  523. package/dist/service-a8cTFka4.js +1446 -0
  524. package/dist/session-binding-BIycxo9u.js +2 -0
  525. package/dist/session-binding-xHwQr9vM.js +219 -0
  526. package/dist/session-kill-http-DiUZhcoN.js +121 -0
  527. package/dist/session-reset-service-DkepDoob.js +625 -0
  528. package/dist/session-route-Ba5u7ecb.js +93 -0
  529. package/dist/session-status.runtime-Cb1X69Rl.js +2 -0
  530. package/dist/session-status.runtime.js +1 -1
  531. package/dist/session-subagent-reactivation.runtime-rbqmto4G.js +2 -0
  532. package/dist/session-subagent-reactivation.runtime.js +1 -1
  533. package/dist/session-tab-registry-DSKOoJta.js +521 -0
  534. package/dist/sessions-history-http-CWP88I_C.js +430 -0
  535. package/dist/sessions.runtime-1q1OwLn3.js +2 -0
  536. package/dist/sessions.runtime.js +1 -1
  537. package/dist/setup-api-DtrOOYeP.js +29 -0
  538. package/dist/setup-core-DMrJS6LP.js +174 -0
  539. package/dist/setup-surface-BFPNu1qA.js +405 -0
  540. package/dist/setup-surface-CedShqhO.js +288 -0
  541. package/dist/setup-surface-DLOBH1Vf.js +320 -0
  542. package/dist/setup-surface-MhCeEWSj.js +221 -0
  543. package/dist/shared-DamL-e8D.js +121 -0
  544. package/dist/shared-client-B48JoAsz.js +2 -0
  545. package/dist/shared-client-BoSiDnUo.js +629 -0
  546. package/dist/side-question-DQoQ_ETb.js +683 -0
  547. package/dist/skill-tool-dispatch.runtime-CWLloYA8.js +143 -0
  548. package/dist/skill-tool-dispatch.runtime.js +1 -1
  549. package/dist/slash-state-DrrWJQfv.js +2166 -0
  550. package/dist/speech-provider-8Hx1uw41.js +184 -0
  551. package/dist/src-BbUYOPwU.js +4256 -0
  552. package/dist/startup-context-opAJAamX.js +313 -0
  553. package/dist/status-subagents.runtime-DSo7ZK_Z.js +18 -0
  554. package/dist/status-subagents.runtime.js +1 -1
  555. package/dist/status-text-AyPuDzrO.js +296 -0
  556. package/dist/sticker-cache-91Tp8mLP.js +206 -0
  557. package/dist/sticker-vision.runtime-DjleFXi5.js +17 -0
  558. package/dist/sticker-vision.runtime.js +1 -1
  559. package/dist/subagent-announce-delivery-DS_2W9oZ.js +958 -0
  560. package/dist/subagent-announce-hatA_PZ2.js +354 -0
  561. package/dist/subagent-control-IyFIvc7T.js +508 -0
  562. package/dist/subagent-hooks-BCj5eB0Z.js +2 -0
  563. package/dist/subagent-hooks-BWjTBkox.js +146 -0
  564. package/dist/subagent-hooks-CdGLK9_3.js +230 -0
  565. package/dist/subagent-hooks-EH0tBkw9.js +2 -0
  566. package/dist/subagent-hooks-api-BhYaXQJV.js +23 -0
  567. package/dist/subagent-hooks-api-uGsV8Xn5.js +22 -0
  568. package/dist/subagent-hooks-api-wfJFKIPx.js +23 -0
  569. package/dist/subagent-hooks-l8Xd94dt.js +2 -0
  570. package/dist/subagent-hooks-m2eHUO_d.js +116 -0
  571. package/dist/subagent-orphan-recovery-Bq9zvX3L.js +352 -0
  572. package/dist/subagent-registry-Bcb3zy6b.js +3 -0
  573. package/dist/subagent-registry-CoZNTFx-.js +2351 -0
  574. package/dist/subagent-registry.runtime.js +1 -1
  575. package/dist/subagent-session-cleanup--00EjDLe.js +525 -0
  576. package/dist/subagent-spawn-ClJJkz3D.js +1164 -0
  577. package/dist/target-id-BsZLiF3x.js +107 -0
  578. package/dist/targets-CQMe4AZP.js +44 -0
  579. package/dist/targets-SmL1AU-H.js +19 -0
  580. package/dist/targets-Y-roiA47.js +19 -0
  581. package/dist/task-registry-control.runtime.js +1 -1
  582. package/dist/telegram/token.js +1 -1
  583. package/dist/testing-B5hNJDuF.js +267 -0
  584. package/dist/thread-bindings-BD3eE0kK.js +232 -0
  585. package/dist/thread-bindings-C9NNiv8K.js +571 -0
  586. package/dist/thread-bindings-Dl4PN1vZ.js +228 -0
  587. package/dist/thread-bindings-uK1LLAwy.js +8 -0
  588. package/dist/thread-bindings.discord-api-BHNEUbnk.js +187 -0
  589. package/dist/thread-bindings.manager-B0LXiH3F.js +2 -0
  590. package/dist/thread-bindings.manager-BTlH4XMG.js +536 -0
  591. package/dist/thread-lifecycle-DG8uyPHd.js +1614 -0
  592. package/dist/token-BbGCANnE.js +134 -0
  593. package/dist/tool-actions.runtime-oUUrD8HB.js +534 -0
  594. package/dist/tool-actions.runtime.js +1 -1
  595. package/dist/tool-bqg-_vYv.js +139 -0
  596. package/dist/tool-resolution-CSZsa3kP.js +149 -0
  597. package/dist/tools-effective-inventory-0CqFp-vq.js +204 -0
  598. package/dist/tools-invoke-http-DhYHY0Yh.js +67 -0
  599. package/dist/tools-invoke-shared-CbVJJUj7.js +200 -0
  600. package/dist/tts-C2qD-ad6.js +66 -0
  601. package/dist/tui-CzGY254f.js +4709 -0
  602. package/dist/tui-backend-fzoeoSN0.js +256 -0
  603. package/dist/tui-cli-B2RWb2gM.js +37 -0
  604. package/dist/tui-dgS8hdXU.js +2 -0
  605. package/dist/update-cli-BmiBDf3c.js +3664 -0
  606. package/dist/update-runner-CM7QVX6u.js +2379 -0
  607. package/dist/vision-tools-BzoBZnIc.js +1409 -0
  608. package/dist/web-search-DmfOd66S.js +62 -0
  609. package/dist/web-search-provider.runtime-3C5-pODD.js +328 -0
  610. package/dist/web-search-provider.runtime-Doh-Z9We.js +2 -0
  611. package/dist/web-search-provider.runtime.js +1 -1
  612. package/dist/xai-oauth-BLvQ43hx.js +479 -0
  613. package/dist/xai-user-agent-BdMQ_0_O.js +32 -0
  614. package/package.json +1 -1
  615. package/dist/abort-DeEb_wKd.js +0 -277
  616. package/dist/abort.runtime-CoYXQGPK.js +0 -2
  617. package/dist/account-inspect-D_06-CYS.js +0 -173
  618. package/dist/accounts-BCTqtj4Y.js +0 -107
  619. package/dist/accounts-BudLl8P2.js +0 -107
  620. package/dist/accounts-CUReBDA0.js +0 -2
  621. package/dist/accounts-PCioSzzr.js +0 -119
  622. package/dist/acp-runtime-B2t9_BHD.js +0 -26
  623. package/dist/acp-spawn-0x4Iiu1o.js +0 -2
  624. package/dist/acp-spawn-B2Ghe0jJ.js +0 -1275
  625. package/dist/acp-stateful-target-driver-C4VgcSyz.js +0 -89
  626. package/dist/action-kill-ClYsXEz7.js +0 -33
  627. package/dist/action-runtime-DrLPkNvU.js +0 -469
  628. package/dist/action-runtime-api-BqSflr9q.js +0 -2
  629. package/dist/action-send-CIy9cziD.js +0 -39
  630. package/dist/action-spawn-BjV6lFnX.js +0 -47
  631. package/dist/actions-D-QH7wq5.js +0 -161
  632. package/dist/actions.runtime-hzDtXQGU.js +0 -5
  633. package/dist/agent-Bb1DTBgv.js +0 -3
  634. package/dist/agent-Cnqj258q.js +0 -2
  635. package/dist/agent-command-BRx6ZNgJ.js +0 -1367
  636. package/dist/agent-components.runtime-D-g6xXJ0.js +0 -10
  637. package/dist/agent-harness-runtime-dKUQFuOc.js +0 -180
  638. package/dist/agent-harness-task-runtime-v2crUm3i.js +0 -140
  639. package/dist/agent-runner-execution-AOzdxvWR.js +0 -1713
  640. package/dist/agent-runner-utils-Byv50B4Z.js +0 -266
  641. package/dist/agent-runner.runtime-hhgRE0Z-.js +0 -3455
  642. package/dist/agent-runtime-BHmh3i0o.js +0 -229
  643. package/dist/agent-via-gateway-DnCqaK4a.js +0 -463
  644. package/dist/api-Bzyb8sFU.js +0 -3
  645. package/dist/api-CIEDFXZs.js +0 -2
  646. package/dist/api-D_dTQAu8.js +0 -2
  647. package/dist/api-DilBjZ9Q.js +0 -6
  648. package/dist/api-E5zoQMmh.js +0 -134
  649. package/dist/api-OJZug8gQ.js +0 -639
  650. package/dist/apply-C0eV5T0O.js +0 -41
  651. package/dist/apply-alsYvxLE.js +0 -54
  652. package/dist/approval-handler.runtime-C6jqZXSN.js +0 -130
  653. package/dist/assistant-DDXnAAB5.js +0 -291
  654. package/dist/attachment-normalize-Cv-_4DWU.js +0 -225
  655. package/dist/attempt-execution-DECEU59r.js +0 -558
  656. package/dist/attempt-execution.runtime-kasMxuER.js +0 -3
  657. package/dist/attempt-execution.shared-ClUxk52p.js +0 -38
  658. package/dist/attempt.prompt-helpers-Bxlv9VSu.js +0 -475
  659. package/dist/attempt.tool-run-context-CplQWX6g.js +0 -2094
  660. package/dist/binding-routing-0Obpp-Ij.js +0 -113
  661. package/dist/binding-targets-CZHQaZL4.js +0 -121
  662. package/dist/bot-BPbQ0840.js +0 -7894
  663. package/dist/bot-deps-Cs1M9USs.js +0 -2
  664. package/dist/bot-deps-xAcaOtTZ.js +0 -747
  665. package/dist/bot-message-context.runtime-Bji78Cbn.js +0 -7
  666. package/dist/bot-message-context.session.runtime-C3dyOIYH.js +0 -12
  667. package/dist/bot-native-commands.delivery.runtime-WshH99fy.js +0 -4
  668. package/dist/bot-native-commands.runtime-C1L364gU.js +0 -13
  669. package/dist/bridge-server-DPlM8_Lk.js +0 -113
  670. package/dist/browser-cli-DFNQE98N.js +0 -230
  671. package/dist/browser-cli-Drb5E5--.js +0 -2
  672. package/dist/browser-cli-actions-input-Dx-1OXmE.js +0 -473
  673. package/dist/browser-cli-actions-observe-BMDfE7xU.js +0 -81
  674. package/dist/browser-cli-debug-nu7Ih09g.js +0 -137
  675. package/dist/browser-cli-inspect-D5X2wohg.js +0 -104
  676. package/dist/browser-cli-manage-DkzYwph4.js +0 -443
  677. package/dist/browser-cli-resize-B30Avedl.js +0 -26
  678. package/dist/browser-cli-shared-cMgQoQzF.js +0 -50
  679. package/dist/browser-cli-state-CQLDvDy7.js +0 -337
  680. package/dist/browser-control-auth-D7ArmHUt.js +0 -2
  681. package/dist/browser-profiles-B39SIZNb.js +0 -2
  682. package/dist/browser-runtime-DUbSAOOS.js +0 -384
  683. package/dist/build-D25KqC92.js +0 -257
  684. package/dist/capability-cli-CuyXrlAB.js +0 -1782
  685. package/dist/channel-0N3YGMGg.js +0 -1496
  686. package/dist/channel-1UyKoLyp.js +0 -481
  687. package/dist/channel-BG87pSEW.js +0 -740
  688. package/dist/channel-BPGSaZW7.js +0 -1249
  689. package/dist/channel-BQMPh1J_.js +0 -376
  690. package/dist/channel-Bd_8V6zn.js +0 -1134
  691. package/dist/channel-BtBjh_ij.js +0 -362
  692. package/dist/channel-CpFBlVH6.js +0 -562
  693. package/dist/channel-CwuTrIrF.js +0 -508
  694. package/dist/channel-Cxl4sJA-.js +0 -1777
  695. package/dist/channel-D-VfU4Z2.js +0 -2126
  696. package/dist/channel-D9q8aYrN.js +0 -867
  697. package/dist/channel-DKSvVvZh.js +0 -238
  698. package/dist/channel-DvoFfWLx.js +0 -808
  699. package/dist/channel-GktTcGHm.js +0 -955
  700. package/dist/channel-actions.runtime-CKcRA0GW.js +0 -265
  701. package/dist/channel-core-nm8s1qFZ.js +0 -5
  702. package/dist/channel-d3t2ESlE.js +0 -653
  703. package/dist/channel-inbound-DKz40dq-.js +0 -80
  704. package/dist/channel-plugin-runtime-DKIGZWfW.js +0 -998
  705. package/dist/channel-runtime-Bh8_GY12.js +0 -408
  706. package/dist/channel-yQ8jCOb9.js +0 -1556
  707. package/dist/channel.runtime-BG4mM5cQ.js +0 -652
  708. package/dist/channel.runtime-BS6PyFFa.js +0 -1008
  709. package/dist/channel.runtime-CE_xECqN.js +0 -88
  710. package/dist/channel.runtime-Cd1Sw8U4.js +0 -254
  711. package/dist/channel.runtime-DIq3XOEe.js +0 -733
  712. package/dist/channel.runtime-Dy1cx35I.js +0 -21009
  713. package/dist/channel.runtime-NyIMjLnP.js +0 -109
  714. package/dist/channel.runtime-Zx5mfE2V.js +0 -4
  715. package/dist/channel.runtime-rJRibGfN.js +0 -2528
  716. package/dist/channel.setup--4ACadmF.js +0 -10
  717. package/dist/channel.setup-DzwqIlo3.js +0 -1098
  718. package/dist/channel.setup-FKYSJwXR.js +0 -343
  719. package/dist/chat-CKxSm7r1.js +0 -2666
  720. package/dist/chrome-rMubJwRG.js +0 -1503
  721. package/dist/cli-CbTod55I.js +0 -1341
  722. package/dist/cli-compaction-BbHgjJyW.js +0 -347
  723. package/dist/cli-metadata-DkOWLC_p.js +0 -22
  724. package/dist/cli-runner-Cwzv_RKf.js +0 -540
  725. package/dist/cli-runner-DdnUsgPl.js +0 -2
  726. package/dist/cli-runner.runtime-BlrSgbEW.js +0 -3
  727. package/dist/cli-runner.runtime-D8kVfvFH.js +0 -4
  728. package/dist/client-ClvxsWgL.js +0 -650
  729. package/dist/client-adapter-CsrIIjK1.js +0 -897
  730. package/dist/client-factory-DAYClhwm.js +0 -9
  731. package/dist/command-auth-CCha2ofd.js +0 -135
  732. package/dist/command-handlers-DCWJzHyB.js +0 -1609
  733. package/dist/command-registry-BIf61QNz.js +0 -9
  734. package/dist/command-registry-DJROBy4h.js +0 -4
  735. package/dist/command-registry-core-BQOWqi6S.js +0 -110
  736. package/dist/command-status.runtime-D88CUglL.js +0 -90
  737. package/dist/commands-acp-B-8dHX4Z.js +0 -74
  738. package/dist/commands-compact.runtime-ComX5mUk.js +0 -10
  739. package/dist/commands-handlers.runtime-DR3wjXHX.js +0 -6154
  740. package/dist/commands-status-CDyGrwsI.js +0 -3
  741. package/dist/commands-status-DV-i_ZIK.js +0 -16
  742. package/dist/commands-status.runtime-CDyGrwsI.js +0 -3
  743. package/dist/commands-subagents-control.runtime-B029cXAS.js +0 -3
  744. package/dist/commands-subagents-control.runtime-DR8Qspe0.js +0 -2
  745. package/dist/commands-system-prompt-C10ctsG3.js +0 -162
  746. package/dist/commands-system-prompt-DQlRWwnk.js +0 -2
  747. package/dist/commands.runtime-BYmIAuN0.js +0 -176
  748. package/dist/compact-14Ljaaeu.js +0 -480
  749. package/dist/compact-B--ovdkx.js +0 -1141
  750. package/dist/compact.runtime-E0Idf2Dq.js +0 -12
  751. package/dist/completion-cli-DMvvQGSk.js +0 -315
  752. package/dist/computer-use-CcLwX5SR.js +0 -367
  753. package/dist/config-B39SIZNb.js +0 -2
  754. package/dist/config-D4rsGOyV.js +0 -373
  755. package/dist/config-mutations-CsI3YJu7.js +0 -159
  756. package/dist/context-engine-host-compat-BZpDFiMJ.js +0 -2
  757. package/dist/context-engine-host-compat-runUdES5.js +0 -288
  758. package/dist/context-engine-lifecycle-D6odtNrn.js +0 -1274
  759. package/dist/control-auth-BPGpPtfz.js +0 -114
  760. package/dist/control-service-C-OmdPCe.js +0 -145
  761. package/dist/control-ui/assets/agents-GeyOHPuW.js +0 -1008
  762. package/dist/control-ui/assets/channel-config-extras-D7en6iUg.js +0 -2
  763. package/dist/control-ui/assets/channels-DkEyr1w5.js +0 -367
  764. package/dist/control-ui/assets/cron-C-wThQ1Q.js +0 -1013
  765. package/dist/control-ui/assets/debug-83AFRtIX.js +0 -97
  766. package/dist/control-ui/assets/index-CiGEhMOA.js +0 -7370
  767. package/dist/control-ui/assets/instances-CVl0t-1h.js +0 -57
  768. package/dist/control-ui/assets/logs-eybVEXxg.js +0 -74
  769. package/dist/control-ui/assets/nodes-C_A7eoU2.js +0 -436
  770. package/dist/control-ui/assets/sessions-Cq4Nc69u.js +0 -399
  771. package/dist/control-ui/assets/skills-ZN6hroIh.js +0 -314
  772. package/dist/control-ui/assets/skills-shared-DIWGwmdC.js +0 -11
  773. package/dist/conversation-binding-runtime-C2U1JElL.js +0 -4
  774. package/dist/conversation-runtime-NmIUd3Zu.js +0 -31
  775. package/dist/core-DGKJP1dm.js +0 -282
  776. package/dist/core-api-1fA4sNeC.js +0 -5
  777. package/dist/core-api-BY822Quq.js +0 -2
  778. package/dist/crestodian-Bp-NXiBC.js +0 -55
  779. package/dist/daocore-tools-Defpam0j.js +0 -11727
  780. package/dist/delivery-CEdVAUGB.js +0 -1002
  781. package/dist/dialogue-CZ69INPq.js +0 -37
  782. package/dist/dir-fetch-tool-BCicHhQE.js +0 -565
  783. package/dist/dir-list-tool-Cv_WktsJ.js +0 -100
  784. package/dist/direct-dm-Bz89rM8x.js +0 -64
  785. package/dist/directive-handling.fast-lane-DDnbcc5S.js +0 -68
  786. package/dist/directive-handling.impl-B0H52Ymr.js +0 -818
  787. package/dist/directive-handling.impl-CgKpwEW-.js +0 -2
  788. package/dist/directive-handling.model-selection-_cXAr0vt.js +0 -122
  789. package/dist/directive-handling.persist.runtime-Dw0mfzXT.js +0 -263
  790. package/dist/dispatch-C3AeYvyP.js +0 -1640
  791. package/dist/dispatch-acp-transcript.runtime-CP8pqBwS.js +0 -40
  792. package/dist/dispatch-acp.runtime-Cdap-AZI.js +0 -18
  793. package/dist/doctor-BZwVH97p.js +0 -2
  794. package/dist/doctor-BfkGBii1.js +0 -6
  795. package/dist/doctor-config-flow-D3JASGDt.js +0 -1741
  796. package/dist/doctor-core-checks-DH5AIT0Q.js +0 -573
  797. package/dist/doctor-core-checks-DiNu7VSh.js +0 -2
  798. package/dist/doctor-health-BDIJ-Nro.js +0 -65
  799. package/dist/doctor-health-contributions-BgmF7w8X.js +0 -696
  800. package/dist/doctor-lint-uIxkMUSO.js +0 -94
  801. package/dist/doctor-state-integrity-ws1b_BGk.js +0 -1231
  802. package/dist/doctor-update-Cx4CqxaX.js +0 -58
  803. package/dist/dynamic-tools-DiqOxhJh.js +0 -486
  804. package/dist/embedded-backend-C634irMl.js +0 -579
  805. package/dist/embedded-gateway-stub.runtime-CCfrTOeN.js +0 -12
  806. package/dist/exec-approvals-D85KThSg.js +0 -149
  807. package/dist/file-fetch-tool-BERaGYCT.js +0 -124
  808. package/dist/file-write-tool-BjHrMyfe.js +0 -127
  809. package/dist/format-DE9PuPg1.js +0 -1145
  810. package/dist/gateway-cli-B5hjhbUy.js +0 -435
  811. package/dist/gateway-method-runtime-Bu0E9Eki.js +0 -21
  812. package/dist/get-reply-6PtPz9hv.js +0 -4689
  813. package/dist/get-reply-from-config.runtime-CwprvhoR.js +0 -2
  814. package/dist/graph-users-DUp1kgnS.js +0 -1419
  815. package/dist/group-access-D5GBQ3w6.js +0 -112
  816. package/dist/handle-action.guild-admin-CA0Y-buD.js +0 -288
  817. package/dist/harness-B5nOFVfm.js +0 -61
  818. package/dist/health-D5heIDj3.js +0 -4
  819. package/dist/heartbeat-runner-BzFkIFHh.js +0 -5
  820. package/dist/heartbeat-runner.runtime-p6H1_xMV.js +0 -4
  821. package/dist/hooks-BvTyQ14X.js +0 -534
  822. package/dist/inbound-direct-dm-runtime-DwiDXi8L.js +0 -2
  823. package/dist/inbound-reply-dispatch-YoDUOC6C.js +0 -148
  824. package/dist/init-CPtcV5Xu.js +0 -59
  825. package/dist/inline-buttons-DeD5d42c.js +0 -40
  826. package/dist/internal-events-DEb50Sw3.js +0 -90
  827. package/dist/isolated-agent-CcxFFZ-Z.js +0 -1118
  828. package/dist/isolated-agent-CpHzq5qr.js +0 -2
  829. package/dist/lifecycle-DNel-oMe.js +0 -571
  830. package/dist/list.probe-DCa3N25d.js +0 -449
  831. package/dist/list.status-command-CyeAJmZW.js +0 -789
  832. package/dist/llm-slug-generator-CyqTY37Z.js +0 -78
  833. package/dist/local-dispatch.runtime-nE39kFIP.js +0 -9
  834. package/dist/manager.runtime-CpAPB8D5.js +0 -2714
  835. package/dist/markdown-to-line-Ci6TRmoZ.js +0 -811
  836. package/dist/mcp-http-BR0vmxFL.js +0 -2
  837. package/dist/mcp-http-C0oniA8h.js +0 -555
  838. package/dist/media-understanding-provider-BwA0XqC3.js +0 -339
  839. package/dist/message-actions-C9C_Ngkd.js +0 -145
  840. package/dist/message-handler-CUUKPC5n.js +0 -384
  841. package/dist/message-handler-xRTfIXWV.js +0 -1715
  842. package/dist/message-handler.preflight-Ch2Q7V3M.js +0 -1125
  843. package/dist/message-handler.process-HM3mK93q.js +0 -1484
  844. package/dist/model-CB8Ex5xS.js +0 -74
  845. package/dist/model-selection-2s0Dinux.js +0 -272
  846. package/dist/models-Cn-6DJ41.js +0 -2
  847. package/dist/models-CzszJD__.js +0 -104
  848. package/dist/models-cli-CbhElnA5.js +0 -256
  849. package/dist/monitor-7aprTsMV.js +0 -715
  850. package/dist/monitor-BuVhqwDS.js +0 -1370
  851. package/dist/monitor-C4H_YkgY.js +0 -2
  852. package/dist/monitor-CPQsMxgv.js +0 -1657
  853. package/dist/monitor-Ce0V1PiR.js +0 -4377
  854. package/dist/monitor-D0bcGJWI.js +0 -60
  855. package/dist/monitor-DEjlJqzh.js +0 -834
  856. package/dist/monitor-auth-DjJZsjgV.js +0 -179
  857. package/dist/monitor-ikSYagv3.js +0 -2788
  858. package/dist/monitor-polling.runtime-D7yEflMM.js +0 -883
  859. package/dist/monitor-webhook.runtime-CIZt-biI.js +0 -387
  860. package/dist/monitor.account-C2sMOBCS.js +0 -5233
  861. package/dist/monitor.runtime-BAi6zmcn.js +0 -2
  862. package/dist/monitor.webhook-BcjpfRCX.js +0 -180
  863. package/dist/node-cli-sessions-CIhkJRU4.js +0 -1228
  864. package/dist/openai-http-Dj21RwSj.js +0 -824
  865. package/dist/openresponses-http-COnnr1ox.js +0 -1173
  866. package/dist/operations-H3vUh0lM.js +0 -805
  867. package/dist/outbound-adapter-WLtWE7wv.js +0 -543
  868. package/dist/outbound-session-route-CZtd64EH.js +0 -45
  869. package/dist/outbound.runtime-D98P0sN1.js +0 -2
  870. package/dist/pi-embedded-BWJzd4mK.js +0 -4
  871. package/dist/pi-embedded-DeNsSqQQ.js +0 -3796
  872. package/dist/pi-embedded.runtime-CZnNwFpc.js +0 -4
  873. package/dist/pi-tools-CNHSpjBa.js +0 -2413
  874. package/dist/plan-B0reFFlM.js +0 -81
  875. package/dist/plan-CrfF-TH8.js +0 -112
  876. package/dist/plugin-DI_8eYOe.js +0 -12396
  877. package/dist/plugin-app-cache-key-WaTUD3e-.js +0 -46
  878. package/dist/plugin-enabled-aWLXgGGi.js +0 -233
  879. package/dist/plugin-registration-ByjRIVJm.js +0 -88
  880. package/dist/plugin-service-VQm_241d.js +0 -1229
  881. package/dist/policy-BmJH-swe.js +0 -680
  882. package/dist/policy-DE-bO1zn.js +0 -138
  883. package/dist/prepare.runtime-bSj3-res.js +0 -732
  884. package/dist/preview-warnings-CbuGYsF9.js +0 -392
  885. package/dist/probe-C_rWg7_m.js +0 -682
  886. package/dist/probe-CagOFfx6.js +0 -2
  887. package/dist/probe-thX1HqOh.js +0 -2204
  888. package/dist/probe-zU6B6gFt.js +0 -47
  889. package/dist/program-BtVdH743.js +0 -131
  890. package/dist/provider-CDoD7tO0.js +0 -8735
  891. package/dist/provider-CK1gMdJ2.js +0 -32
  892. package/dist/provider-DJqr9djy.js +0 -32
  893. package/dist/provider-DsOJp5bK.js +0 -152
  894. package/dist/provider-dispatcher-UNQ-LSx9.js +0 -22
  895. package/dist/provider-session.runtime-DMrkMb4x.js +0 -9
  896. package/dist/provider.runtime-C2-t3zm8.js +0 -2
  897. package/dist/public-surface-loader-hTeyyHcd.js +0 -114
  898. package/dist/pw-ai-BaL3eVYx.js +0 -3029
  899. package/dist/pw-role-snapshot-DKeBqhN1.js +0 -333
  900. package/dist/reaction-level-BV2potsD.js +0 -19
  901. package/dist/reaction-runtime-api-CCBxgM10.js +0 -116
  902. package/dist/realtime-transcription-provider-CHYtIXZm.js +0 -205
  903. package/dist/register-BJf28G9B.js +0 -2178
  904. package/dist/register.agent-oXAHwNQv.js +0 -156
  905. package/dist/register.crestodian-CQ0sqdV2.js +0 -24
  906. package/dist/register.maintenance-CylVRs5M.js +0 -83
  907. package/dist/register.runtime-CcDgwy0X.js +0 -54
  908. package/dist/register.subclis-CpBYNw2X.js +0 -3
  909. package/dist/register.subclis-N2CvieOL.js +0 -31
  910. package/dist/register.subclis-core-BHaGvbzg.js +0 -273
  911. package/dist/repair-sequencing-EBBnBdIB.js +0 -640
  912. package/dist/reply-delivery-BLoPALlI.js +0 -196
  913. package/dist/reply-runtime-D4asNTSa.js +0 -11
  914. package/dist/reply.runtime-CwprvhoR.js +0 -2
  915. package/dist/request-DlWPRUDt.js +0 -54
  916. package/dist/resolve-allowlist-BukQf58x.js +0 -220
  917. package/dist/result-fallback-classifier-DyHFnqfV.js +0 -79
  918. package/dist/route-BMf4keN5.js +0 -469
  919. package/dist/route-resolution-DWNi1QAu.js +0 -274
  920. package/dist/routes-C20LC8c4.js +0 -3602
  921. package/dist/routes-CkK7Vv_m.js +0 -2
  922. package/dist/run-KDF_AEza.js +0 -1162
  923. package/dist/run-attempt-JHYCfonU.js +0 -7704
  924. package/dist/run-command-3PVihYIy.js +0 -2
  925. package/dist/run-command-QHAXnyKY.js +0 -23
  926. package/dist/run-embedded.runtime-BJw-2vss.js +0 -4
  927. package/dist/run-execution-cli.runtime-GHClMn2g.js +0 -4
  928. package/dist/run-subagent-registry.runtime-BLLMrhtE.js +0 -2
  929. package/dist/runtime-C2u-dC1r.js +0 -1287
  930. package/dist/runtime-ClyfkDWT.js +0 -6179
  931. package/dist/runtime-WXCarlPc.js +0 -438
  932. package/dist/runtime-api-3QhGLpZf.js +0 -13
  933. package/dist/runtime-api-DRAu3mjv.js +0 -4
  934. package/dist/runtime-api-JE07pOem.js +0 -13
  935. package/dist/runtime-api-JuKylHvw.js +0 -24
  936. package/dist/runtime-api-bcbk4yax.js +0 -21
  937. package/dist/runtime-api-dDe9U2_V.js +0 -17
  938. package/dist/runtime-api-uMexLqGS.js +0 -3
  939. package/dist/runtime-api.actions-Bo7TLDFl.js +0 -3
  940. package/dist/runtime-api.monitor-7q78L1Em.js +0 -6
  941. package/dist/runtime-api.send-Bf9RR4nV.js +0 -4
  942. package/dist/runtime-api.threads-Dj2QuhHj.js +0 -2
  943. package/dist/runtime-channel-k1C0Satl.js +0 -2
  944. package/dist/runtime-channel-qt9t0J-J.js +0 -150
  945. package/dist/runtime-embedded-pi.runtime-BPB9NlTS.js +0 -2
  946. package/dist/sanitize-outbound-BLH_SQvg.js +0 -127
  947. package/dist/sdk-setup-tools-BshlBPau.js +0 -8
  948. package/dist/secrets-CsHXv7d3.js +0 -113
  949. package/dist/security-audit-CUXBQXNX.js +0 -122
  950. package/dist/security-audit-CzdXbRma.js +0 -118
  951. package/dist/security-audit.runtime-Ca0FMFJG.js +0 -2
  952. package/dist/selection-BmvQJlSD.js +0 -3
  953. package/dist/selection-BplDXc9w.js +0 -16157
  954. package/dist/send--qFg8a9v.js +0 -1631
  955. package/dist/send-BPdryPPA.js +0 -192
  956. package/dist/send-Bl4YaRkS.js +0 -143
  957. package/dist/send-Ccm7RMXC.js +0 -2
  958. package/dist/send.components-c3OUPSmR.js +0 -2
  959. package/dist/send.components-rhQJYoXs.js +0 -500
  960. package/dist/send.runtime-dfUkAp5d.js +0 -2
  961. package/dist/server-DRhyTMLe.js +0 -73
  962. package/dist/server-Dv4BzjGn.js +0 -24
  963. package/dist/server-context-4HRJy2vp.js +0 -955
  964. package/dist/server-context-DlxYb1G5.js +0 -2
  965. package/dist/server-cron-Bt8Pkc3i.js +0 -2989
  966. package/dist/server-cron-CtNWsa4Z.js +0 -2
  967. package/dist/server-methods-rye_okUW.js +0 -16494
  968. package/dist/server-node-events-C1yZ5a1u.js +0 -596
  969. package/dist/server-plugin-bootstrap-DUMyVtlP.js +0 -70
  970. package/dist/server-plugins-B5ZWWkRE.js +0 -432
  971. package/dist/server-reload-handlers-CTnMXNjT.js +0 -714
  972. package/dist/server-restart-sentinel-CAYxtwmY.js +0 -747
  973. package/dist/server-restart-sentinel-DqrtSIvy.js +0 -2
  974. package/dist/server-runtime-services-CuptQTe5.js +0 -2
  975. package/dist/server-runtime-services-aaS2IiW3.js +0 -267
  976. package/dist/server-startup-plugins-D0ymJgQT.js +0 -113
  977. package/dist/server-startup-post-attach-DlrN2uyt.js +0 -716
  978. package/dist/server-ws-runtime-CdpLbv4o.js +0 -349
  979. package/dist/server.impl-Cb4qcMTg.js +0 -2586
  980. package/dist/service-qxvDlMQE.js +0 -1446
  981. package/dist/session-binding-6bLobLHL.js +0 -219
  982. package/dist/session-binding-Bm6fCpoY.js +0 -2
  983. package/dist/session-kill-http-B6WjVo8V.js +0 -121
  984. package/dist/session-reset-service-GUVIhxp4.js +0 -625
  985. package/dist/session-route-BcRDnvzG.js +0 -93
  986. package/dist/session-status.runtime-BcjOunV4.js +0 -2
  987. package/dist/session-subagent-reactivation.runtime-BSmk_KYn.js +0 -2
  988. package/dist/session-tab-registry-BBYzbSOu.js +0 -521
  989. package/dist/sessions-history-http-bLJJfgLm.js +0 -430
  990. package/dist/sessions.runtime-DNRtQzCk.js +0 -2
  991. package/dist/setup-api-CcolVVJs.js +0 -29
  992. package/dist/setup-core-eJD18F3B.js +0 -174
  993. package/dist/setup-surface-B75C2Qtz.js +0 -221
  994. package/dist/setup-surface-CFuPfVHp.js +0 -405
  995. package/dist/setup-surface-Dyy-Mzyz.js +0 -288
  996. package/dist/setup-surface-ZsVF_g8W.js +0 -320
  997. package/dist/shared-BkCNrcLX.js +0 -121
  998. package/dist/shared-client-B7zqC9p2.js +0 -2
  999. package/dist/shared-client-yXjKgZBz.js +0 -629
  1000. package/dist/side-question-DU3gESCb.js +0 -683
  1001. package/dist/skill-tool-dispatch.runtime-CPBuqyvk.js +0 -143
  1002. package/dist/slash-state-Do3bAahA.js +0 -2166
  1003. package/dist/speech-provider-Bg9los3C.js +0 -184
  1004. package/dist/src-D7LzUctH.js +0 -4256
  1005. package/dist/startup-context-CCF2gIOl.js +0 -313
  1006. package/dist/status-subagents.runtime-DX5FTymp.js +0 -18
  1007. package/dist/status-text-B-1u5dSV.js +0 -296
  1008. package/dist/sticker-cache-DwpU_9RJ.js +0 -206
  1009. package/dist/sticker-vision.runtime-Bbldi_YL.js +0 -17
  1010. package/dist/subagent-announce-BCo0VHVL.js +0 -354
  1011. package/dist/subagent-announce-delivery-JcnuDN_N.js +0 -958
  1012. package/dist/subagent-control-BzbA3Suz.js +0 -508
  1013. package/dist/subagent-hooks-BIGZQWrG.js +0 -2
  1014. package/dist/subagent-hooks-Bj4qYZfv.js +0 -230
  1015. package/dist/subagent-hooks-C-rvhVBv.js +0 -2
  1016. package/dist/subagent-hooks-P01_AFl5.js +0 -116
  1017. package/dist/subagent-hooks-VEfak8nl.js +0 -2
  1018. package/dist/subagent-hooks-api-BPnSxxN4.js +0 -23
  1019. package/dist/subagent-hooks-api-DwIAvMoS.js +0 -22
  1020. package/dist/subagent-hooks-api-kgyR9FOb.js +0 -23
  1021. package/dist/subagent-hooks-oED56wqq.js +0 -146
  1022. package/dist/subagent-orphan-recovery-D79ZzwKN.js +0 -352
  1023. package/dist/subagent-registry-D0soBT5j.js +0 -2351
  1024. package/dist/subagent-registry-DRJDkmty.js +0 -3
  1025. package/dist/subagent-session-cleanup-9eAO1aJe.js +0 -525
  1026. package/dist/subagent-spawn-D80vbogm.js +0 -1164
  1027. package/dist/target-id-COLv5LsJ.js +0 -107
  1028. package/dist/targets-CDW5IQ6a.js +0 -44
  1029. package/dist/targets-Ci6O1ZdP.js +0 -19
  1030. package/dist/targets-CsaWFBg1.js +0 -19
  1031. package/dist/testing-BoJit-h1.js +0 -267
  1032. package/dist/thread-bindings-CGCvw0KT.js +0 -571
  1033. package/dist/thread-bindings-ClCTNacX.js +0 -228
  1034. package/dist/thread-bindings-DRb7BMZ6.js +0 -8
  1035. package/dist/thread-bindings-Xc6smav0.js +0 -232
  1036. package/dist/thread-bindings.discord-api-DC467oeF.js +0 -187
  1037. package/dist/thread-bindings.manager-C_mpTDIZ.js +0 -536
  1038. package/dist/thread-bindings.manager-DkCRs612.js +0 -2
  1039. package/dist/thread-lifecycle-DpqCXlx9.js +0 -1614
  1040. package/dist/token-CI6HjbTA.js +0 -134
  1041. package/dist/tool-BMe7hjBK.js +0 -139
  1042. package/dist/tool-actions.runtime-D-h5PI_m.js +0 -534
  1043. package/dist/tool-resolution-CnLx0CHe.js +0 -149
  1044. package/dist/tools-effective-inventory-BR6MUMtE.js +0 -204
  1045. package/dist/tools-invoke-http-CTTs2yMT.js +0 -67
  1046. package/dist/tools-invoke-shared-9B1EjXWf.js +0 -200
  1047. package/dist/tts-eGOviZ5c.js +0 -66
  1048. package/dist/tui-Bw0HqKd7.js +0 -4709
  1049. package/dist/tui-CIZJnPzj.js +0 -2
  1050. package/dist/tui-backend-BJ_r7tcF.js +0 -256
  1051. package/dist/tui-cli-BaSMBpuA.js +0 -37
  1052. package/dist/update-cli-zuCybGNR.js +0 -3664
  1053. package/dist/update-runner-Dek2BHmQ.js +0 -2379
  1054. package/dist/vision-tools-1ps0BEE5.js +0 -1409
  1055. package/dist/web-search-B7EziZXE.js +0 -62
  1056. package/dist/web-search-provider.runtime-DGTCvGch.js +0 -328
  1057. package/dist/web-search-provider.runtime-DWL5t39M.js +0 -2
  1058. package/dist/xai-oauth-CRtsj2Gs.js +0 -479
  1059. package/dist/xai-user-agent-Dndwzw2S.js +0 -32
  1060. /package/dist/{acp-runtime-backend-DSDBcyh9.js → acp-runtime-backend-Cxo7eBHf.js} +0 -0
  1061. /package/dist/{channel-actions-FV66JqtI.js → channel-actions-UDeVjgGz.js} +0 -0
  1062. /package/dist/{command-status-runtime-BRWKSoG7.js → command-status-runtime-CoHd4Fws.js} +0 -0
  1063. /package/dist/{delegate-DGqKhwB4.js → delegate-B-2xZ77o.js} +0 -0
  1064. /package/dist/{dispatch-acp-Ceoxja_Z.js → dispatch-acp-DLPkmK7K.js} +0 -0
  1065. /package/dist/{heartbeat-runner-CJHvr5pG.js → heartbeat-runner-D2j6JwOI.js} +0 -0
  1066. /package/dist/{library-Bq3aDek_.js → library-DBT0cIPP.js} +0 -0
  1067. /package/dist/{run-executor.runtime-DNJhGPbA.js → run-executor.runtime-DE4J7f4M.js} +0 -0
  1068. /package/dist/{shared-CYxmRpq1.js → shared-xeo8Yh5n.js} +0 -0
@@ -0,0 +1,2714 @@
1
+ import { c as normalizeOptionalString } from "./string-coerce-DyL154ka.js";
2
+ import { i as formatErrorMessage } from "./errors-D_oyTIw2.js";
3
+ import { b as escapeRegExp } from "./utils-CNnMhEDp.js";
4
+ import { a as resolveAgentDir } from "./agent-scope-config-CJUQxn7u.js";
5
+ import { n as resolvePreferredDaoCoreTmpDir } from "./tmp-daocore-dir-kDRsiZXM.js";
6
+ import { a as shouldLogVerbose, r as logVerbose } from "./globals-DhGeOA1P.js";
7
+ import { t as createSubsystemLogger } from "./subsystem-CppbuBPw.js";
8
+ import { t as tempWorkspace } from "./private-temp-workspace-C8UPtY2h.js";
9
+ import { i as stripInlineDirectiveTagsForDisplay } from "./directive-tags-CClLEtM7.js";
10
+ import { i as resolveAgentRoute } from "./resolve-route-C0-Q-Gjg.js";
11
+ import "./temp-path-CKL9wgHJ.js";
12
+ import { _ as resolveTtsPrefsPath, g as resolveTtsConfig, o as getTtsProvider } from "./tts-runtime-xVEuik1Y.js";
13
+ import { n as parseTtsDirectives } from "./directives-B-3PBPK5.js";
14
+ import "./runtime-env-BSECk1Nm.js";
15
+ import "./string-coerce-runtime-DcopKqDR.js";
16
+ import "./routing-AC-P99jg.js";
17
+ import "./ssrf-runtime-Gwgbj2qf.js";
18
+ import "./text-chunking-ObhJDe8L.js";
19
+ import "./agent-runtime-BgIT5Ytc.js";
20
+ import { n as agentCommandFromIngress } from "./agent-command-D6Ds198G.js";
21
+ import { n as resolveRealtimeBootstrapContextInstructions } from "./realtime-bootstrap-context-BhQDURYS.js";
22
+ import { A as REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ, _ as resolveRealtimeVoiceAgentConsultToolPolicy, d as buildRealtimeVoiceAgentConsultPolicyInstructions, n as resolveConfiguredRealtimeVoiceProvider, p as buildRealtimeVoiceAgentConsultWorkingResponse, t as createRealtimeVoiceBridgeSession, u as buildRealtimeVoiceAgentConsultChatMessage, v as resolveRealtimeVoiceAgentConsultTools, y as resolveRealtimeVoiceAgentConsultToolsAllow } from "./session-runtime-DtOn7xuW.js";
23
+ import { i as resamplePcm, p as createRealtimeVoiceAgentTalkbackQueue } from "./realtime-voice-yB3UuV8s.js";
24
+ import "./speech-B2PBLmd_.js";
25
+ import "./text-utility-runtime-DMDtY7pX.js";
26
+ import { c as resolveDiscordAccountAllowFrom } from "./accounts-BgsM9h2-.js";
27
+ import { t as parseDiscordTarget } from "./target-parsing-D1FhMbX6.js";
28
+ import { Ct as getGuildVoiceState, It as ChannelType, l as VoiceStateUpdateListener, o as ReadyListener, s as ResumedListener } from "./discord-DLn5dEWC.js";
29
+ import { n as formatDiscordUserTag } from "./format-DZW075F7.js";
30
+ import { a as normalizeDiscordSlug, m as resolveDiscordOwnerAccess } from "./allow-list-BcPKAZym.js";
31
+ import { t as formatMention } from "./mentions-BQeyZvGM.js";
32
+ import { t as getDiscordRuntime } from "./runtime-BMg-o6zJ.js";
33
+ import { t as buildDiscordGroupSystemPrompt } from "./inbound-context-BKozGR57.js";
34
+ import { n as resolveDiscordVoiceEnabled, t as authorizeDiscordVoiceIngress } from "./access-BlVTMtpw.js";
35
+ import { createRequire } from "node:module";
36
+ import path from "node:path";
37
+ import fs from "node:fs/promises";
38
+ import { PassThrough, Readable } from "node:stream";
39
+ //#region extensions/discord/src/voice/audio.ts
40
+ const require = createRequire(import.meta.url);
41
+ const SAMPLE_RATE = 48e3;
42
+ const CHANNELS = 2;
43
+ const BIT_DEPTH = 16;
44
+ let warnedOpusMissing = false;
45
+ let cachedOpusDecoderFactory = "unresolved";
46
+ function buildWavBuffer(pcm) {
47
+ const blockAlign = CHANNELS * BIT_DEPTH / 8;
48
+ const byteRate = SAMPLE_RATE * blockAlign;
49
+ const header = Buffer.alloc(44);
50
+ header.write("RIFF", 0);
51
+ header.writeUInt32LE(36 + pcm.length, 4);
52
+ header.write("WAVE", 8);
53
+ header.write("fmt ", 12);
54
+ header.writeUInt32LE(16, 16);
55
+ header.writeUInt16LE(1, 20);
56
+ header.writeUInt16LE(CHANNELS, 22);
57
+ header.writeUInt32LE(SAMPLE_RATE, 24);
58
+ header.writeUInt32LE(byteRate, 28);
59
+ header.writeUInt16LE(blockAlign, 32);
60
+ header.writeUInt16LE(BIT_DEPTH, 34);
61
+ header.write("data", 36);
62
+ header.writeUInt32LE(pcm.length, 40);
63
+ return Buffer.concat([header, pcm]);
64
+ }
65
+ function resolveOpusDecoderFactory(params) {
66
+ const nativeFactory = {
67
+ name: "@discordjs/opus",
68
+ load: () => {
69
+ return new (require("@discordjs/opus")).OpusEncoder(SAMPLE_RATE, CHANNELS);
70
+ }
71
+ };
72
+ const opusscriptFactory = {
73
+ name: "opusscript",
74
+ load: () => {
75
+ const OpusScript = require("opusscript");
76
+ return new OpusScript(SAMPLE_RATE, CHANNELS, OpusScript.Application.AUDIO);
77
+ }
78
+ };
79
+ const factories = resolveOpusDecoderPreference() === "native" ? [nativeFactory, opusscriptFactory] : [opusscriptFactory, nativeFactory];
80
+ const failures = [];
81
+ for (const factory of factories) try {
82
+ factory.load();
83
+ return factory;
84
+ } catch (err) {
85
+ failures.push(`${factory.name}: ${formatErrorMessage(err)}`);
86
+ }
87
+ if (!warnedOpusMissing) {
88
+ warnedOpusMissing = true;
89
+ params.onWarn(`discord voice: no usable opus decoder available (${failures.join("; ")}); cannot decode voice audio`);
90
+ }
91
+ return null;
92
+ }
93
+ function resolveOpusDecoderPreference(value = process.env.DAOCORE_DISCORD_OPUS_DECODER) {
94
+ const normalized = value?.trim().toLowerCase();
95
+ if (normalized === "native" || normalized === "@discordjs/opus") return "native";
96
+ return "opusscript";
97
+ }
98
+ function getOrCreateOpusDecoderFactory(params) {
99
+ if (cachedOpusDecoderFactory !== "unresolved") return cachedOpusDecoderFactory;
100
+ cachedOpusDecoderFactory = resolveOpusDecoderFactory(params);
101
+ return cachedOpusDecoderFactory;
102
+ }
103
+ function createOpusDecoder(params) {
104
+ const factory = getOrCreateOpusDecoderFactory(params);
105
+ if (!factory) return null;
106
+ return {
107
+ decoder: factory.load(),
108
+ name: factory.name
109
+ };
110
+ }
111
+ async function decodeOpusStream(stream, params) {
112
+ const selected = createOpusDecoder({ onWarn: params.onWarn });
113
+ if (!selected) return Buffer.alloc(0);
114
+ params.onVerbose(`opus decoder: ${selected.name}`);
115
+ const chunks = [];
116
+ try {
117
+ for await (const chunk of stream) {
118
+ if (!chunk || !(chunk instanceof Buffer) || chunk.length === 0) continue;
119
+ const decoded = selected.decoder.decode(chunk);
120
+ if (decoded && decoded.length > 0) chunks.push(Buffer.from(decoded));
121
+ }
122
+ } catch (err) {
123
+ if (shouldLogVerbose()) logVerbose(`discord voice: opus decode failed: ${formatErrorMessage(err)}`);
124
+ }
125
+ return chunks.length > 0 ? Buffer.concat(chunks) : Buffer.alloc(0);
126
+ }
127
+ async function decodeOpusStreamChunks(stream, params) {
128
+ const selected = createOpusDecoder({ onWarn: params.onWarn });
129
+ if (!selected) return;
130
+ params.onVerbose(`opus decoder: ${selected.name}`);
131
+ try {
132
+ for await (const chunk of stream) {
133
+ if (!chunk || !(chunk instanceof Buffer) || chunk.length === 0) continue;
134
+ const decoded = selected.decoder.decode(chunk);
135
+ if (decoded && decoded.length > 0) params.onChunk(Buffer.from(decoded));
136
+ }
137
+ } catch (err) {
138
+ if (shouldLogVerbose()) logVerbose(`discord voice: opus decode failed: ${formatErrorMessage(err)}`);
139
+ }
140
+ }
141
+ function convertDiscordPcm48kStereoToRealtimePcm24kMono(pcm) {
142
+ const frameCount = Math.floor(pcm.length / 4);
143
+ if (frameCount === 0) return Buffer.alloc(0);
144
+ const mono48k = Buffer.alloc(frameCount * 2);
145
+ for (let frame = 0; frame < frameCount; frame += 1) {
146
+ const offset = frame * 4;
147
+ const left = pcm.readInt16LE(offset);
148
+ const right = pcm.readInt16LE(offset + 2);
149
+ mono48k.writeInt16LE(Math.round((left + right) / 2), frame * 2);
150
+ }
151
+ return resamplePcm(mono48k, SAMPLE_RATE, 24e3);
152
+ }
153
+ function convertRealtimePcm24kMonoToDiscordPcm48kStereo(pcm) {
154
+ const mono48k = resamplePcm(pcm, 24e3, SAMPLE_RATE);
155
+ const sampleCount = Math.floor(mono48k.length / 2);
156
+ if (sampleCount === 0) return Buffer.alloc(0);
157
+ const stereo = Buffer.alloc(sampleCount * 4);
158
+ for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex += 1) {
159
+ const sample = mono48k.readInt16LE(sampleIndex * 2);
160
+ const offset = sampleIndex * 4;
161
+ stereo.writeInt16LE(sample, offset);
162
+ stereo.writeInt16LE(sample, offset + 2);
163
+ }
164
+ return stereo;
165
+ }
166
+ function estimateDurationSeconds(pcm) {
167
+ const bytesPerSample = BIT_DEPTH / 8 * CHANNELS;
168
+ return pcm.length / (bytesPerSample * SAMPLE_RATE);
169
+ }
170
+ async function writeVoiceWavFile(pcm) {
171
+ const workspace = await tempWorkspace({
172
+ rootDir: resolvePreferredDaoCoreTmpDir(),
173
+ prefix: "discord-voice-"
174
+ });
175
+ const wav = buildWavBuffer(pcm);
176
+ const filePath = await workspace.write("segment.wav", wav);
177
+ scheduleTempCleanup(workspace.dir);
178
+ return {
179
+ path: filePath,
180
+ durationSeconds: estimateDurationSeconds(pcm)
181
+ };
182
+ }
183
+ function scheduleTempCleanup(tempDir, delayMs = 1800 * 1e3) {
184
+ setTimeout(() => {
185
+ fs.rm(tempDir, {
186
+ recursive: true,
187
+ force: true
188
+ }).catch((err) => {
189
+ if (shouldLogVerbose()) logVerbose(`discord voice: temp cleanup failed for ${tempDir}: ${formatErrorMessage(err)}`);
190
+ });
191
+ }, delayMs).unref();
192
+ }
193
+ //#endregion
194
+ //#region extensions/discord/src/voice/capture-state.ts
195
+ function createVoiceCaptureState() {
196
+ return {
197
+ activeSpeakers: /* @__PURE__ */ new Set(),
198
+ activeCaptureStreams: /* @__PURE__ */ new Map(),
199
+ captureFinalizeTimers: /* @__PURE__ */ new Map(),
200
+ captureGenerations: /* @__PURE__ */ new Map()
201
+ };
202
+ }
203
+ function stopVoiceCaptureState(state) {
204
+ for (const { timer } of state.captureFinalizeTimers.values()) clearTimeout(timer);
205
+ state.captureFinalizeTimers.clear();
206
+ for (const { stream } of state.activeCaptureStreams.values()) stream.destroy();
207
+ state.activeCaptureStreams.clear();
208
+ state.captureGenerations.clear();
209
+ state.activeSpeakers.clear();
210
+ }
211
+ function getActiveVoiceCapture(state, userId) {
212
+ return state.activeCaptureStreams.get(userId);
213
+ }
214
+ function isVoiceCaptureActive(state, userId) {
215
+ return state.activeSpeakers.has(userId);
216
+ }
217
+ function clearVoiceCaptureFinalizeTimer(state, userId, generation) {
218
+ const scheduled = state.captureFinalizeTimers.get(userId);
219
+ if (!scheduled || generation !== void 0 && scheduled.generation !== generation) return false;
220
+ clearTimeout(scheduled.timer);
221
+ state.captureFinalizeTimers.delete(userId);
222
+ return true;
223
+ }
224
+ function beginVoiceCapture(state, userId, stream) {
225
+ const generation = (state.captureGenerations.get(userId) ?? 0) + 1;
226
+ state.captureGenerations.set(userId, generation);
227
+ state.activeSpeakers.add(userId);
228
+ state.activeCaptureStreams.set(userId, {
229
+ generation,
230
+ stream
231
+ });
232
+ clearVoiceCaptureFinalizeTimer(state, userId, generation);
233
+ return generation;
234
+ }
235
+ function finishVoiceCapture(state, userId, generation) {
236
+ clearVoiceCaptureFinalizeTimer(state, userId, generation);
237
+ if (state.activeCaptureStreams.get(userId)?.generation !== generation) return false;
238
+ state.activeCaptureStreams.delete(userId);
239
+ state.activeSpeakers.delete(userId);
240
+ return true;
241
+ }
242
+ function scheduleVoiceCaptureFinalize(params) {
243
+ const { state, userId, delayMs, onFinalize } = params;
244
+ const capture = state.activeCaptureStreams.get(userId);
245
+ if (!capture) return false;
246
+ clearVoiceCaptureFinalizeTimer(state, userId, capture.generation);
247
+ const timer = setTimeout(() => {
248
+ const activeCapture = state.activeCaptureStreams.get(userId);
249
+ if (!activeCapture || activeCapture.generation !== capture.generation) return;
250
+ state.captureFinalizeTimers.delete(userId);
251
+ state.activeCaptureStreams.delete(userId);
252
+ state.activeSpeakers.delete(userId);
253
+ onFinalize?.(activeCapture);
254
+ activeCapture.stream.destroy();
255
+ }, delayMs);
256
+ state.captureFinalizeTimers.set(userId, {
257
+ generation: capture.generation,
258
+ timer
259
+ });
260
+ return true;
261
+ }
262
+ const logger$3 = createSubsystemLogger("discord/voice");
263
+ function summarizeAgentTurnPayloads(payloads) {
264
+ let textPayloads = 0;
265
+ let nonEmptyTextPayloads = 0;
266
+ let reasoningPayloads = 0;
267
+ let errorPayloads = 0;
268
+ let mediaPayloads = 0;
269
+ for (const payload of payloads) {
270
+ if (!payload || typeof payload !== "object") continue;
271
+ const record = payload;
272
+ const text = record.text;
273
+ if (typeof text === "string") {
274
+ textPayloads += 1;
275
+ if (text.trim()) nonEmptyTextPayloads += 1;
276
+ }
277
+ if (record.isReasoning === true) reasoningPayloads += 1;
278
+ if (record.isError === true) errorPayloads += 1;
279
+ if (typeof record.mediaUrl === "string" || Array.isArray(record.mediaUrls) && record.mediaUrls.length > 0) mediaPayloads += 1;
280
+ }
281
+ return `payloadCount=${payloads.length} textPayloads=${textPayloads} nonEmptyTextPayloads=${nonEmptyTextPayloads} reasoningPayloads=${reasoningPayloads} errorPayloads=${errorPayloads} mediaPayloads=${mediaPayloads}`;
282
+ }
283
+ async function resolveDiscordVoiceIngressContext(params) {
284
+ const { entry, userId } = params;
285
+ if (!entry.guildName) entry.guildName = await params.fetchGuildName(entry.guildId);
286
+ const speaker = await params.speakerContext.resolveContext(entry.guildId, userId);
287
+ const speakerIdentity = await params.speakerContext.resolveIdentity(entry.guildId, userId);
288
+ const access = await authorizeDiscordVoiceIngress({
289
+ cfg: params.cfg,
290
+ discordConfig: params.discordConfig,
291
+ guildName: entry.guildName,
292
+ guildId: entry.guildId,
293
+ channelId: entry.channelId,
294
+ channelName: entry.channelName,
295
+ channelSlug: entry.channelName ? normalizeDiscordSlug(entry.channelName) : "",
296
+ channelLabel: formatMention({ channelId: entry.channelId }),
297
+ memberRoleIds: speakerIdentity.memberRoleIds,
298
+ ownerAllowFrom: params.ownerAllowFrom,
299
+ sender: {
300
+ id: speakerIdentity.id,
301
+ name: speakerIdentity.name,
302
+ tag: speakerIdentity.tag
303
+ }
304
+ });
305
+ if (!access.ok) return null;
306
+ return {
307
+ extraSystemPrompt: buildDiscordGroupSystemPrompt(access.channelConfig),
308
+ senderIsOwner: speaker.senderIsOwner,
309
+ speakerLabel: speaker.label
310
+ };
311
+ }
312
+ async function runDiscordVoiceAgentTurn(params) {
313
+ const context = params.context ?? await resolveDiscordVoiceIngressContext({
314
+ entry: params.entry,
315
+ userId: params.userId,
316
+ cfg: params.cfg,
317
+ discordConfig: params.discordConfig,
318
+ ownerAllowFrom: params.ownerAllowFrom,
319
+ fetchGuildName: params.fetchGuildName,
320
+ speakerContext: params.speakerContext
321
+ });
322
+ if (!context) return null;
323
+ const voiceModel = normalizeOptionalString(params.discordConfig.voice?.model);
324
+ const payloads = (await agentCommandFromIngress({
325
+ message: params.message,
326
+ sessionKey: params.entry.route.sessionKey,
327
+ agentId: params.entry.route.agentId,
328
+ messageChannel: "discord",
329
+ messageProvider: "discord-voice",
330
+ extraSystemPrompt: context.extraSystemPrompt,
331
+ allowModelOverride: Boolean(voiceModel),
332
+ model: voiceModel,
333
+ toolsAllow: params.toolsAllow,
334
+ deliver: false
335
+ }, params.runtime)).payloads ?? [];
336
+ const text = payloads.map((payload) => payload.text).filter((entry) => typeof entry === "string" && entry.trim()).join("\n").trim();
337
+ if (!text) logger$3.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)}`);
338
+ return {
339
+ context,
340
+ text
341
+ };
342
+ }
343
+ async function resolveDiscordVoiceRealtimeBootstrapContext(params) {
344
+ const files = (params.discordConfig.voice?.realtime)?.bootstrapContextFiles;
345
+ if (files?.length === 0) return;
346
+ try {
347
+ return await resolveRealtimeBootstrapContextInstructions({
348
+ config: params.cfg,
349
+ agentId: params.entry.route.agentId,
350
+ sessionKey: params.entry.route.sessionKey,
351
+ files,
352
+ warn: (message) => logger$3.warn(`discord voice: realtime bootstrap context: ${message}`)
353
+ });
354
+ } catch (error) {
355
+ logger$3.warn(`discord voice: realtime bootstrap context unavailable: ${error instanceof Error ? error.message : String(error)}`);
356
+ return;
357
+ }
358
+ }
359
+ //#endregion
360
+ //#region extensions/discord/src/voice/prompt.ts
361
+ const DISCORD_VOICE_SPOKEN_OUTPUT_CONTRACT = [
362
+ "You are DaoCore's Discord voice interface in a live voice channel.",
363
+ "Discord voice reply requirements:",
364
+ "- Return only the concise text that should be spoken aloud in the voice channel.",
365
+ "- Treat the transcript as speech-to-text from a live conversation; repair obvious transcription artifacts and ignore repeated partial fragments caused by voice buffering.",
366
+ "- If the transcript is garbled, incomplete, or missing the user's intent, ask one brief clarifying question instead of guessing.",
367
+ "- If the request needs deeper reasoning, current information, or tools, use the available tools before answering.",
368
+ "- Do not call the tts tool; Discord voice will synthesize and play the returned text.",
369
+ "- Do not reply with NO_REPLY unless no spoken response is appropriate.",
370
+ "- Keep the response brief, natural, and conversational. Prefer one to three short sentences.",
371
+ "- Avoid markdown tables, code fences, citations, and visual formatting unless the user explicitly asks for something that cannot be spoken naturally."
372
+ ].join("\n");
373
+ function formatVoiceIngressPrompt(transcript, speakerLabel) {
374
+ const cleanedTranscript = transcript.trim();
375
+ const cleanedLabel = speakerLabel?.trim();
376
+ return [DISCORD_VOICE_SPOKEN_OUTPUT_CONTRACT, cleanedLabel ? [`Voice transcript from speaker "${cleanedLabel}":`, cleanedTranscript].join("\n") : cleanedTranscript].join("\n\n");
377
+ }
378
+ //#endregion
379
+ //#region extensions/discord/src/voice/sdk-runtime.ts
380
+ let cachedDiscordVoiceSdk = null;
381
+ function loadDiscordVoiceSdk() {
382
+ if (cachedDiscordVoiceSdk) return cachedDiscordVoiceSdk;
383
+ cachedDiscordVoiceSdk = createRequire(import.meta.url)("@discordjs/voice");
384
+ return cachedDiscordVoiceSdk;
385
+ }
386
+ const CAPTURE_FINALIZE_GRACE_MS = 2500;
387
+ const VOICE_CONNECT_READY_TIMEOUT_MS = 3e4;
388
+ const VOICE_RECONNECT_GRACE_MS = 15e3;
389
+ const PLAYBACK_READY_TIMEOUT_MS = 6e4;
390
+ const SPEAKING_READY_TIMEOUT_MS = 6e4;
391
+ function resolveVoiceTimeoutMs(value, fallbackMs) {
392
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return fallbackMs;
393
+ return Math.floor(value);
394
+ }
395
+ function logVoiceVerbose(message) {
396
+ logVerbose(`discord voice: ${message}`);
397
+ }
398
+ function isVoiceChannel(type) {
399
+ return type === ChannelType.GuildVoice || type === ChannelType.GuildStageVoice;
400
+ }
401
+ //#endregion
402
+ //#region extensions/discord/src/voice/realtime.ts
403
+ const logger$2 = createSubsystemLogger("discord/voice");
404
+ const DISCORD_REALTIME_TALKBACK_DEBOUNCE_MS = 350;
405
+ const DISCORD_REALTIME_FALLBACK_TEXT = "I hit an error while checking that. Please try again.";
406
+ const DISCORD_REALTIME_PENDING_SPEAKER_CONTEXT_LIMIT = 32;
407
+ const DISCORD_REALTIME_RECENT_AGENT_PROXY_CONSULT_LIMIT = 16;
408
+ const DISCORD_REALTIME_RECENT_AGENT_PROXY_CONSULT_TTL_MS = 15e3;
409
+ const DISCORD_REALTIME_LOG_PREVIEW_CHARS = 500;
410
+ const DISCORD_REALTIME_DEFAULT_MIN_BARGE_IN_AUDIO_END_MS = 250;
411
+ const DISCORD_REALTIME_FORCED_CONSULT_FALLBACK_DELAY_MS = 200;
412
+ const DISCORD_REALTIME_DUPLICATE_ERROR_SUPPRESS_MS = 6e4;
413
+ const REALTIME_PCM16_BYTES_PER_SAMPLE = 2;
414
+ const DISCORD_RAW_PCM_FRAME_BYTES = 3840;
415
+ const DISCORD_REALTIME_OUTPUT_PREROLL_FRAMES = 25;
416
+ const DISCORD_REALTIME_TRAILING_SILENCE_MIN_MS = 700;
417
+ const DISCORD_REALTIME_TRAILING_SILENCE_MAX_MS = 3e3;
418
+ const DISCORD_REALTIME_FORCED_CONSULT_TRAILING_FRAGMENT_WORDS = new Set([
419
+ "a",
420
+ "about",
421
+ "an",
422
+ "and",
423
+ "as",
424
+ "at",
425
+ "because",
426
+ "but",
427
+ "by",
428
+ "for",
429
+ "from",
430
+ "in",
431
+ "of",
432
+ "on",
433
+ "or",
434
+ "so",
435
+ "that",
436
+ "the",
437
+ "then",
438
+ "to",
439
+ "with"
440
+ ]);
441
+ const DISCORD_REALTIME_VERBOSE_OMITTED_EVENTS = new Set([
442
+ "conversation.output_audio.delta",
443
+ "input_audio_buffer.append",
444
+ "response.audio.delta",
445
+ "response.output_audio.delta"
446
+ ]);
447
+ function formatRealtimeLogPreview(text) {
448
+ const oneLine = text.replace(/\s+/g, " ").trim();
449
+ if (oneLine.length <= DISCORD_REALTIME_LOG_PREVIEW_CHARS) return oneLine;
450
+ return `${oneLine.slice(0, DISCORD_REALTIME_LOG_PREVIEW_CHARS)}...`;
451
+ }
452
+ function formatRealtimeInterruptionLog(event) {
453
+ const detail = event.detail ? ` ${event.detail}` : "";
454
+ if (event.direction === "client") {
455
+ if (event.type === "response.cancel") return `discord voice: realtime model interrupt requested ${event.direction}:${event.type}${detail}`;
456
+ if (event.type === "conversation.item.truncate.skipped") return `discord voice: realtime model interrupt ignored ${event.direction}:${event.type}${detail}`;
457
+ if (event.type === "conversation.item.truncate") return `discord voice: realtime model audio truncated ${event.direction}:${event.type}${detail}`;
458
+ }
459
+ if (event.direction === "server") {
460
+ if (event.type === "response.cancelled") return `discord voice: realtime model interrupt confirmed ${event.direction}:${event.type}${detail}`;
461
+ if (event.type === "response.done" && event.detail?.includes("status=cancelled")) return `discord voice: realtime model interrupt confirmed ${event.direction}:${event.type}${detail}`;
462
+ if (event.type === "error" && event.detail === "Cancellation failed: no active response found") return `discord voice: realtime model interrupt raced ${event.direction}:${event.type}${detail}`;
463
+ }
464
+ }
465
+ function isRealtimeResponseCancelled(event) {
466
+ return event.direction === "server" && (event.type === "response.cancelled" || event.type === "response.done" && event.detail?.includes("status=cancelled") === true);
467
+ }
468
+ function shouldLogRealtimeVerboseEvent(event) {
469
+ return !DISCORD_REALTIME_VERBOSE_OMITTED_EVENTS.has(event.type);
470
+ }
471
+ function classifySkippableForcedAgentProxyTranscript(text) {
472
+ const normalized = text.replace(/\s+/g, " ").trim().toLowerCase();
473
+ if (!normalized) return "empty";
474
+ if (/(\.\.\.|…)\s*$/.test(normalized)) return "incomplete-transcript";
475
+ const lastWord = normalized.match(/[a-z']+$/)?.[0]?.replace(/^'+|'+$/g, "");
476
+ if (lastWord && DISCORD_REALTIME_FORCED_CONSULT_TRAILING_FRAGMENT_WORDS.has(lastWord)) return "trailing-fragment";
477
+ if (!normalized.includes("?") && (/^(i'?ll|i will) be (right )?back\b/.test(normalized) || /\b(see you|bye(?:-bye)?|goodbye)\b/.test(normalized))) return "non-actionable-closing";
478
+ }
479
+ function readProviderConfigString(config, key) {
480
+ const value = config[key];
481
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
482
+ }
483
+ function readProviderConfigBoolean(config, key) {
484
+ const value = config?.[key];
485
+ return typeof value === "boolean" ? value : void 0;
486
+ }
487
+ function resolveDiscordVoiceMode(voice) {
488
+ const mode = voice?.mode;
489
+ if (mode === "stt-tts" || mode === "bidi") return mode;
490
+ return "agent-proxy";
491
+ }
492
+ function isDiscordRealtimeVoiceMode(mode) {
493
+ return mode === "agent-proxy" || mode === "bidi";
494
+ }
495
+ function isDiscordAgentProxyVoiceMode(mode) {
496
+ return mode === "agent-proxy";
497
+ }
498
+ function resolveDiscordRealtimeInterruptResponseOnInputAudio(params) {
499
+ const providerConfig = params.realtimeConfig?.providers?.[params.providerId];
500
+ return readProviderConfigBoolean(providerConfig, "interruptResponseOnInputAudio") ?? true;
501
+ }
502
+ function resolveDiscordRealtimeBargeIn(params) {
503
+ const configured = params.realtimeConfig?.bargeIn;
504
+ if (typeof configured === "boolean") return configured;
505
+ return resolveDiscordRealtimeInterruptResponseOnInputAudio(params);
506
+ }
507
+ function buildDiscordSpeakExactUserMessage(text) {
508
+ return [
509
+ "Internal DaoCore voice playback result.",
510
+ "Do not call daocore_agent_consult or any other tool for this message.",
511
+ "Speak this exact DaoCore answer to the Discord voice channel, without adding, removing, or rephrasing words.",
512
+ `Answer: ${JSON.stringify(text)}`
513
+ ].join("\n");
514
+ }
515
+ function isEscapedQuote(text, quoteIndex) {
516
+ let backslashes = 0;
517
+ for (let index = quoteIndex - 1; index >= 0 && text[index] === "\\"; index -= 1) backslashes += 1;
518
+ return backslashes % 2 === 1;
519
+ }
520
+ function readJsonStringAfterLabel(text, label) {
521
+ const labelIndex = text.indexOf(label);
522
+ if (labelIndex < 0) return;
523
+ const quoteIndex = text.indexOf("\"", labelIndex + label.length);
524
+ if (quoteIndex < 0) return;
525
+ for (let index = quoteIndex + 1; index < text.length; index += 1) {
526
+ if (text[index] !== "\"" || isEscapedQuote(text, index)) continue;
527
+ try {
528
+ const parsed = JSON.parse(text.slice(quoteIndex, index + 1));
529
+ return typeof parsed === "string" ? parsed : void 0;
530
+ } catch {
531
+ return;
532
+ }
533
+ }
534
+ }
535
+ function collectRealtimeConsultArgStrings(args) {
536
+ if (!args || typeof args !== "object") return typeof args === "string" ? [args] : [];
537
+ const values = [];
538
+ for (const key of [
539
+ "question",
540
+ "prompt",
541
+ "query",
542
+ "task",
543
+ "context",
544
+ "responseStyle"
545
+ ]) {
546
+ const value = args[key];
547
+ if (typeof value === "string") values.push(value);
548
+ }
549
+ return values;
550
+ }
551
+ function extractDiscordExactSpeechConsultText(args) {
552
+ const message = collectRealtimeConsultArgStrings(args).join("\n");
553
+ if (!message.includes("Speak this exact DaoCore answer") && !message.includes("Speak the provided exact answer verbatim")) return;
554
+ return readJsonStringAfterLabel(message, "Answer:") ?? readJsonStringAfterLabel(message, "Provided answer text:");
555
+ }
556
+ function normalizeRealtimeConsultMatchText(text) {
557
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
558
+ }
559
+ function matchesPendingAgentProxyQuestion(consultMessage, question) {
560
+ const normalizedConsult = normalizeRealtimeConsultMatchText(consultMessage);
561
+ const normalizedQuestion = normalizeRealtimeConsultMatchText(question);
562
+ if (!normalizedConsult || !normalizedQuestion) return false;
563
+ return normalizedConsult.includes(normalizedQuestion) || normalizedQuestion.includes(normalizedConsult);
564
+ }
565
+ var DiscordRealtimeVoiceSession = class {
566
+ constructor(params) {
567
+ this.params = params;
568
+ this.bridge = null;
569
+ this.outputStream = null;
570
+ this.stopped = false;
571
+ this.consultToolPolicy = "safe-read-only";
572
+ this.consultPolicy = "auto";
573
+ this.pendingAgentProxyConsultContexts = [];
574
+ this.recentAgentProxyConsultContexts = [];
575
+ this.pendingSpeakerTurns = [];
576
+ this.outputAudioTimestampMs = 0;
577
+ this.outputAudioDiscordBytes = 0;
578
+ this.outputAudioRealtimeBytes = 0;
579
+ this.outputAudioChunks = 0;
580
+ this.outputStreamEnding = false;
581
+ this.outputPacedBuffer = Buffer.alloc(0);
582
+ this.outputPlaybackStarted = false;
583
+ this.queuedExactSpeechMessages = [];
584
+ this.exactSpeechResponseActive = false;
585
+ this.exactSpeechAudioStarted = false;
586
+ this.playerIdleHandler = () => {
587
+ this.resetOutputStream("player-idle");
588
+ this.completeExactSpeechResponse("player-idle");
589
+ };
590
+ this.talkback = createRealtimeVoiceAgentTalkbackQueue({
591
+ debounceMs: this.realtimeConfig?.debounceMs ?? DISCORD_REALTIME_TALKBACK_DEBOUNCE_MS,
592
+ isStopped: () => this.stopped,
593
+ logger: logger$2,
594
+ logPrefix: "[discord] realtime agent",
595
+ responseStyle: "Brief, natural spoken answer for a Discord voice channel.",
596
+ fallbackText: DISCORD_REALTIME_FALLBACK_TEXT,
597
+ consult: async ({ question, responseStyle, metadata }) => {
598
+ const context = isDiscordRealtimeSpeakerContext(metadata) ? metadata : void 0;
599
+ return { text: await this.runAgentTurn({
600
+ context,
601
+ message: formatVoiceIngressPrompt([question, responseStyle ? `Spoken style: ${responseStyle}` : void 0].filter(Boolean).join("\n\n"), context?.speakerLabel ?? "Discord voice speaker")
602
+ }) };
603
+ },
604
+ deliver: (text) => this.enqueueExactSpeechMessage(text)
605
+ });
606
+ }
607
+ async connect() {
608
+ const resolved = resolveConfiguredRealtimeVoiceProvider({
609
+ configuredProviderId: this.realtimeConfig?.provider,
610
+ providerConfigs: buildProviderConfigs(this.realtimeConfig),
611
+ providerConfigOverrides: buildProviderConfigOverrides(this.realtimeConfig),
612
+ cfg: this.params.cfg,
613
+ defaultModel: this.realtimeConfig?.model,
614
+ noRegisteredProviderMessage: "No configured realtime voice provider registered"
615
+ });
616
+ this.realtimeProviderId = resolved.provider.id;
617
+ const isAgentProxy = isDiscordAgentProxyVoiceMode(this.params.mode);
618
+ const defaultToolPolicy = isAgentProxy ? "owner" : "safe-read-only";
619
+ const toolPolicy = resolveRealtimeVoiceAgentConsultToolPolicy(this.realtimeConfig?.toolPolicy, defaultToolPolicy);
620
+ this.consultToolPolicy = toolPolicy;
621
+ this.consultToolsAllow = resolveRealtimeVoiceAgentConsultToolsAllow(toolPolicy);
622
+ const consultPolicy = this.realtimeConfig?.consultPolicy ?? (isAgentProxy ? "always" : "auto");
623
+ this.consultPolicy = consultPolicy;
624
+ const usesRealtimeAgentHandoff = this.params.mode === "bidi" || toolPolicy !== "none";
625
+ const autoRespondToAudio = !isAgentProxy || consultPolicy !== "always";
626
+ const interruptResponseOnInputAudio = resolveDiscordRealtimeInterruptResponseOnInputAudio({
627
+ realtimeConfig: this.realtimeConfig,
628
+ providerId: resolved.provider.id
629
+ });
630
+ const instructions = buildDiscordRealtimeInstructions({
631
+ mode: this.params.mode,
632
+ instructions: this.realtimeConfig?.instructions,
633
+ bootstrapContextInstructions: this.params.bootstrapContextInstructions,
634
+ toolPolicy,
635
+ consultPolicy
636
+ });
637
+ this.bridge = createRealtimeVoiceBridgeSession({
638
+ provider: resolved.provider,
639
+ providerConfig: resolved.providerConfig,
640
+ audioFormat: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
641
+ instructions,
642
+ autoRespondToAudio,
643
+ interruptResponseOnInputAudio,
644
+ markStrategy: "ack-immediately",
645
+ tools: usesRealtimeAgentHandoff ? resolveRealtimeVoiceAgentConsultTools(toolPolicy) : [],
646
+ audioSink: {
647
+ isOpen: () => !this.stopped,
648
+ sendAudio: (audio) => this.sendOutputAudio(audio),
649
+ clearAudio: () => this.clearOutputAudio("provider-clear-audio")
650
+ },
651
+ onTranscript: (role, text, isFinal) => {
652
+ if (isFinal && text.trim()) logger$2.info(`discord voice: realtime ${role} transcript (${text.length} chars): ${formatRealtimeLogPreview(text)}`);
653
+ if (!isFinal || role !== "user" || !isDiscordAgentProxyVoiceMode(this.params.mode)) return;
654
+ if (usesRealtimeAgentHandoff) {
655
+ this.scheduleForcedAgentProxyConsult(text);
656
+ return;
657
+ }
658
+ this.talkback.enqueue(text, this.consumePendingSpeakerContext());
659
+ },
660
+ onToolCall: (event, session) => this.handleToolCall(event, session),
661
+ onEvent: (event) => {
662
+ const detail = event.detail ? ` ${event.detail}` : "";
663
+ if (shouldLogRealtimeVerboseEvent(event)) logVoiceVerbose(`realtime ${event.direction}:${event.type}${detail}`);
664
+ if (event.direction === "server" && (event.type === "response.done" || event.type === "response.cancelled")) {
665
+ if (this.exactSpeechResponseActive && !this.exactSpeechAudioStarted) this.completeExactSpeechResponse(event.type);
666
+ this.finishOutputAudioStream(event.type, { playBuffered: !isRealtimeResponseCancelled(event) });
667
+ }
668
+ const interruptionLog = formatRealtimeInterruptionLog(event);
669
+ if (interruptionLog) logger$2.info(interruptionLog);
670
+ },
671
+ onError: (error) => this.logRealtimeError(formatErrorMessage(error)),
672
+ onClose: (reason) => {
673
+ this.flushSuppressedRealtimeErrors();
674
+ logVoiceVerbose(`realtime closed: ${reason}`);
675
+ }
676
+ });
677
+ const resolvedModel = readProviderConfigString(resolved.providerConfig, "model") ?? resolved.provider.defaultModel;
678
+ const resolvedVoice = readProviderConfigString(resolved.providerConfig, "voice");
679
+ logger$2.info(`discord voice: realtime bridge starting mode=${this.params.mode} provider=${resolved.provider.id} model=${resolvedModel ?? "default"} voice=${resolvedVoice ?? "default"} consultPolicy=${consultPolicy} toolPolicy=${toolPolicy} autoRespond=${autoRespondToAudio} interruptResponse=${interruptResponseOnInputAudio} bargeIn=${resolveDiscordRealtimeBargeIn({
680
+ realtimeConfig: this.realtimeConfig,
681
+ providerId: resolved.provider.id
682
+ })} minBargeInAudioEndMs=${resolveDiscordRealtimeMinBargeInAudioEndMs(this.realtimeConfig)}`);
683
+ const voiceSdk = loadDiscordVoiceSdk();
684
+ this.params.entry.player.on(voiceSdk.AudioPlayerStatus.Idle, this.playerIdleHandler);
685
+ await this.bridge.connect();
686
+ logger$2.info(`discord voice: realtime bridge ready mode=${this.params.mode} provider=${resolved.provider.id} model=${resolvedModel ?? "default"} voice=${resolvedVoice ?? "default"}`);
687
+ }
688
+ close() {
689
+ this.stopped = true;
690
+ this.flushSuppressedRealtimeErrors();
691
+ this.talkback.close();
692
+ this.clearForcedConsultTimers();
693
+ this.pendingAgentProxyConsultContexts = [];
694
+ this.recentAgentProxyConsultContexts = [];
695
+ this.pendingSpeakerTurns.length = 0;
696
+ this.queuedExactSpeechMessages = [];
697
+ this.exactSpeechResponseActive = false;
698
+ this.exactSpeechAudioStarted = false;
699
+ this.clearOutputAudio("session-close");
700
+ this.bridge?.close();
701
+ this.bridge = null;
702
+ this.realtimeProviderId = void 0;
703
+ const voiceSdk = loadDiscordVoiceSdk();
704
+ this.params.entry.player.off(voiceSdk.AudioPlayerStatus.Idle, this.playerIdleHandler);
705
+ }
706
+ logRealtimeError(message) {
707
+ const now = Date.now();
708
+ if (this.lastRealtimeError?.message === message && now - this.lastRealtimeError.lastLoggedAt < DISCORD_REALTIME_DUPLICATE_ERROR_SUPPRESS_MS) {
709
+ this.lastRealtimeError.suppressed += 1;
710
+ return;
711
+ }
712
+ this.flushSuppressedRealtimeErrors();
713
+ this.lastRealtimeError = {
714
+ message,
715
+ suppressed: 0,
716
+ lastLoggedAt: now
717
+ };
718
+ logger$2.warn(`discord voice: realtime error: ${message}`);
719
+ }
720
+ flushSuppressedRealtimeErrors() {
721
+ if (!this.lastRealtimeError || this.lastRealtimeError.suppressed === 0) return;
722
+ logger$2.warn(`discord voice: suppressed ${this.lastRealtimeError.suppressed} duplicate realtime errors: ${this.lastRealtimeError.message}`);
723
+ this.lastRealtimeError.suppressed = 0;
724
+ }
725
+ beginSpeakerTurn(context, userId) {
726
+ const turn = {
727
+ context: {
728
+ ...context,
729
+ userId
730
+ },
731
+ hasAudio: false,
732
+ inputDiscordBytes: 0,
733
+ inputRealtimeBytes: 0,
734
+ inputChunks: 0,
735
+ interruptedPlayback: false,
736
+ closed: false,
737
+ startedAt: Date.now()
738
+ };
739
+ this.pendingSpeakerTurns.push(turn);
740
+ logger$2.info(`discord voice: realtime speaker turn opened guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} user=${userId} speaker=${context.speakerLabel} owner=${context.senderIsOwner} pendingTurns=${this.pendingSpeakerTurns.length}`);
741
+ this.prunePendingSpeakerTurns();
742
+ return {
743
+ sendInputAudio: (discordPcm48kStereo) => this.sendInputAudioForTurn(turn, discordPcm48kStereo),
744
+ close: () => {
745
+ this.sendRealtimeTrailingSilenceForTurn(turn);
746
+ this.logSpeakerTurnClosed(turn);
747
+ turn.closed = true;
748
+ this.prunePendingSpeakerTurns();
749
+ }
750
+ };
751
+ }
752
+ sendInputAudioForTurn(turn, discordPcm48kStereo) {
753
+ if (!this.bridge || this.stopped) return;
754
+ turn.hasAudio = true;
755
+ const realtimePcm = convertDiscordPcm48kStereoToRealtimePcm24kMono(discordPcm48kStereo);
756
+ if (realtimePcm.length > 0) {
757
+ turn.inputDiscordBytes += discordPcm48kStereo.length;
758
+ turn.inputRealtimeBytes += realtimePcm.length;
759
+ turn.inputChunks += 1;
760
+ turn.lastAudioAt = Date.now();
761
+ if (turn.inputChunks === 1) logger$2.info(`discord voice: realtime input audio started guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} user=${turn.context.userId} speaker=${turn.context.speakerLabel} discordBytes=${discordPcm48kStereo.length} realtimeBytes=${realtimePcm.length} outputAudioMs=${Math.floor(this.outputAudioTimestampMs)} outputActive=${this.isOutputAudioActive()}`);
762
+ const outputActive = this.hasInterruptibleOutputAudio();
763
+ if (!turn.interruptedPlayback && this.isBargeInEnabled() && outputActive) {
764
+ turn.interruptedPlayback = true;
765
+ logVoiceVerbose(`realtime barge-in from active speaker audio: guild ${this.params.entry.guildId} channel ${this.params.entry.channelId} user ${turn.context.userId}`);
766
+ logger$2.info(`discord voice: realtime barge-in detected source=active-speaker-audio guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} user=${turn.context.userId} speaker=${turn.context.speakerLabel} outputAudioMs=${Math.floor(this.outputAudioTimestampMs)} outputActive=${this.isOutputAudioActive()} discordBytes=${discordPcm48kStereo.length} realtimeBytes=${realtimePcm.length}`);
767
+ this.handleBargeIn("active-speaker-audio");
768
+ }
769
+ this.bridge.sendAudio(realtimePcm);
770
+ }
771
+ }
772
+ handleBargeIn(reason = "barge-in") {
773
+ if (!this.isBargeInEnabled()) {
774
+ logger$2.info(`discord voice: realtime barge-in ignored reason=${reason} bargeIn=false guild=${this.params.entry.guildId} channel=${this.params.entry.channelId}`);
775
+ return;
776
+ }
777
+ if (!this.hasInterruptibleOutputAudio()) {
778
+ logger$2.info(`discord voice: realtime barge-in ignored reason=${reason} outputActive=false guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} playbackChunks=${this.outputAudioChunks}`);
779
+ return;
780
+ }
781
+ logger$2.info(`discord voice: realtime barge-in requested reason=${reason} guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} outputAudioMs=${Math.floor(this.outputAudioTimestampMs)} outputActive=${this.isOutputAudioActive()} playbackChunks=${this.outputAudioChunks}`);
782
+ this.bridge?.handleBargeIn({ audioPlaybackActive: true });
783
+ }
784
+ isBargeInEnabled() {
785
+ const providerId = this.realtimeProviderId ?? this.realtimeConfig?.provider ?? "openai";
786
+ return resolveDiscordRealtimeBargeIn({
787
+ realtimeConfig: this.realtimeConfig,
788
+ providerId
789
+ });
790
+ }
791
+ hasInterruptibleOutputAudio() {
792
+ this.syncOutputAudioTimestamp();
793
+ return this.isOutputAudioActive() || this.outputAudioChunks > 0 || this.outputAudioTimestampMs > 0;
794
+ }
795
+ get realtimeConfig() {
796
+ return this.params.discordConfig.voice?.realtime;
797
+ }
798
+ sendOutputAudio(realtimePcm24kMono) {
799
+ const discordPcm = convertRealtimePcm24kMonoToDiscordPcm48kStereo(realtimePcm24kMono);
800
+ if (discordPcm.length === 0) return;
801
+ this.syncOutputAudioTimestamp();
802
+ if (this.outputStreamEnding) {
803
+ logVoiceVerbose(`realtime output audio ignored after stream ending: guild ${this.params.entry.guildId} channel ${this.params.entry.channelId}`);
804
+ return;
805
+ }
806
+ const stream = this.ensureOutputStream();
807
+ if (this.exactSpeechResponseActive) this.exactSpeechAudioStarted = true;
808
+ this.outputAudioDiscordBytes += discordPcm.length;
809
+ this.outputAudioRealtimeBytes += realtimePcm24kMono.length;
810
+ this.outputAudioChunks += 1;
811
+ this.outputAudioTimestampMs += pcm16MonoDurationMs(realtimePcm24kMono, REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ.sampleRateHz);
812
+ this.queueOutputAudio(stream, discordPcm);
813
+ }
814
+ ensureOutputStream() {
815
+ if (this.outputStream && !this.outputStream.destroyed && !this.outputStream.writableEnded) return this.outputStream;
816
+ const stream = new PassThrough({ highWaterMark: DISCORD_RAW_PCM_FRAME_BYTES * 128 });
817
+ this.outputStream = stream;
818
+ this.outputPacedBuffer = Buffer.alloc(0);
819
+ this.outputPlaybackStarted = false;
820
+ stream.once("close", () => {
821
+ if (this.outputStream === stream) {
822
+ this.logOutputAudioStopped("stream-close");
823
+ this.outputStream = null;
824
+ this.resetOutputAudioStats();
825
+ this.completeExactSpeechResponse("stream-close", { drain: false });
826
+ }
827
+ });
828
+ return stream;
829
+ }
830
+ queueOutputAudio(stream, discordPcm) {
831
+ if (this.outputPlaybackStarted) {
832
+ stream.write(discordPcm);
833
+ return;
834
+ }
835
+ this.outputPacedBuffer = this.outputPacedBuffer.length > 0 ? Buffer.concat([this.outputPacedBuffer, discordPcm]) : discordPcm;
836
+ if (this.outputPacedBuffer.length >= DISCORD_RAW_PCM_FRAME_BYTES * DISCORD_REALTIME_OUTPUT_PREROLL_FRAMES) this.startOutputPlayback(stream);
837
+ }
838
+ startOutputPlayback(stream) {
839
+ if (this.outputPlaybackStarted || stream.destroyed) return;
840
+ const voiceSdk = loadDiscordVoiceSdk();
841
+ if (this.outputPacedBuffer.length > 0) {
842
+ stream.write(this.outputPacedBuffer);
843
+ this.outputPacedBuffer = Buffer.alloc(0);
844
+ }
845
+ const resource = voiceSdk.createAudioResource(stream, { inputType: voiceSdk.StreamType.Raw });
846
+ this.params.entry.player.play(resource);
847
+ this.outputPlaybackStarted = true;
848
+ this.outputAudioStartedAt = Date.now();
849
+ const realtimeConfig = this.realtimeConfig;
850
+ logger$2.info(`discord voice: realtime audio playback started guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} mode=${this.params.mode} model=${realtimeConfig?.model ?? "provider-default"} voice=${realtimeConfig?.voice ?? "provider-default"}`);
851
+ }
852
+ clearOutputAudio(reason = "clear") {
853
+ this.resetOutputStream(reason);
854
+ this.params.entry.player.stop(true);
855
+ }
856
+ resetOutputStream(reason = "reset") {
857
+ const stream = this.outputStream;
858
+ this.logOutputAudioStopped(reason);
859
+ this.outputStream = null;
860
+ this.outputPacedBuffer = Buffer.alloc(0);
861
+ this.outputPlaybackStarted = false;
862
+ this.resetOutputAudioStats();
863
+ stream?.end();
864
+ stream?.destroy();
865
+ }
866
+ finishOutputAudioStream(reason, { playBuffered = true } = {}) {
867
+ const stream = this.outputStream;
868
+ if (!stream || stream.destroyed || this.outputStreamEnding) return;
869
+ this.outputStreamEnding = true;
870
+ logger$2.info(`discord voice: realtime audio playback finishing reason=${reason} guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} audioMs=${Math.floor(this.outputAudioTimestampMs)} chunks=${this.outputAudioChunks}`);
871
+ if (playBuffered) this.startOutputPlayback(stream);
872
+ else {
873
+ this.resetOutputStream(reason);
874
+ this.params.entry.player.stop(true);
875
+ this.completeExactSpeechResponse(reason);
876
+ return;
877
+ }
878
+ stream.end();
879
+ }
880
+ enqueueExactSpeechMessage(text) {
881
+ if (this.stopped || !text.trim()) return;
882
+ if (this.exactSpeechResponseActive || this.hasInterruptibleOutputAudio()) {
883
+ this.queuedExactSpeechMessages.push(text);
884
+ logger$2.info(`discord voice: realtime exact speech queued guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} queued=${this.queuedExactSpeechMessages.length} outputAudioMs=${Math.floor(this.outputAudioTimestampMs)} outputActive=${this.isOutputAudioActive()}`);
885
+ return;
886
+ }
887
+ this.sendExactSpeechMessage(text);
888
+ }
889
+ sendExactSpeechMessage(text) {
890
+ if (this.stopped || !text.trim()) return;
891
+ this.exactSpeechResponseActive = true;
892
+ this.exactSpeechAudioStarted = false;
893
+ this.bridge?.sendUserMessage(buildDiscordSpeakExactUserMessage(text));
894
+ }
895
+ completeExactSpeechResponse(reason, options) {
896
+ if (!this.exactSpeechResponseActive && this.queuedExactSpeechMessages.length === 0) return;
897
+ this.exactSpeechResponseActive = false;
898
+ this.exactSpeechAudioStarted = false;
899
+ if (options?.drain === false) return;
900
+ this.drainQueuedExactSpeechMessages(reason);
901
+ }
902
+ drainQueuedExactSpeechMessages(reason) {
903
+ if (this.stopped || this.exactSpeechResponseActive || this.queuedExactSpeechMessages.length === 0 || this.hasInterruptibleOutputAudio()) return;
904
+ const next = this.queuedExactSpeechMessages.shift();
905
+ if (!next) return;
906
+ logger$2.info(`discord voice: realtime exact speech dequeued reason=${reason} guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} queued=${this.queuedExactSpeechMessages.length}`);
907
+ this.sendExactSpeechMessage(next);
908
+ }
909
+ logOutputAudioStopped(reason) {
910
+ const audioMs = Math.floor(this.outputAudioTimestampMs);
911
+ const chunks = this.outputAudioChunks;
912
+ const discordBytes = this.outputAudioDiscordBytes;
913
+ const realtimeBytes = this.outputAudioRealtimeBytes;
914
+ const elapsedMs = this.outputAudioStartedAt ? Date.now() - this.outputAudioStartedAt : 0;
915
+ if (this.outputStream || chunks > 0 || audioMs > 0) logger$2.info(`discord voice: realtime audio playback stopped reason=${reason} guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} audioMs=${audioMs} elapsedMs=${elapsedMs} chunks=${chunks} discordBytes=${discordBytes} realtimeBytes=${realtimeBytes}`);
916
+ }
917
+ resetOutputAudioStats() {
918
+ this.outputAudioTimestampMs = 0;
919
+ this.outputAudioDiscordBytes = 0;
920
+ this.outputAudioRealtimeBytes = 0;
921
+ this.outputAudioChunks = 0;
922
+ this.outputAudioStartedAt = void 0;
923
+ this.outputStreamEnding = false;
924
+ this.outputPacedBuffer = Buffer.alloc(0);
925
+ this.outputPlaybackStarted = false;
926
+ }
927
+ syncOutputAudioTimestamp() {
928
+ this.bridge?.setMediaTimestamp(Math.floor(this.outputAudioTimestampMs));
929
+ }
930
+ isOutputAudioActive() {
931
+ return Boolean(this.outputStream && !this.outputStream.destroyed) || this.outputAudioChunks > 0;
932
+ }
933
+ logSpeakerTurnClosed(turn) {
934
+ if (turn.closed) return;
935
+ const elapsedMs = Date.now() - turn.startedAt;
936
+ const sinceLastAudioMs = turn.lastAudioAt ? Date.now() - turn.lastAudioAt : void 0;
937
+ logger$2.info(`discord voice: realtime speaker turn closed guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} user=${turn.context.userId} speaker=${turn.context.speakerLabel} owner=${turn.context.senderIsOwner} hasAudio=${turn.hasAudio} chunks=${turn.inputChunks} discordBytes=${turn.inputDiscordBytes} realtimeBytes=${turn.inputRealtimeBytes} elapsedMs=${elapsedMs}${sinceLastAudioMs === void 0 ? "" : ` sinceLastAudioMs=${sinceLastAudioMs}`} interruptedPlayback=${turn.interruptedPlayback}`);
938
+ }
939
+ sendRealtimeTrailingSilenceForTurn(turn) {
940
+ if (!this.bridge || this.stopped || turn.closed || !turn.hasAudio) return;
941
+ const providerId = this.realtimeProviderId ?? this.realtimeConfig?.provider ?? "openai";
942
+ const rawSilenceDurationMs = (this.realtimeConfig?.providers?.[providerId])?.silenceDurationMs;
943
+ const silenceMs = Math.min(DISCORD_REALTIME_TRAILING_SILENCE_MAX_MS, Math.max(DISCORD_REALTIME_TRAILING_SILENCE_MIN_MS, typeof rawSilenceDurationMs === "number" && Number.isFinite(rawSilenceDurationMs) ? rawSilenceDurationMs : 0));
944
+ const silenceBytes = Math.ceil(REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ.sampleRateHz * silenceMs / 1e3) * REALTIME_PCM16_BYTES_PER_SAMPLE;
945
+ const silence = Buffer.alloc(silenceBytes);
946
+ this.bridge.sendAudio(silence);
947
+ logger$2.info(`discord voice: realtime trailing silence sent guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} user=${turn.context.userId} speaker=${turn.context.speakerLabel} silenceMs=${silenceMs} realtimeBytes=${silence.length}`);
948
+ }
949
+ handleToolCall(event, session) {
950
+ const callId = event.callId || event.itemId || "unknown";
951
+ if (event.name !== "daocore_agent_consult") {
952
+ session.submitToolResult(callId, { error: `Tool "${event.name}" not available` });
953
+ return;
954
+ }
955
+ if (this.consultToolPolicy === "none") {
956
+ session.submitToolResult(callId, { error: `Tool "${event.name}" not available` });
957
+ return;
958
+ }
959
+ const exactSpeechText = extractDiscordExactSpeechConsultText(event.args);
960
+ if (exactSpeechText !== void 0) {
961
+ logger$2.info(`discord voice: realtime exact speech consult bypassed call=${callId || "unknown"} answerChars=${exactSpeechText.length}`);
962
+ session.submitToolResult(callId, { text: exactSpeechText });
963
+ return;
964
+ }
965
+ const consultMessage = buildRealtimeVoiceAgentConsultChatMessage(event.args);
966
+ logger$2.info(`discord voice: realtime consult requested call=${callId || "unknown"} voiceSession=${this.params.entry.voiceSessionKey} supervisorSession=${this.params.entry.route.sessionKey} agent=${this.params.entry.route.agentId} question=${formatRealtimeLogPreview(consultMessage)}`);
967
+ if (session.bridge.supportsToolResultContinuation) session.submitToolResult(callId, buildRealtimeVoiceAgentConsultWorkingResponse("speaker"), { willContinue: true });
968
+ const pendingConsultContext = this.consumeAgentProxyConsultContext(consultMessage);
969
+ if (pendingConsultContext) this.addRecentAgentProxyConsultQuestion(pendingConsultContext.recent, consultMessage);
970
+ let context = pendingConsultContext?.context;
971
+ let recent = pendingConsultContext?.recent;
972
+ if (!context) {
973
+ const recentConsult = this.findRecentAgentProxyConsultContext(consultMessage);
974
+ if (recentConsult) {
975
+ if (this.hasPendingSpeakerAudioContext()) {
976
+ logger$2.info(`discord voice: realtime consult matched recent agent result but newer speaker audio is pending call=${callId} speaker=${recentConsult.context.speakerLabel} owner=${recentConsult.context.senderIsOwner}`);
977
+ session.submitToolResult(callId, { error: "Discord speaker context changed before this realtime consult completed" });
978
+ return;
979
+ }
980
+ if (this.submitRecentAgentProxyConsultResult(callId, recentConsult, session)) return;
981
+ }
982
+ }
983
+ if (!context) {
984
+ context = this.consumePendingSpeakerContext();
985
+ if (context) recent = this.rememberRecentAgentProxyConsultContext(consultMessage, context);
986
+ }
987
+ if (!context) {
988
+ logger$2.warn(`discord voice: realtime consult has no speaker context call=${callId || "unknown"}`);
989
+ session.submitToolResult(callId, { error: "No Discord speaker context available" });
990
+ return;
991
+ }
992
+ const promise = this.runAgentTurn({
993
+ context,
994
+ message: consultMessage
995
+ });
996
+ if (recent) this.setRecentAgentProxyConsultPromise(recent, promise);
997
+ promise.then((text) => {
998
+ logger$2.info(`discord voice: realtime consult answer (${text.length} chars) voiceSession=${this.params.entry.voiceSessionKey} supervisorSession=${this.params.entry.route.sessionKey} agent=${this.params.entry.route.agentId} speaker=${context.speakerLabel} owner=${context.senderIsOwner}: ${formatRealtimeLogPreview(text)}`);
999
+ session.submitToolResult(callId, { text });
1000
+ }).catch((error) => {
1001
+ logger$2.warn(`discord voice: realtime consult failed call=${callId || "unknown"}: ${formatErrorMessage(error)}`);
1002
+ session.submitToolResult(callId, { error: formatErrorMessage(error) });
1003
+ });
1004
+ }
1005
+ async runAgentTurn(params) {
1006
+ const context = params.context;
1007
+ if (!context) return "";
1008
+ return this.params.runAgentTurn({
1009
+ context,
1010
+ message: params.message,
1011
+ toolsAllow: this.consultToolsAllow,
1012
+ userId: context.userId
1013
+ });
1014
+ }
1015
+ scheduleForcedAgentProxyConsult(transcript) {
1016
+ if (this.consultPolicy !== "always") return;
1017
+ const question = transcript.trim();
1018
+ if (!question) return;
1019
+ const context = this.consumePendingSpeakerContext();
1020
+ const skipReason = classifySkippableForcedAgentProxyTranscript(question);
1021
+ if (skipReason) {
1022
+ logger$2.info(`discord voice: realtime forced agent consult skipped reason=${skipReason} chars=${question.length} speaker=${context?.speakerLabel ?? "unknown"} transcript=${formatRealtimeLogPreview(question)}`);
1023
+ return;
1024
+ }
1025
+ if (!context) {
1026
+ const recent = this.findRecentAgentProxyConsultContext(question);
1027
+ if (recent) {
1028
+ logVoiceVerbose(`realtime forced agent consult skipped (already delegated): guild ${this.params.entry.guildId} channel ${this.params.entry.channelId} speaker ${recent.context.userId}`);
1029
+ return;
1030
+ }
1031
+ logger$2.warn("discord voice: realtime forced agent consult has no speaker context");
1032
+ return;
1033
+ }
1034
+ const pending = {
1035
+ context,
1036
+ question,
1037
+ recent: this.rememberRecentAgentProxyConsultContext(question, context)
1038
+ };
1039
+ this.pendingAgentProxyConsultContexts.push(pending);
1040
+ pending.timer = setTimeout(() => {
1041
+ pending.timer = void 0;
1042
+ this.runForcedAgentProxyConsult(pending);
1043
+ }, DISCORD_REALTIME_FORCED_CONSULT_FALLBACK_DELAY_MS);
1044
+ pending.timer.unref?.();
1045
+ }
1046
+ clearForcedConsultTimers() {
1047
+ for (const pending of this.pendingAgentProxyConsultContexts) this.clearForcedConsultTimer(pending);
1048
+ }
1049
+ clearForcedConsultTimer(pending) {
1050
+ if (!pending.timer) return;
1051
+ clearTimeout(pending.timer);
1052
+ pending.timer = void 0;
1053
+ }
1054
+ consumeAgentProxyConsultContext(consultMessage) {
1055
+ let pending;
1056
+ if (this.pendingAgentProxyConsultContexts.length === 1) pending = this.pendingAgentProxyConsultContexts.shift();
1057
+ else if (this.pendingAgentProxyConsultContexts.length > 1) {
1058
+ const index = this.pendingAgentProxyConsultContexts.findIndex((candidate) => matchesPendingAgentProxyQuestion(consultMessage, candidate.question));
1059
+ if (index < 0) return;
1060
+ pending = this.pendingAgentProxyConsultContexts.splice(index, 1)[0];
1061
+ }
1062
+ if (!pending) return;
1063
+ this.clearForcedConsultTimer(pending);
1064
+ return pending;
1065
+ }
1066
+ removePendingAgentProxyConsultContext(pending) {
1067
+ this.clearForcedConsultTimer(pending);
1068
+ const index = this.pendingAgentProxyConsultContexts.indexOf(pending);
1069
+ if (index >= 0) this.pendingAgentProxyConsultContexts.splice(index, 1);
1070
+ }
1071
+ async runForcedAgentProxyConsult(pending) {
1072
+ this.removePendingAgentProxyConsultContext(pending);
1073
+ const { context, question } = pending;
1074
+ if (this.stopped) return;
1075
+ const startedAt = Date.now();
1076
+ logger$2.info(`discord voice: realtime forced agent consult starting chars=${question.length} voiceSession=${this.params.entry.voiceSessionKey} supervisorSession=${this.params.entry.route.sessionKey} agent=${this.params.entry.route.agentId} speaker=${context.speakerLabel} owner=${context.senderIsOwner}`);
1077
+ if (this.hasInterruptibleOutputAudio()) logger$2.info(`discord voice: realtime forced agent consult preserving active playback guild=${this.params.entry.guildId} channel=${this.params.entry.channelId} outputAudioMs=${Math.floor(this.outputAudioTimestampMs)} outputActive=${this.isOutputAudioActive()} playbackChunks=${this.outputAudioChunks}`);
1078
+ pending.recent.handledByForcedPlayback = true;
1079
+ try {
1080
+ const promise = this.runAgentTurn({
1081
+ context,
1082
+ message: [question, "Context: The realtime model produced a final user transcript without calling daocore_agent_consult. DaoCore is forcing the consult because consultPolicy is always."].join("\n\n")
1083
+ });
1084
+ this.setRecentAgentProxyConsultPromise(pending.recent, promise);
1085
+ const text = await promise;
1086
+ logger$2.info(`discord voice: realtime forced agent consult answer (${text.length} chars) elapsedMs=${Date.now() - startedAt} voiceSession=${this.params.entry.voiceSessionKey} supervisorSession=${this.params.entry.route.sessionKey} agent=${this.params.entry.route.agentId}: ${formatRealtimeLogPreview(text)}`);
1087
+ if (text.trim()) this.enqueueExactSpeechMessage(text);
1088
+ } catch (error) {
1089
+ logger$2.warn(`discord voice: realtime forced agent consult failed elapsedMs=${Date.now() - startedAt}: ${formatErrorMessage(error)}`);
1090
+ this.enqueueExactSpeechMessage(DISCORD_REALTIME_FALLBACK_TEXT);
1091
+ }
1092
+ }
1093
+ consumePendingSpeakerContext() {
1094
+ this.prunePendingSpeakerTurns();
1095
+ this.expireClosedSpeakerTurnsBeforeLaterAudio();
1096
+ const index = this.pendingSpeakerTurns.findIndex((turn) => turn.hasAudio);
1097
+ if (index < 0) return;
1098
+ const [turn] = this.pendingSpeakerTurns.splice(index, 1);
1099
+ this.prunePendingSpeakerTurns();
1100
+ return turn?.context;
1101
+ }
1102
+ hasPendingSpeakerAudioContext() {
1103
+ this.prunePendingSpeakerTurns();
1104
+ this.expireClosedSpeakerTurnsBeforeLaterAudio();
1105
+ return this.pendingSpeakerTurns.some((turn) => turn.hasAudio);
1106
+ }
1107
+ prunePendingSpeakerTurns() {
1108
+ for (let index = this.pendingSpeakerTurns.length - 1; index >= 0; index -= 1) {
1109
+ const turn = this.pendingSpeakerTurns[index];
1110
+ if (turn?.closed && !turn.hasAudio) this.pendingSpeakerTurns.splice(index, 1);
1111
+ }
1112
+ while (this.pendingSpeakerTurns.length > DISCORD_REALTIME_PENDING_SPEAKER_CONTEXT_LIMIT) {
1113
+ const completedIndex = this.pendingSpeakerTurns.findIndex((turn) => turn.closed);
1114
+ this.pendingSpeakerTurns.splice(Math.max(completedIndex, 0), 1);
1115
+ }
1116
+ }
1117
+ expireClosedSpeakerTurnsBeforeLaterAudio() {
1118
+ let hasLaterAudio = false;
1119
+ for (let index = this.pendingSpeakerTurns.length - 1; index >= 0; index -= 1) {
1120
+ const turn = this.pendingSpeakerTurns[index];
1121
+ if (!turn?.hasAudio) continue;
1122
+ if (turn.closed && hasLaterAudio) {
1123
+ this.pendingSpeakerTurns.splice(index, 1);
1124
+ continue;
1125
+ }
1126
+ hasLaterAudio = true;
1127
+ }
1128
+ }
1129
+ rememberRecentAgentProxyConsultContext(question, context) {
1130
+ this.pruneRecentAgentProxyConsultContexts();
1131
+ const recent = {
1132
+ context,
1133
+ createdAt: Date.now(),
1134
+ questions: [question]
1135
+ };
1136
+ this.recentAgentProxyConsultContexts.push(recent);
1137
+ this.pruneRecentAgentProxyConsultContexts();
1138
+ return recent;
1139
+ }
1140
+ addRecentAgentProxyConsultQuestion(recent, question) {
1141
+ if (recent.questions.some((candidate) => matchesPendingAgentProxyQuestion(question, candidate))) return;
1142
+ recent.questions.push(question);
1143
+ }
1144
+ setRecentAgentProxyConsultPromise(recent, promise) {
1145
+ recent.promise = promise;
1146
+ promise.then((text) => {
1147
+ recent.result = {
1148
+ status: "fulfilled",
1149
+ text
1150
+ };
1151
+ }).catch((error) => {
1152
+ recent.result = {
1153
+ status: "rejected",
1154
+ error: formatErrorMessage(error)
1155
+ };
1156
+ });
1157
+ }
1158
+ findRecentAgentProxyConsultContext(consultMessage) {
1159
+ this.pruneRecentAgentProxyConsultContexts();
1160
+ for (let index = this.recentAgentProxyConsultContexts.length - 1; index >= 0; index -= 1) {
1161
+ const recent = this.recentAgentProxyConsultContexts[index];
1162
+ if (recent?.questions.some((question) => matchesPendingAgentProxyQuestion(consultMessage, question))) return recent;
1163
+ }
1164
+ }
1165
+ submitRecentAgentProxyConsultResult(callId, recent, session) {
1166
+ const submitAlreadyDelivered = () => {
1167
+ session.submitToolResult(callId, {
1168
+ status: "already_delivered",
1169
+ message: "DaoCore already delivered this answer to Discord voice."
1170
+ }, { suppressResponse: true });
1171
+ };
1172
+ const submitResult = (result) => {
1173
+ if (recent.handledByForcedPlayback) {
1174
+ submitAlreadyDelivered();
1175
+ return;
1176
+ }
1177
+ if (result.status === "fulfilled") {
1178
+ session.submitToolResult(callId, { text: result.text });
1179
+ return;
1180
+ }
1181
+ session.submitToolResult(callId, { error: result.error });
1182
+ };
1183
+ if (recent.result) {
1184
+ logger$2.info(`discord voice: realtime consult reused recent agent result call=${callId || "unknown"} speaker=${recent.context.speakerLabel} owner=${recent.context.senderIsOwner}`);
1185
+ submitResult(recent.result);
1186
+ return true;
1187
+ }
1188
+ if (!recent.promise) return false;
1189
+ logger$2.info(`discord voice: realtime consult joined in-flight agent result call=${callId || "unknown"} speaker=${recent.context.speakerLabel} owner=${recent.context.senderIsOwner}`);
1190
+ if (recent.handledByForcedPlayback) {
1191
+ recent.promise.then(submitAlreadyDelivered, submitAlreadyDelivered);
1192
+ return true;
1193
+ }
1194
+ recent.promise.then((text) => session.submitToolResult(callId, { text })).catch((error) => session.submitToolResult(callId, { error: formatErrorMessage(error) }));
1195
+ return true;
1196
+ }
1197
+ pruneRecentAgentProxyConsultContexts() {
1198
+ const minCreatedAt = Date.now() - DISCORD_REALTIME_RECENT_AGENT_PROXY_CONSULT_TTL_MS;
1199
+ for (let index = this.recentAgentProxyConsultContexts.length - 1; index >= 0; index -= 1) {
1200
+ const recent = this.recentAgentProxyConsultContexts[index];
1201
+ if (recent && recent.createdAt < minCreatedAt) this.recentAgentProxyConsultContexts.splice(index, 1);
1202
+ }
1203
+ while (this.recentAgentProxyConsultContexts.length > DISCORD_REALTIME_RECENT_AGENT_PROXY_CONSULT_LIMIT) this.recentAgentProxyConsultContexts.shift();
1204
+ }
1205
+ };
1206
+ function isDiscordRealtimeSpeakerContext(value) {
1207
+ return Boolean(value) && typeof value === "object" && typeof value.userId === "string" && typeof value.senderIsOwner === "boolean" && typeof value.speakerLabel === "string";
1208
+ }
1209
+ function pcm16MonoDurationMs(audio, sampleRate) {
1210
+ if (audio.length === 0 || sampleRate <= 0) return 0;
1211
+ return audio.length / REALTIME_PCM16_BYTES_PER_SAMPLE * 1e3 / sampleRate;
1212
+ }
1213
+ function buildProviderConfigs(realtimeConfig) {
1214
+ const configs = realtimeConfig?.providers;
1215
+ return configs && Object.keys(configs).length > 0 ? { ...configs } : void 0;
1216
+ }
1217
+ function buildProviderConfigOverrides(realtimeConfig) {
1218
+ const overrides = {
1219
+ ...realtimeConfig?.model ? { model: realtimeConfig.model } : {},
1220
+ ...realtimeConfig?.voice ? { voice: realtimeConfig.voice } : {},
1221
+ ...typeof realtimeConfig?.minBargeInAudioEndMs === "number" ? { minBargeInAudioEndMs: realtimeConfig.minBargeInAudioEndMs } : {}
1222
+ };
1223
+ return Object.keys(overrides).length > 0 ? overrides : void 0;
1224
+ }
1225
+ function resolveDiscordRealtimeMinBargeInAudioEndMs(realtimeConfig) {
1226
+ return typeof realtimeConfig?.minBargeInAudioEndMs === "number" ? realtimeConfig.minBargeInAudioEndMs : DISCORD_REALTIME_DEFAULT_MIN_BARGE_IN_AUDIO_END_MS;
1227
+ }
1228
+ function buildDiscordRealtimeInstructions(params) {
1229
+ const base = params.instructions ?? ["You are DaoCore's Discord voice interface.", "Keep spoken replies concise, natural, and suitable for a live Discord voice channel."].join("\n");
1230
+ if (isDiscordAgentProxyVoiceMode(params.mode)) return [
1231
+ base,
1232
+ params.bootstrapContextInstructions?.trim(),
1233
+ "Mode: DaoCore agent proxy.",
1234
+ "You are the realtime voice surface for the same DaoCore agent the user can message directly.",
1235
+ "Do not mention a backend, supervisor, helper, or separate system. Present the result as your own work.",
1236
+ "Delegate substantive requests, actions, tool work, current facts, memory, workspace context, and user-specific context with daocore_agent_consult.",
1237
+ "Do not block, refuse, or downscope at the voice layer. Delegate to DaoCore and treat its result as authoritative.",
1238
+ "Answer directly only for greetings, acknowledgements, brief latency tests, or filler while waiting.",
1239
+ "When DaoCore sends an internal exact answer to speak, do not call tools. Say only that answer.",
1240
+ buildRealtimeVoiceAgentConsultPolicyInstructions({
1241
+ toolPolicy: params.toolPolicy,
1242
+ consultPolicy: params.consultPolicy
1243
+ })
1244
+ ].join("\n\n");
1245
+ return [
1246
+ base,
1247
+ params.bootstrapContextInstructions?.trim(),
1248
+ buildRealtimeVoiceAgentConsultPolicyInstructions({
1249
+ toolPolicy: params.toolPolicy,
1250
+ consultPolicy: params.consultPolicy
1251
+ })
1252
+ ].filter(Boolean).join("\n\n");
1253
+ }
1254
+ //#endregion
1255
+ //#region extensions/discord/src/voice/receive-recovery.ts
1256
+ const DECRYPT_FAILURE_WINDOW_MS = 3e4;
1257
+ const DECRYPT_FAILURE_RECONNECT_THRESHOLD = 3;
1258
+ const DECRYPT_FAILURE_MARKER = "DecryptionFailed(";
1259
+ const DAVE_PASSTHROUGH_DISABLED_MARKER = "UnencryptedWhenPassthroughDisabled";
1260
+ function createVoiceReceiveRecoveryState() {
1261
+ return {
1262
+ decryptFailureCount: 0,
1263
+ lastDecryptFailureAt: 0,
1264
+ decryptRecoveryInFlight: false
1265
+ };
1266
+ }
1267
+ function isAbortLikeReceiveError(err) {
1268
+ if (!err || typeof err !== "object") return false;
1269
+ const name = "name" in err && typeof err.name === "string" ? err.name : "";
1270
+ const message = "message" in err && typeof err.message === "string" ? err.message : "";
1271
+ return name === "AbortError" || message.includes("The operation was aborted") || message.includes("aborted");
1272
+ }
1273
+ function analyzeVoiceReceiveError(err) {
1274
+ const message = formatErrorMessage(err);
1275
+ const shouldAttemptPassthrough = message.includes(DAVE_PASSTHROUGH_DISABLED_MARKER);
1276
+ return {
1277
+ message,
1278
+ isAbortLike: isAbortLikeReceiveError(err),
1279
+ shouldAttemptPassthrough,
1280
+ countsAsDecryptFailure: message.includes(DECRYPT_FAILURE_MARKER) || shouldAttemptPassthrough
1281
+ };
1282
+ }
1283
+ function noteVoiceDecryptFailure(state, now = Date.now()) {
1284
+ if (now - state.lastDecryptFailureAt > DECRYPT_FAILURE_WINDOW_MS) state.decryptFailureCount = 0;
1285
+ state.lastDecryptFailureAt = now;
1286
+ state.decryptFailureCount += 1;
1287
+ const firstFailure = state.decryptFailureCount === 1;
1288
+ if (state.decryptFailureCount < DECRYPT_FAILURE_RECONNECT_THRESHOLD || state.decryptRecoveryInFlight) return {
1289
+ firstFailure,
1290
+ shouldRecover: false
1291
+ };
1292
+ state.decryptRecoveryInFlight = true;
1293
+ resetVoiceReceiveRecoveryState(state);
1294
+ return {
1295
+ firstFailure,
1296
+ shouldRecover: true
1297
+ };
1298
+ }
1299
+ function resetVoiceReceiveRecoveryState(state) {
1300
+ state.decryptFailureCount = 0;
1301
+ state.lastDecryptFailureAt = 0;
1302
+ }
1303
+ function finishVoiceDecryptRecovery(state) {
1304
+ state.decryptRecoveryInFlight = false;
1305
+ }
1306
+ function enableDaveReceivePassthrough(params) {
1307
+ const { target, sdk, reason, expirySeconds, onVerbose, onWarn } = params;
1308
+ const networkingState = target.connection.state.networking?.state;
1309
+ if (target.connection.state.status !== sdk.VoiceConnectionStatus.Ready || !networkingState || networkingState.code !== sdk.NetworkingStatusCode.Ready && networkingState.code !== sdk.NetworkingStatusCode.Resuming) return false;
1310
+ const daveSession = networkingState.dave?.session;
1311
+ if (!daveSession) return false;
1312
+ try {
1313
+ daveSession.setPassthroughMode(true, expirySeconds);
1314
+ onVerbose(`enabled DAVE receive passthrough: guild ${target.guildId} channel ${target.channelId} expiry=${expirySeconds}s reason=${reason}`);
1315
+ return true;
1316
+ } catch (err) {
1317
+ onWarn(`discord voice: failed to enable DAVE passthrough guild=${target.guildId} channel=${target.channelId} reason=${reason}: ${formatErrorMessage(err)}`);
1318
+ return false;
1319
+ }
1320
+ }
1321
+ //#endregion
1322
+ //#region extensions/discord/src/voice/sanitize.ts
1323
+ const SPEECH_EMOJI_RE = /(?:\p{Extended_Pictographic}(?:\uFE0F|\u200D|\p{Extended_Pictographic}|\p{Emoji_Modifier})*)+/gu;
1324
+ function stripEmojiForSpeech(text) {
1325
+ return text.replace(SPEECH_EMOJI_RE, " ").replace(/\s+([?!.,:;])/g, "$1").replace(/[ \t]{2,}/g, " ").replace(/ *\n */g, "\n").trim();
1326
+ }
1327
+ function sanitizeVoiceReplyTextForSpeech(text, speakerLabel) {
1328
+ let cleaned = stripInlineDirectiveTagsForDisplay(text).text.trim();
1329
+ if (!cleaned) return "";
1330
+ const label = speakerLabel?.trim();
1331
+ if (label) {
1332
+ const prefix = new RegExp(`^${escapeRegExp(label)}\\s*:\\s*`, "i");
1333
+ cleaned = cleaned.replace(prefix, "").trim();
1334
+ }
1335
+ return stripEmojiForSpeech(cleaned);
1336
+ }
1337
+ //#endregion
1338
+ //#region extensions/discord/src/voice/tts.ts
1339
+ function mergeTtsConfig(base, override) {
1340
+ if (!override) return base;
1341
+ const baseProviders = base.providers ?? {};
1342
+ const overrideProviders = override.providers ?? {};
1343
+ const mergedProviders = Object.fromEntries([...new Set([...Object.keys(baseProviders), ...Object.keys(overrideProviders)])].map((providerId) => {
1344
+ const baseProvider = baseProviders[providerId] ?? {};
1345
+ const overrideProvider = overrideProviders[providerId] ?? {};
1346
+ return [providerId, {
1347
+ ...baseProvider,
1348
+ ...overrideProvider
1349
+ }];
1350
+ }));
1351
+ return {
1352
+ ...base,
1353
+ ...override,
1354
+ modelOverrides: {
1355
+ ...base.modelOverrides,
1356
+ ...override.modelOverrides
1357
+ },
1358
+ ...Object.keys(mergedProviders).length === 0 ? {} : { providers: mergedProviders }
1359
+ };
1360
+ }
1361
+ function resolveVoiceTtsConfig(params) {
1362
+ if (!params.override) return {
1363
+ cfg: params.cfg,
1364
+ resolved: resolveTtsConfig(params.cfg)
1365
+ };
1366
+ const merged = mergeTtsConfig(params.cfg.messages?.tts ?? {}, params.override);
1367
+ const messages = params.cfg.messages ?? {};
1368
+ const cfg = {
1369
+ ...params.cfg,
1370
+ messages: {
1371
+ ...messages,
1372
+ tts: merged
1373
+ }
1374
+ };
1375
+ return {
1376
+ cfg,
1377
+ resolved: resolveTtsConfig(cfg)
1378
+ };
1379
+ }
1380
+ async function transcribeVoiceAudio(params) {
1381
+ return normalizeOptionalString((await getDiscordRuntime().mediaUnderstanding.transcribeAudioFile({
1382
+ filePath: params.filePath,
1383
+ cfg: params.cfg,
1384
+ agentDir: resolveAgentDir(params.cfg, params.agentId),
1385
+ mime: "audio/wav"
1386
+ })).text);
1387
+ }
1388
+ async function synthesizeVoiceReplyAudio(params) {
1389
+ const { cfg: ttsCfg, resolved: ttsConfig } = resolveVoiceTtsConfig({
1390
+ cfg: params.cfg,
1391
+ override: params.override
1392
+ });
1393
+ const directive = parseTtsDirectives(params.replyText, ttsConfig.modelOverrides, {
1394
+ cfg: ttsCfg,
1395
+ providerConfigs: ttsConfig.providerConfigs,
1396
+ preferredProviderId: getTtsProvider(ttsConfig, resolveTtsPrefsPath(ttsConfig))
1397
+ });
1398
+ const speakText = sanitizeVoiceReplyTextForSpeech(directive.overrides.ttsText ?? directive.cleanedText.trim(), params.speakerLabel);
1399
+ if (!speakText) return { status: "empty" };
1400
+ const runtime = getDiscordRuntime();
1401
+ const streamResult = await runtime.tts.textToSpeechStream?.({
1402
+ text: speakText,
1403
+ cfg: ttsCfg,
1404
+ channel: "discord",
1405
+ overrides: directive.overrides,
1406
+ disableFallback: true
1407
+ });
1408
+ if (streamResult?.success && streamResult.audioStream) return {
1409
+ status: "ok",
1410
+ mode: "stream",
1411
+ audioStream: streamResult.audioStream,
1412
+ release: streamResult.release,
1413
+ speakText
1414
+ };
1415
+ const result = await runtime.tts.textToSpeech({
1416
+ text: speakText,
1417
+ cfg: ttsCfg,
1418
+ channel: "discord",
1419
+ overrides: directive.overrides
1420
+ });
1421
+ if (!result.success || !result.audioPath) return {
1422
+ status: "failed",
1423
+ error: result.error ?? "unknown error"
1424
+ };
1425
+ return {
1426
+ status: "ok",
1427
+ mode: "file",
1428
+ audioPath: result.audioPath,
1429
+ speakText
1430
+ };
1431
+ }
1432
+ //#endregion
1433
+ //#region extensions/discord/src/voice/segment.ts
1434
+ const VOICE_TRANSCRIPT_LOG_PREVIEW_CHARS = 500;
1435
+ const logger$1 = createSubsystemLogger("discord/voice");
1436
+ function formatVoiceTranscriptLogPreview(text) {
1437
+ const oneLine = text.replace(/\s+/g, " ").trim();
1438
+ if (oneLine.length <= VOICE_TRANSCRIPT_LOG_PREVIEW_CHARS) return oneLine;
1439
+ return `${oneLine.slice(0, VOICE_TRANSCRIPT_LOG_PREVIEW_CHARS)}...`;
1440
+ }
1441
+ async function processDiscordVoiceSegment(params) {
1442
+ const { entry, wavPath, userId, durationSeconds } = params;
1443
+ logVoiceVerbose(`segment processing (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId}`);
1444
+ const ingress = await resolveDiscordVoiceIngressContext({
1445
+ entry,
1446
+ userId,
1447
+ cfg: params.cfg,
1448
+ discordConfig: params.discordConfig,
1449
+ ownerAllowFrom: params.ownerAllowFrom,
1450
+ fetchGuildName: params.fetchGuildName,
1451
+ speakerContext: params.speakerContext
1452
+ });
1453
+ if (!ingress) {
1454
+ logVoiceVerbose(`segment unauthorized: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1455
+ return;
1456
+ }
1457
+ const transcript = await transcribeVoiceAudio({
1458
+ cfg: params.cfg,
1459
+ agentId: entry.route.agentId,
1460
+ filePath: wavPath
1461
+ });
1462
+ if (!transcript) {
1463
+ logVoiceVerbose(`transcription empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1464
+ return;
1465
+ }
1466
+ logVoiceVerbose(`transcription ok (${transcript.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1467
+ logVoiceVerbose(`transcript from ${ingress.speakerLabel} (${userId}) in guild ${entry.guildId} channel ${entry.channelId}: ${formatVoiceTranscriptLogPreview(transcript)}`);
1468
+ const turn = await runDiscordVoiceAgentTurn({
1469
+ entry,
1470
+ userId,
1471
+ message: formatVoiceIngressPrompt(transcript, ingress.speakerLabel),
1472
+ cfg: params.cfg,
1473
+ discordConfig: params.discordConfig,
1474
+ runtime: params.runtime,
1475
+ context: ingress,
1476
+ ownerAllowFrom: params.ownerAllowFrom,
1477
+ fetchGuildName: params.fetchGuildName,
1478
+ speakerContext: params.speakerContext
1479
+ });
1480
+ if (!turn) {
1481
+ logVoiceVerbose(`segment unauthorized before agent turn: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1482
+ return;
1483
+ }
1484
+ const replyText = turn.text;
1485
+ if (!replyText) {
1486
+ logVoiceVerbose(`reply empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1487
+ return;
1488
+ }
1489
+ logVoiceVerbose(`reply ok (${replyText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1490
+ const voiceReplyAudio = await synthesizeVoiceReplyAudio({
1491
+ cfg: params.cfg,
1492
+ override: params.discordConfig.voice?.tts,
1493
+ replyText,
1494
+ speakerLabel: ingress.speakerLabel
1495
+ });
1496
+ if (voiceReplyAudio.status === "empty") {
1497
+ logVoiceVerbose(`tts skipped (empty): guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1498
+ return;
1499
+ }
1500
+ if (voiceReplyAudio.status === "failed") {
1501
+ logger$1.warn(`discord voice: TTS failed: ${voiceReplyAudio.error ?? "unknown error"}`);
1502
+ return;
1503
+ }
1504
+ logVoiceVerbose(`tts ok (${voiceReplyAudio.speakText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1505
+ params.enqueuePlayback(entry, async () => {
1506
+ const voiceSdk = loadDiscordVoiceSdk();
1507
+ const releaseAudioStream = voiceReplyAudio.mode === "stream" ? voiceReplyAudio.release : void 0;
1508
+ try {
1509
+ if (voiceReplyAudio.mode === "stream") {
1510
+ logVoiceVerbose(`playback start: guild ${entry.guildId} channel ${entry.channelId} stream`);
1511
+ const nodeStream = Readable.fromWeb(voiceReplyAudio.audioStream);
1512
+ const resource = voiceSdk.createAudioResource(nodeStream);
1513
+ entry.player.play(resource);
1514
+ } else {
1515
+ logVoiceVerbose(`playback start: guild ${entry.guildId} channel ${entry.channelId} file ${path.basename(voiceReplyAudio.audioPath)}`);
1516
+ const resource = voiceSdk.createAudioResource(voiceReplyAudio.audioPath);
1517
+ entry.player.play(resource);
1518
+ }
1519
+ await voiceSdk.entersState(entry.player, voiceSdk.AudioPlayerStatus.Playing, PLAYBACK_READY_TIMEOUT_MS).catch(() => void 0);
1520
+ await voiceSdk.entersState(entry.player, voiceSdk.AudioPlayerStatus.Idle, SPEAKING_READY_TIMEOUT_MS).catch(() => void 0);
1521
+ logVoiceVerbose(`playback done: guild ${entry.guildId} channel ${entry.channelId}`);
1522
+ } finally {
1523
+ await releaseAudioStream?.();
1524
+ }
1525
+ });
1526
+ }
1527
+ //#endregion
1528
+ //#region extensions/discord/src/voice/speaker-context.ts
1529
+ const SPEAKER_CONTEXT_CACHE_TTL_MS = 6e4;
1530
+ var DiscordVoiceSpeakerContextResolver = class {
1531
+ constructor(params) {
1532
+ this.params = params;
1533
+ this.cache = /* @__PURE__ */ new Map();
1534
+ }
1535
+ async resolveContext(guildId, userId) {
1536
+ const cached = this.getCachedContext(guildId, userId);
1537
+ if (cached) return cached;
1538
+ const identity = await this.resolveIdentity(guildId, userId);
1539
+ const context = {
1540
+ id: identity.id,
1541
+ label: identity.label,
1542
+ name: identity.name,
1543
+ tag: identity.tag,
1544
+ senderIsOwner: this.resolveIsOwner(identity)
1545
+ };
1546
+ this.setCachedContext(guildId, userId, context);
1547
+ return context;
1548
+ }
1549
+ async resolveIdentity(guildId, userId) {
1550
+ try {
1551
+ const member = await this.params.client.fetchMember(guildId, userId);
1552
+ const username = member.user?.username ?? void 0;
1553
+ return {
1554
+ id: userId,
1555
+ label: member.nickname ?? member.user?.globalName ?? username ?? userId,
1556
+ name: username,
1557
+ tag: member.user ? formatDiscordUserTag(member.user) : void 0,
1558
+ memberRoleIds: Array.isArray(member.roles) ? member.roles.map((role) => typeof role === "string" ? role : typeof role?.id === "string" ? role.id : "").filter(Boolean) : []
1559
+ };
1560
+ } catch {
1561
+ try {
1562
+ const user = await this.params.client.fetchUser(userId);
1563
+ const username = user.username ?? void 0;
1564
+ return {
1565
+ id: userId,
1566
+ label: user.globalName ?? username ?? userId,
1567
+ name: username,
1568
+ tag: formatDiscordUserTag(user),
1569
+ memberRoleIds: []
1570
+ };
1571
+ } catch {
1572
+ return {
1573
+ id: userId,
1574
+ label: userId,
1575
+ memberRoleIds: []
1576
+ };
1577
+ }
1578
+ }
1579
+ }
1580
+ resolveIsOwner(identity) {
1581
+ return resolveDiscordOwnerAccess({
1582
+ allowFrom: this.params.ownerAllowFrom,
1583
+ sender: {
1584
+ id: identity.id,
1585
+ name: identity.name,
1586
+ tag: identity.tag
1587
+ },
1588
+ allowNameMatching: false
1589
+ }).ownerAllowed;
1590
+ }
1591
+ resolveCacheKey(guildId, userId) {
1592
+ return `${guildId}:${userId}`;
1593
+ }
1594
+ getCachedContext(guildId, userId) {
1595
+ const key = this.resolveCacheKey(guildId, userId);
1596
+ const cached = this.cache.get(key);
1597
+ if (!cached) return;
1598
+ if (cached.expiresAt <= Date.now()) {
1599
+ this.cache.delete(key);
1600
+ return;
1601
+ }
1602
+ return {
1603
+ id: cached.id,
1604
+ label: cached.label,
1605
+ name: cached.name,
1606
+ tag: cached.tag,
1607
+ senderIsOwner: cached.senderIsOwner
1608
+ };
1609
+ }
1610
+ setCachedContext(guildId, userId, context) {
1611
+ const key = this.resolveCacheKey(guildId, userId);
1612
+ this.cache.set(key, {
1613
+ ...context,
1614
+ expiresAt: Date.now() + SPEAKER_CONTEXT_CACHE_TTL_MS
1615
+ });
1616
+ }
1617
+ };
1618
+ //#endregion
1619
+ //#region extensions/discord/src/voice/manager.ts
1620
+ const logger = createSubsystemLogger("discord/voice");
1621
+ const VOICE_LOG_PREVIEW_CHARS = 500;
1622
+ const FOLLOW_USERS_RECONCILE_INTERVAL_MS = 1e4;
1623
+ const FOLLOW_USERS_RECONCILE_MAX_GUILDS_PER_RUN = 4;
1624
+ const FOLLOW_USERS_RECONCILE_MAX_REST_LOOKUPS_PER_RUN = 32;
1625
+ const DISCORD_VOICE_FATAL_AUTOJOIN_ERROR_PATTERNS = [
1626
+ "api key missing",
1627
+ "incorrect api key",
1628
+ "invalid api key",
1629
+ "unauthorized",
1630
+ "authentication",
1631
+ "permission denied",
1632
+ "forbidden"
1633
+ ];
1634
+ function formatVoiceLogPreview(text) {
1635
+ const oneLine = text.replace(/\s+/g, " ").trim();
1636
+ if (oneLine.length <= VOICE_LOG_PREVIEW_CHARS) return oneLine;
1637
+ return `${oneLine.slice(0, VOICE_LOG_PREVIEW_CHARS)}...`;
1638
+ }
1639
+ function isVoiceConnectionDestroyed(connection, voiceSdk) {
1640
+ return connection.state.status === voiceSdk.VoiceConnectionStatus.Destroyed;
1641
+ }
1642
+ function destroyVoiceConnectionSafely(params) {
1643
+ if (isVoiceConnectionDestroyed(params.connection, params.voiceSdk)) {
1644
+ logVoiceVerbose(`destroy skipped: ${params.reason}; connection already destroyed`);
1645
+ return;
1646
+ }
1647
+ try {
1648
+ params.connection.destroy();
1649
+ } catch (err) {
1650
+ const message = formatErrorMessage(err);
1651
+ if (message.includes("already been destroyed")) {
1652
+ logVoiceVerbose(`destroy skipped: ${params.reason}; ${message}`);
1653
+ return;
1654
+ }
1655
+ logger.warn(`discord voice: destroy failed: ${params.reason}: ${message}`);
1656
+ }
1657
+ }
1658
+ function normalizeVoiceChannelResidencies(entries) {
1659
+ const normalized = [];
1660
+ for (const entry of entries ?? []) {
1661
+ const guildId = entry.guildId?.trim();
1662
+ const channelId = entry.channelId?.trim();
1663
+ if (guildId && channelId) normalized.push({
1664
+ guildId,
1665
+ channelId
1666
+ });
1667
+ }
1668
+ return normalized;
1669
+ }
1670
+ function normalizeDiscordUserId(value) {
1671
+ const trimmed = value.trim();
1672
+ const withoutDiscordPrefix = trimmed.startsWith("discord:") ? trimmed.slice(8) : trimmed;
1673
+ return (withoutDiscordPrefix.startsWith("user:") ? withoutDiscordPrefix.slice(5) : withoutDiscordPrefix).trim() || void 0;
1674
+ }
1675
+ function normalizeDiscordUserIds(entries) {
1676
+ const ids = /* @__PURE__ */ new Set();
1677
+ for (const entry of entries ?? []) {
1678
+ const id = normalizeDiscordUserId(entry);
1679
+ if (id) ids.add(id);
1680
+ }
1681
+ return ids;
1682
+ }
1683
+ function resolveFollowUsersEnabled(voiceConfig) {
1684
+ return voiceConfig?.followUsersEnabled !== false;
1685
+ }
1686
+ function isVoiceChannelAllowed(params) {
1687
+ return params.allowedChannels === null || params.allowedChannels.some((entry) => entry.guildId === params.guildId && entry.channelId === params.channelId);
1688
+ }
1689
+ function formatAutoJoinFailureKey(entry) {
1690
+ return `${entry.guildId}:${entry.channelId}`;
1691
+ }
1692
+ function isFatalAutoJoinFailure(message) {
1693
+ const normalized = message.toLowerCase();
1694
+ return DISCORD_VOICE_FATAL_AUTOJOIN_ERROR_PATTERNS.some((pattern) => normalized.includes(pattern));
1695
+ }
1696
+ function isUnknownDiscordVoiceStateError(err) {
1697
+ return (err && typeof err === "object" && "status" in err && typeof err.status === "number" ? err.status : void 0) === 404 || /unknown voice state/i.test(formatErrorMessage(err));
1698
+ }
1699
+ function startAutoJoin(manager) {
1700
+ manager.autoJoin().catch((err) => logger.warn(`discord voice: autoJoin failed: ${formatErrorMessage(err)}`));
1701
+ }
1702
+ function resolveDiscordVoiceAgentRoute(params) {
1703
+ const voiceRoute = resolveAgentRoute({
1704
+ cfg: params.cfg,
1705
+ channel: "discord",
1706
+ accountId: params.accountId,
1707
+ guildId: params.guildId,
1708
+ peer: {
1709
+ kind: "channel",
1710
+ id: params.sessionChannelId
1711
+ }
1712
+ });
1713
+ const agentSession = params.voiceConfig?.agentSession;
1714
+ if (agentSession?.mode !== "target") return {
1715
+ route: voiceRoute,
1716
+ voiceRoute,
1717
+ agentSessionMode: "voice",
1718
+ agentSessionTarget: void 0
1719
+ };
1720
+ const target = agentSession.target?.trim();
1721
+ if (!target) throw new Error("channels.discord.voice.agentSession.target is required when mode is \"target\"");
1722
+ const parsed = parseDiscordTarget(target, { defaultKind: "channel" });
1723
+ if (!parsed) throw new Error(`Invalid Discord voice agent session target "${target}"`);
1724
+ return {
1725
+ route: resolveAgentRoute({
1726
+ cfg: params.cfg,
1727
+ channel: "discord",
1728
+ accountId: params.accountId,
1729
+ guildId: params.guildId,
1730
+ peer: {
1731
+ kind: parsed.kind === "user" ? "direct" : "channel",
1732
+ id: parsed.id
1733
+ }
1734
+ }),
1735
+ voiceRoute,
1736
+ agentSessionMode: "target",
1737
+ agentSessionTarget: parsed.normalized
1738
+ };
1739
+ }
1740
+ var DiscordVoiceManager$1 = class {
1741
+ constructor(params) {
1742
+ this.params = params;
1743
+ this.sessions = /* @__PURE__ */ new Map();
1744
+ this.autoJoinTask = null;
1745
+ this.fatalAutoJoinFailures = /* @__PURE__ */ new Map();
1746
+ this.followedUserChannels = /* @__PURE__ */ new Map();
1747
+ this.followedVoiceGuilds = /* @__PURE__ */ new Set();
1748
+ this.followUsersReconcileTimer = null;
1749
+ this.followUsersReconcileTask = null;
1750
+ this.followUsersReconcileGuildCursor = 0;
1751
+ this.followUsersReconcileBotGuildCursor = 0;
1752
+ this.followUsersReconcileUserCursors = /* @__PURE__ */ new Map();
1753
+ this.destroyed = false;
1754
+ this.botUserId = params.botUserId;
1755
+ this.voiceEnabled = resolveDiscordVoiceEnabled(params.discordConfig.voice);
1756
+ this.ownerAllowFrom = resolveDiscordAccountAllowFrom({
1757
+ cfg: params.cfg,
1758
+ accountId: params.accountId
1759
+ }) ?? params.discordConfig.allowFrom ?? params.discordConfig.dm?.allowFrom ?? [];
1760
+ this.allowedChannels = params.discordConfig.voice?.allowedChannels === void 0 ? null : normalizeVoiceChannelResidencies(params.discordConfig.voice.allowedChannels);
1761
+ this.followUserIds = resolveFollowUsersEnabled(params.discordConfig.voice) ? normalizeDiscordUserIds(params.discordConfig.voice?.followUsers) : /* @__PURE__ */ new Set();
1762
+ this.speakerContext = new DiscordVoiceSpeakerContextResolver({
1763
+ client: params.client,
1764
+ ownerAllowFrom: this.ownerAllowFrom
1765
+ });
1766
+ }
1767
+ setBotUserId(id) {
1768
+ if (id) this.botUserId = id;
1769
+ }
1770
+ isEnabled() {
1771
+ return this.voiceEnabled;
1772
+ }
1773
+ async autoJoin() {
1774
+ if (!this.voiceEnabled || this.destroyed) return;
1775
+ if (this.autoJoinTask) return this.autoJoinTask;
1776
+ this.autoJoinTask = (async () => {
1777
+ const entries = this.params.discordConfig.voice?.autoJoin ?? [];
1778
+ const entriesByGuild = /* @__PURE__ */ new Map();
1779
+ const duplicateGuilds = /* @__PURE__ */ new Set();
1780
+ for (const entry of entries) {
1781
+ const guildId = entry.guildId.trim();
1782
+ const channelId = entry.channelId.trim();
1783
+ if (!guildId || !channelId) continue;
1784
+ if (entriesByGuild.has(guildId)) duplicateGuilds.add(guildId);
1785
+ entriesByGuild.set(guildId, {
1786
+ guildId,
1787
+ channelId
1788
+ });
1789
+ }
1790
+ logVoiceVerbose(`autoJoin: ${entries.length} entries, ${entriesByGuild.size} guilds`);
1791
+ for (const guildId of duplicateGuilds) {
1792
+ const selected = entriesByGuild.get(guildId);
1793
+ if (selected) logger.warn(`discord voice: autoJoin has multiple entries for guild ${guildId}; using channel ${selected.channelId}`);
1794
+ }
1795
+ for (const entry of entriesByGuild.values()) {
1796
+ const failureKey = formatAutoJoinFailureKey(entry);
1797
+ const fatalFailure = this.fatalAutoJoinFailures.get(failureKey);
1798
+ if (fatalFailure) {
1799
+ if (!fatalFailure.skipLogged) {
1800
+ logger.warn(`discord voice: autoJoin suppressed guild=${entry.guildId} channel=${entry.channelId} after fatal startup failure; retry with /vc join or reload config after fixing credentials: ${fatalFailure.message}`);
1801
+ fatalFailure.skipLogged = true;
1802
+ }
1803
+ continue;
1804
+ }
1805
+ logVoiceVerbose(`autoJoin: joining guild ${entry.guildId} channel ${entry.channelId}`);
1806
+ const result = await this.join({
1807
+ guildId: entry.guildId,
1808
+ channelId: entry.channelId
1809
+ });
1810
+ if (!result.ok) {
1811
+ logger.warn(`discord voice: autoJoin skipped guild=${entry.guildId} channel=${entry.channelId}: ${result.message}`);
1812
+ if (isFatalAutoJoinFailure(result.message)) this.fatalAutoJoinFailures.set(failureKey, {
1813
+ message: result.message,
1814
+ skipLogged: false
1815
+ });
1816
+ }
1817
+ }
1818
+ this.ensureFollowUsersReconcileTimer();
1819
+ await this.reconcileFollowedUsers("startup");
1820
+ })().finally(() => {
1821
+ this.autoJoinTask = null;
1822
+ });
1823
+ return this.autoJoinTask;
1824
+ }
1825
+ status() {
1826
+ return Array.from(this.sessions.values()).map((session) => ({
1827
+ ok: true,
1828
+ message: `connected: guild ${session.guildId} channel ${session.channelId}`,
1829
+ guildId: session.guildId,
1830
+ channelId: session.channelId
1831
+ }));
1832
+ }
1833
+ isAllowedVoiceChannel(params) {
1834
+ return isVoiceChannelAllowed({
1835
+ allowedChannels: this.allowedChannels,
1836
+ guildId: params.guildId.trim(),
1837
+ channelId: params.channelId.trim()
1838
+ });
1839
+ }
1840
+ async join(params, options) {
1841
+ if (this.destroyed) return {
1842
+ ok: false,
1843
+ message: "Discord voice manager is stopped."
1844
+ };
1845
+ if (!this.voiceEnabled) return {
1846
+ ok: false,
1847
+ message: "Discord voice is disabled (channels.discord.voice.enabled)."
1848
+ };
1849
+ const guildId = params.guildId.trim();
1850
+ const channelId = params.channelId.trim();
1851
+ if (!guildId || !channelId) return {
1852
+ ok: false,
1853
+ message: "Missing guildId or channelId."
1854
+ };
1855
+ if (!this.isAllowedVoiceChannel({
1856
+ guildId,
1857
+ channelId
1858
+ })) {
1859
+ logger.warn(`discord voice: join rejected for non-allowed channel guild=${guildId} channel=${channelId}`);
1860
+ return {
1861
+ ok: false,
1862
+ message: `${formatMention({ channelId })} is not allowed by channels.discord.voice.allowedChannels.`,
1863
+ guildId,
1864
+ channelId
1865
+ };
1866
+ }
1867
+ logVoiceVerbose(`join requested: guild ${guildId} channel ${channelId}`);
1868
+ const existing = this.sessions.get(guildId);
1869
+ if (existing && existing.channelId === channelId) {
1870
+ logVoiceVerbose(`join: already connected to guild ${guildId} channel ${channelId}`);
1871
+ return {
1872
+ ok: true,
1873
+ message: `Already connected to ${formatMention({ channelId })}.`,
1874
+ guildId,
1875
+ channelId
1876
+ };
1877
+ }
1878
+ if (existing) {
1879
+ logVoiceVerbose(`join: replacing existing session for guild ${guildId}`);
1880
+ await this.leave({ guildId }, { preserveFollowState: options?.preserveFollowState });
1881
+ }
1882
+ const channelInfo = await this.params.client.fetchChannel(channelId).catch(() => null);
1883
+ if (!channelInfo || "type" in channelInfo && !isVoiceChannel(channelInfo.type)) return {
1884
+ ok: false,
1885
+ message: `Channel ${channelId} is not a voice channel.`
1886
+ };
1887
+ const channelGuildId = "guildId" in channelInfo ? channelInfo.guildId : void 0;
1888
+ if (channelGuildId && channelGuildId !== guildId) return {
1889
+ ok: false,
1890
+ message: "Voice channel is not in this guild."
1891
+ };
1892
+ const voicePlugin = this.params.client.getPlugin("voice");
1893
+ if (!voicePlugin) return {
1894
+ ok: false,
1895
+ message: "Discord voice plugin is not available."
1896
+ };
1897
+ const voiceConfig = this.params.discordConfig.voice;
1898
+ const voiceMode = resolveDiscordVoiceMode(voiceConfig);
1899
+ const adapterCreator = voicePlugin.getGatewayAdapterCreator(guildId);
1900
+ const daveEncryption = voiceConfig?.daveEncryption;
1901
+ const decryptionFailureTolerance = voiceConfig?.decryptionFailureTolerance;
1902
+ const connectReadyTimeoutMs = resolveVoiceTimeoutMs(voiceConfig?.connectTimeoutMs, VOICE_CONNECT_READY_TIMEOUT_MS);
1903
+ const reconnectGraceMs = resolveVoiceTimeoutMs(voiceConfig?.reconnectGraceMs, VOICE_RECONNECT_GRACE_MS);
1904
+ logVoiceVerbose(`join: DAVE settings encryption=${daveEncryption === false ? "off" : "on"} tolerance=${decryptionFailureTolerance ?? "default"} connectTimeout=${connectReadyTimeoutMs}ms reconnectGrace=${reconnectGraceMs}ms`);
1905
+ const voiceSdk = loadDiscordVoiceSdk();
1906
+ const existingEntry = this.sessions.get(guildId);
1907
+ if (existingEntry) {
1908
+ existingEntry.stop();
1909
+ this.sessions.delete(guildId);
1910
+ }
1911
+ const staleConnection = voiceSdk.getVoiceConnection(guildId);
1912
+ if (staleConnection) destroyVoiceConnectionSafely({
1913
+ connection: staleConnection,
1914
+ voiceSdk,
1915
+ reason: `stale connection before join guild ${guildId}`
1916
+ });
1917
+ const connection = voiceSdk.joinVoiceChannel({
1918
+ channelId,
1919
+ guildId,
1920
+ adapterCreator,
1921
+ selfDeaf: false,
1922
+ selfMute: false,
1923
+ daveEncryption,
1924
+ decryptionFailureTolerance
1925
+ });
1926
+ try {
1927
+ await voiceSdk.entersState(connection, voiceSdk.VoiceConnectionStatus.Ready, connectReadyTimeoutMs);
1928
+ logVoiceVerbose(`join: connected to guild ${guildId} channel ${channelId}`);
1929
+ } catch (err) {
1930
+ logger.warn(`discord voice: join failed before ready: guild ${guildId} channel ${channelId} timeout=${connectReadyTimeoutMs}ms error=${formatErrorMessage(err)}`);
1931
+ destroyVoiceConnectionSafely({
1932
+ connection,
1933
+ voiceSdk,
1934
+ reason: `failed join cleanup guild ${guildId} channel ${channelId}`
1935
+ });
1936
+ return {
1937
+ ok: false,
1938
+ message: `Failed to join voice channel: ${formatErrorMessage(err)}`
1939
+ };
1940
+ }
1941
+ const sessionChannelId = channelInfo?.id ?? channelId;
1942
+ if (sessionChannelId !== channelId) logVoiceVerbose(`join: using session channel ${sessionChannelId} for voice channel ${channelId}`);
1943
+ let routeInfo;
1944
+ try {
1945
+ routeInfo = resolveDiscordVoiceAgentRoute({
1946
+ cfg: this.params.cfg,
1947
+ accountId: this.params.accountId,
1948
+ guildId,
1949
+ sessionChannelId,
1950
+ voiceConfig
1951
+ });
1952
+ } catch (err) {
1953
+ destroyVoiceConnectionSafely({
1954
+ connection,
1955
+ voiceSdk,
1956
+ reason: `voice agent session route failed guild ${guildId} channel ${channelId}`
1957
+ });
1958
+ return {
1959
+ ok: false,
1960
+ message: `Failed to resolve Discord voice agent session: ${formatErrorMessage(err)}`,
1961
+ guildId,
1962
+ channelId
1963
+ };
1964
+ }
1965
+ const { route, voiceRoute, agentSessionMode, agentSessionTarget } = routeInfo;
1966
+ logger.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?.voice ?? "provider-default"}`);
1967
+ const player = voiceSdk.createAudioPlayer();
1968
+ connection.subscribe(player);
1969
+ let speakingHandler;
1970
+ let speakingEndHandler;
1971
+ let disconnectedHandler;
1972
+ let destroyedHandler;
1973
+ let playerErrorHandler;
1974
+ let stopped = false;
1975
+ const clearSessionIfCurrent = () => {
1976
+ if (this.sessions.get(guildId)?.connection === connection) this.sessions.delete(guildId);
1977
+ };
1978
+ const stopEntry = (entry, options) => {
1979
+ if (stopped) return;
1980
+ stopped = true;
1981
+ if (speakingHandler) connection.receiver.speaking.off("start", speakingHandler);
1982
+ if (speakingEndHandler) connection.receiver.speaking.off("end", speakingEndHandler);
1983
+ stopVoiceCaptureState(entry.capture);
1984
+ if (disconnectedHandler) connection.off(voiceSdk.VoiceConnectionStatus.Disconnected, disconnectedHandler);
1985
+ if (destroyedHandler) connection.off(voiceSdk.VoiceConnectionStatus.Destroyed, destroyedHandler);
1986
+ if (playerErrorHandler) player.off("error", playerErrorHandler);
1987
+ entry.realtime?.close();
1988
+ entry.realtime = void 0;
1989
+ player.stop();
1990
+ if (options.destroyConnection) destroyVoiceConnectionSafely({
1991
+ connection,
1992
+ voiceSdk,
1993
+ reason: options.reason
1994
+ });
1995
+ };
1996
+ const entry = {
1997
+ guildId,
1998
+ guildName: channelInfo && "guild" in channelInfo && channelInfo.guild && typeof channelInfo.guild.name === "string" ? channelInfo.guild.name : void 0,
1999
+ channelId,
2000
+ channelName: channelInfo && "name" in channelInfo && typeof channelInfo.name === "string" ? channelInfo.name : void 0,
2001
+ sessionChannelId,
2002
+ voiceSessionKey: voiceRoute.sessionKey,
2003
+ route,
2004
+ connection,
2005
+ player,
2006
+ playbackQueue: Promise.resolve(),
2007
+ processingQueue: Promise.resolve(),
2008
+ capture: createVoiceCaptureState(),
2009
+ receiveRecovery: createVoiceReceiveRecoveryState(),
2010
+ stop: () => {
2011
+ stopEntry(entry, {
2012
+ destroyConnection: true,
2013
+ reason: `stop guild ${guildId} channel ${channelId}`
2014
+ });
2015
+ }
2016
+ };
2017
+ if (voiceMode !== "stt-tts") {
2018
+ entry.realtime = new DiscordRealtimeVoiceSession({
2019
+ bootstrapContextInstructions: await resolveDiscordVoiceRealtimeBootstrapContext({
2020
+ entry,
2021
+ cfg: this.params.cfg,
2022
+ discordConfig: this.params.discordConfig
2023
+ }),
2024
+ cfg: this.params.cfg,
2025
+ discordConfig: this.params.discordConfig,
2026
+ entry,
2027
+ mode: voiceMode,
2028
+ runAgentTurn: ({ context, message, toolsAllow, userId }) => this.runDiscordRealtimeAgentTurn({
2029
+ context,
2030
+ entry,
2031
+ message,
2032
+ toolsAllow,
2033
+ userId
2034
+ })
2035
+ });
2036
+ try {
2037
+ await entry.realtime.connect();
2038
+ } catch (err) {
2039
+ entry.realtime.close();
2040
+ destroyVoiceConnectionSafely({
2041
+ connection,
2042
+ voiceSdk,
2043
+ reason: `realtime setup failed guild ${guildId} channel ${channelId}`
2044
+ });
2045
+ return {
2046
+ ok: false,
2047
+ message: `Failed to start Discord realtime voice: ${formatErrorMessage(err)}`,
2048
+ guildId,
2049
+ channelId
2050
+ };
2051
+ }
2052
+ }
2053
+ speakingHandler = (userId) => {
2054
+ this.handleSpeakingStart(entry, userId).catch((err) => {
2055
+ logger.warn(`discord voice: capture failed: ${formatErrorMessage(err)}`);
2056
+ });
2057
+ };
2058
+ speakingEndHandler = (userId) => {
2059
+ this.scheduleCaptureFinalize(entry, userId, "speaker end");
2060
+ };
2061
+ disconnectedHandler = async () => {
2062
+ try {
2063
+ logVoiceVerbose(`disconnected: attempting recovery guild ${guildId} channel ${channelId} grace=${reconnectGraceMs}ms`);
2064
+ await Promise.race([voiceSdk.entersState(connection, voiceSdk.VoiceConnectionStatus.Signalling, reconnectGraceMs), voiceSdk.entersState(connection, voiceSdk.VoiceConnectionStatus.Connecting, reconnectGraceMs)]);
2065
+ logVoiceVerbose(`disconnected: recovery started guild ${guildId} channel ${channelId}`);
2066
+ } catch (err) {
2067
+ logger.warn(`discord voice: disconnect recovery failed: guild ${guildId} channel ${channelId} timeout=${reconnectGraceMs}ms error=${formatErrorMessage(err)}; destroying connection`);
2068
+ clearSessionIfCurrent();
2069
+ stopEntry(entry, {
2070
+ destroyConnection: true,
2071
+ reason: `disconnect recovery failed guild ${guildId} channel ${channelId}`
2072
+ });
2073
+ }
2074
+ };
2075
+ destroyedHandler = () => {
2076
+ clearSessionIfCurrent();
2077
+ stopEntry(entry, {
2078
+ destroyConnection: false,
2079
+ reason: `destroyed guild ${guildId} channel ${channelId}`
2080
+ });
2081
+ };
2082
+ playerErrorHandler = (err) => {
2083
+ logger.warn(`discord voice: playback error: ${formatErrorMessage(err)}`);
2084
+ };
2085
+ this.enableDaveReceivePassthrough(entry, "post-join warmup", 30);
2086
+ connection.receiver.speaking.on("start", speakingHandler);
2087
+ connection.receiver.speaking.on("end", speakingEndHandler);
2088
+ connection.on(voiceSdk.VoiceConnectionStatus.Disconnected, disconnectedHandler);
2089
+ connection.on(voiceSdk.VoiceConnectionStatus.Destroyed, destroyedHandler);
2090
+ player.on("error", playerErrorHandler);
2091
+ this.sessions.set(guildId, entry);
2092
+ this.fatalAutoJoinFailures.delete(formatAutoJoinFailureKey({
2093
+ guildId,
2094
+ channelId
2095
+ }));
2096
+ logger.info(`discord voice: joined guild=${guildId} channel=${channelId} mode=${voiceMode} agent=${route.agentId} voiceSession=${voiceRoute.sessionKey} supervisorSession=${route.sessionKey} voiceModel=${voiceConfig?.model ?? "route-default"}`);
2097
+ return {
2098
+ ok: true,
2099
+ message: `Joined ${formatMention({ channelId })}.`,
2100
+ guildId,
2101
+ channelId
2102
+ };
2103
+ }
2104
+ async leave(params, options) {
2105
+ const guildId = params.guildId.trim();
2106
+ logVoiceVerbose(`leave requested: guild ${guildId} channel ${params.channelId ?? "current"}`);
2107
+ const entry = this.sessions.get(guildId);
2108
+ if (!entry) return {
2109
+ ok: false,
2110
+ message: "Not connected to a voice channel."
2111
+ };
2112
+ if (params.channelId && params.channelId !== entry.channelId) return {
2113
+ ok: false,
2114
+ message: "Not connected to that voice channel."
2115
+ };
2116
+ entry.stop();
2117
+ this.sessions.delete(guildId);
2118
+ if (!options?.preserveFollowState) {
2119
+ this.followedVoiceGuilds.delete(guildId);
2120
+ this.deleteFollowedUserChannelsForGuild(guildId);
2121
+ }
2122
+ logVoiceVerbose(`leave: disconnected from guild ${guildId} channel ${entry.channelId}`);
2123
+ return {
2124
+ ok: true,
2125
+ message: `Left ${formatMention({ channelId: entry.channelId })}.`,
2126
+ guildId,
2127
+ channelId: entry.channelId
2128
+ };
2129
+ }
2130
+ async handleVoiceStateUpdate(data) {
2131
+ const guildId = data.guild_id?.trim();
2132
+ const userId = data.user_id?.trim();
2133
+ const channelId = data.channel_id?.trim();
2134
+ if (!guildId || !userId) return;
2135
+ if (this.botUserId && userId === this.botUserId) {
2136
+ await this.handleBotVoiceStateUpdate({
2137
+ guildId,
2138
+ channelId
2139
+ });
2140
+ return;
2141
+ }
2142
+ if (this.followUserIds.has(userId)) await this.handleFollowedUserVoiceStateUpdate({
2143
+ guildId,
2144
+ channelId,
2145
+ userId
2146
+ });
2147
+ }
2148
+ async handleBotVoiceStateUpdate(params) {
2149
+ const { guildId, channelId } = params;
2150
+ if (!channelId) return;
2151
+ const existing = this.sessions.get(guildId);
2152
+ if (this.isAllowedVoiceChannel({
2153
+ guildId,
2154
+ channelId
2155
+ })) {
2156
+ if (existing && existing.channelId !== channelId) {
2157
+ logger.warn(`discord voice: bot moved to allowed channel guild=${guildId} from=${existing.channelId} to=${channelId}; rebuilding voice session`);
2158
+ await this.join({
2159
+ guildId,
2160
+ channelId
2161
+ }, { preserveFollowState: this.isFollowOwnedGuild(guildId) });
2162
+ }
2163
+ return;
2164
+ }
2165
+ logger.warn(`discord voice: bot moved to non-allowed channel guild=${guildId} channel=${channelId}; leaving`);
2166
+ if (existing) await this.leave({ guildId });
2167
+ else {
2168
+ const voiceSdk = loadDiscordVoiceSdk();
2169
+ const connection = voiceSdk.getVoiceConnection(guildId);
2170
+ if (connection) destroyVoiceConnectionSafely({
2171
+ connection,
2172
+ voiceSdk,
2173
+ reason: `non-allowed voice state guild ${guildId} channel ${channelId}`
2174
+ });
2175
+ }
2176
+ const target = this.resolveVoiceResidencyTarget(guildId);
2177
+ if (target) {
2178
+ logger.warn(`discord voice: rejoining allowed voice channel guild=${guildId} channel=${target.channelId}`);
2179
+ await this.join(target);
2180
+ }
2181
+ }
2182
+ async handleFollowedUserVoiceStateUpdate(params) {
2183
+ if (!this.voiceEnabled || this.destroyed) return;
2184
+ const { guildId, channelId, userId } = params;
2185
+ const followKey = this.formatFollowedUserKey({
2186
+ guildId,
2187
+ userId
2188
+ });
2189
+ const existing = this.sessions.get(guildId);
2190
+ const wasFollowedVoiceSession = this.followedUserChannels.has(followKey) || this.followedVoiceGuilds.has(guildId);
2191
+ if (!channelId) {
2192
+ this.followedUserChannels.delete(followKey);
2193
+ if (existing && wasFollowedVoiceSession && !this.hasFollowedUserInChannel(existing)) await this.handoffToAnotherFollowedUserOrLeave({
2194
+ guildId,
2195
+ userId,
2196
+ existing,
2197
+ reason: "disconnected"
2198
+ });
2199
+ return;
2200
+ }
2201
+ if (!this.isAllowedVoiceChannel({
2202
+ guildId,
2203
+ channelId
2204
+ })) {
2205
+ this.followedUserChannels.delete(followKey);
2206
+ logger.warn(`discord voice: followed user joined non-allowed channel guild=${guildId} user=${userId} channel=${channelId}; ignoring`);
2207
+ if (existing && wasFollowedVoiceSession && !this.hasFollowedUserInChannel(existing)) await this.handoffToAnotherFollowedUserOrLeave({
2208
+ guildId,
2209
+ userId,
2210
+ existing,
2211
+ reason: "joined non-allowed channel"
2212
+ });
2213
+ return;
2214
+ }
2215
+ this.followedUserChannels.set(followKey, {
2216
+ guildId,
2217
+ channelId
2218
+ });
2219
+ if (existing?.channelId === channelId) {
2220
+ this.followedVoiceGuilds.add(guildId);
2221
+ return;
2222
+ }
2223
+ logger.info(`discord voice: following user guild=${guildId} user=${userId} channel=${channelId}`);
2224
+ const result = await this.join({
2225
+ guildId,
2226
+ channelId
2227
+ }, { preserveFollowState: true });
2228
+ if (!result.ok) {
2229
+ if (this.sessions.get(guildId)?.channelId === channelId) this.followedVoiceGuilds.add(guildId);
2230
+ else this.followedUserChannels.delete(followKey);
2231
+ logger.warn(`discord voice: failed to follow user guild=${guildId} user=${userId} channel=${channelId}: ${result.message}`);
2232
+ return;
2233
+ }
2234
+ this.followedVoiceGuilds.add(guildId);
2235
+ }
2236
+ async destroy() {
2237
+ this.destroyed = true;
2238
+ if (this.followUsersReconcileTimer) {
2239
+ clearInterval(this.followUsersReconcileTimer);
2240
+ this.followUsersReconcileTimer = null;
2241
+ }
2242
+ for (const entry of this.sessions.values()) entry.stop();
2243
+ this.sessions.clear();
2244
+ this.followedUserChannels.clear();
2245
+ this.followedVoiceGuilds.clear();
2246
+ }
2247
+ resolveFollowGuildIds() {
2248
+ const guildIds = /* @__PURE__ */ new Set();
2249
+ for (const guildId of Object.keys(this.params.discordConfig.guilds ?? {})) {
2250
+ const normalized = guildId.trim();
2251
+ if (normalized) guildIds.add(normalized);
2252
+ }
2253
+ for (const entry of normalizeVoiceChannelResidencies(this.params.discordConfig.voice?.autoJoin)) guildIds.add(entry.guildId);
2254
+ for (const entry of this.allowedChannels ?? []) guildIds.add(entry.guildId);
2255
+ for (const entry of this.sessions.values()) guildIds.add(entry.guildId);
2256
+ return Array.from(guildIds);
2257
+ }
2258
+ ensureFollowUsersReconcileTimer() {
2259
+ if (this.followUserIds.size === 0) return;
2260
+ if (this.followUsersReconcileTimer) return;
2261
+ this.followUsersReconcileTimer = setInterval(() => {
2262
+ this.reconcileFollowedUsers("interval").catch((err) => {
2263
+ logger.warn(`discord voice: follow user reconciliation failed: ${formatErrorMessage(err)}`);
2264
+ });
2265
+ }, FOLLOW_USERS_RECONCILE_INTERVAL_MS);
2266
+ this.followUsersReconcileTimer.unref?.();
2267
+ }
2268
+ async reconcileFollowedUsers(reason) {
2269
+ if (this.followUserIds.size === 0 || this.destroyed) return;
2270
+ if (this.followUsersReconcileTask) return this.followUsersReconcileTask;
2271
+ this.followUsersReconcileTask = this.runFollowedUsersReconcile(reason).finally(() => {
2272
+ this.followUsersReconcileTask = null;
2273
+ });
2274
+ return this.followUsersReconcileTask;
2275
+ }
2276
+ async runFollowedUsersReconcile(reason) {
2277
+ if (this.destroyed) return;
2278
+ const guildIds = this.resolveFollowGuildIds();
2279
+ if (guildIds.length === 0) {
2280
+ logVoiceVerbose(`follow user reconcile skipped reason=${reason}: no Discord guild ids are configured`);
2281
+ return;
2282
+ }
2283
+ logVoiceVerbose(`follow user reconcile reason=${reason}: ${this.followUserIds.size} users across ${guildIds.length} guilds`);
2284
+ const plans = this.selectFollowUserReconcilePlans(guildIds, reason);
2285
+ for (const plan of plans) {
2286
+ for (const userId of plan.userIds) {
2287
+ const voiceState = await getGuildVoiceState(this.params.client.rest, plan.guildId, userId).catch((err) => {
2288
+ if (!isUnknownDiscordVoiceStateError(err)) {
2289
+ logger.warn(`discord voice: follow user reconcile skipped transient voice state error guild=${plan.guildId} user=${userId} reason=${reason}: ${formatErrorMessage(err)}`);
2290
+ return "transient-error";
2291
+ }
2292
+ logVoiceVerbose(`follow user reconcile reason=${reason}: no voice state guild ${plan.guildId} user ${userId}: ${formatErrorMessage(err)}`);
2293
+ });
2294
+ if (this.destroyed) return;
2295
+ if (voiceState === "transient-error") continue;
2296
+ const channelId = voiceState?.channel_id?.trim();
2297
+ await this.handleFollowedUserVoiceStateUpdate({
2298
+ guildId: plan.guildId,
2299
+ channelId,
2300
+ userId
2301
+ });
2302
+ }
2303
+ if (plan.checkBotVoiceState) {
2304
+ if (this.destroyed) return;
2305
+ await this.disconnectStaleFollowedBotVoiceState({
2306
+ guildId: plan.guildId,
2307
+ reason
2308
+ });
2309
+ }
2310
+ }
2311
+ }
2312
+ selectFollowUserReconcilePlans(guildIds, reason) {
2313
+ const followedUserIds = Array.from(this.followUserIds);
2314
+ if (followedUserIds.length === 0) return [];
2315
+ let remainingLookups = FOLLOW_USERS_RECONCILE_MAX_REST_LOOKUPS_PER_RUN;
2316
+ const guildLimit = Math.min(guildIds.length, FOLLOW_USERS_RECONCILE_MAX_GUILDS_PER_RUN);
2317
+ const start = this.followUsersReconcileGuildCursor % guildIds.length;
2318
+ const plans = [];
2319
+ for (let offset = 0; offset < guildLimit && remainingLookups > 0; offset += 1) {
2320
+ if (this.botUserId && remainingLookups === 1) break;
2321
+ const guildId = guildIds[(start + offset) % guildIds.length];
2322
+ const userLimit = this.resolveFollowUserReconcileUserLookupLimit(followedUserIds.length, remainingLookups);
2323
+ if (userLimit <= 0) break;
2324
+ const selection = this.selectFollowUserReconcileUserIds(guildId, followedUserIds, userLimit);
2325
+ plans.push({
2326
+ guildId,
2327
+ userIds: selection.userIds,
2328
+ checkedAllUsers: selection.completedCycle,
2329
+ checkBotVoiceState: false
2330
+ });
2331
+ remainingLookups -= selection.userIds.length;
2332
+ }
2333
+ this.followUsersReconcileGuildCursor = (start + plans.length) % guildIds.length;
2334
+ this.assignFollowUserReconcileBotChecks(guildIds, plans, remainingLookups);
2335
+ if (plans.length < guildIds.length || plans.some((plan) => plan.userIds.length < followedUserIds.length)) logVoiceVerbose(`follow user reconcile reason=${reason}: sampling ${plans.length}/${guildIds.length} guilds and up to ${FOLLOW_USERS_RECONCILE_MAX_REST_LOOKUPS_PER_RUN} REST lookups`);
2336
+ return plans;
2337
+ }
2338
+ assignFollowUserReconcileBotChecks(guildIds, plans, remainingLookups) {
2339
+ if (!this.botUserId || remainingLookups <= 0 || plans.length === 0) return;
2340
+ const plansByGuild = new Map(plans.map((plan) => [plan.guildId, plan]));
2341
+ const start = this.followUsersReconcileBotGuildCursor % guildIds.length;
2342
+ let scanned = 0;
2343
+ let assigned = 0;
2344
+ for (; scanned < guildIds.length && assigned < remainingLookups; scanned += 1) {
2345
+ const guildId = guildIds[(start + scanned) % guildIds.length];
2346
+ const plan = plansByGuild.get(guildId);
2347
+ if (!plan?.checkedAllUsers) continue;
2348
+ plan.checkBotVoiceState = true;
2349
+ assigned += 1;
2350
+ }
2351
+ this.followUsersReconcileBotGuildCursor = (start + scanned) % guildIds.length;
2352
+ }
2353
+ resolveFollowUserReconcileUserLookupLimit(followedUserCount, remainingLookups) {
2354
+ const userLimit = Math.min(followedUserCount, remainingLookups);
2355
+ if (this.botUserId && followedUserCount > userLimit && remainingLookups > 1) return remainingLookups - 1;
2356
+ return userLimit;
2357
+ }
2358
+ selectFollowUserReconcileUserIds(guildId, followedUserIds, limit) {
2359
+ if (followedUserIds.length <= limit) {
2360
+ this.followUsersReconcileUserCursors.set(guildId, 0);
2361
+ return {
2362
+ userIds: followedUserIds,
2363
+ completedCycle: true
2364
+ };
2365
+ }
2366
+ const start = this.followUsersReconcileUserCursors.get(guildId) ?? 0;
2367
+ const selected = Array.from({ length: limit }, (_, offset) => followedUserIds[(start + offset) % followedUserIds.length]);
2368
+ const completedCycle = start + selected.length >= followedUserIds.length;
2369
+ this.followUsersReconcileUserCursors.set(guildId, (start + selected.length) % followedUserIds.length);
2370
+ return {
2371
+ userIds: selected,
2372
+ completedCycle
2373
+ };
2374
+ }
2375
+ formatFollowedUserKey(params) {
2376
+ return `${params.guildId}:${params.userId}`;
2377
+ }
2378
+ hasFollowedUserInChannel(entry) {
2379
+ return Array.from(this.followedUserChannels.values()).some((candidate) => candidate.guildId === entry.guildId && candidate.channelId === entry.channelId);
2380
+ }
2381
+ resolveFollowedUserHandoffTarget(guildId, currentChannelId) {
2382
+ for (const entry of this.followedUserChannels.values()) if (entry.guildId === guildId && entry.channelId !== currentChannelId && this.isAllowedVoiceChannel(entry)) return entry;
2383
+ return null;
2384
+ }
2385
+ async handoffToAnotherFollowedUserOrLeave(params) {
2386
+ const target = this.resolveFollowedUserHandoffTarget(params.guildId, params.existing.channelId);
2387
+ if (target) {
2388
+ logger.info(`discord voice: followed user ${params.reason} guild=${params.guildId} user=${params.userId}; moving to remaining followed user channel=${target.channelId}`);
2389
+ const result = await this.join(target, { preserveFollowState: true });
2390
+ if (result.ok) this.followedVoiceGuilds.add(params.guildId);
2391
+ else {
2392
+ logger.warn(`discord voice: failed to hand off followed user session guild=${params.guildId} channel=${target.channelId}: ${result.message}`);
2393
+ this.followedVoiceGuilds.delete(params.guildId);
2394
+ this.deleteFollowedUserChannelsForGuild(params.guildId);
2395
+ await this.leave({ guildId: params.guildId });
2396
+ }
2397
+ return;
2398
+ }
2399
+ logger.info(`discord voice: followed user ${params.reason} guild=${params.guildId} user=${params.userId}; leaving channel=${params.existing.channelId}`);
2400
+ await this.leave({ guildId: params.guildId });
2401
+ }
2402
+ isFollowOwnedGuild(guildId) {
2403
+ return this.followedVoiceGuilds.has(guildId) || Array.from(this.followedUserChannels.values()).some((entry) => entry.guildId === guildId);
2404
+ }
2405
+ deleteFollowedUserChannelsForGuild(guildId) {
2406
+ for (const [key, entry] of this.followedUserChannels.entries()) if (entry.guildId === guildId) this.followedUserChannels.delete(key);
2407
+ }
2408
+ async disconnectStaleFollowedBotVoiceState(params) {
2409
+ if (this.destroyed) return;
2410
+ const { guildId, reason } = params;
2411
+ if (Array.from(this.followedUserChannels.values()).some((entry) => entry.guildId === guildId)) return;
2412
+ const existing = this.sessions.get(guildId);
2413
+ if (existing) {
2414
+ if (this.followedVoiceGuilds.has(guildId)) {
2415
+ logger.info(`discord voice: follow reconcile leaving local session guild=${guildId} channel=${existing.channelId} reason=${reason}`);
2416
+ await this.leave({ guildId });
2417
+ }
2418
+ return;
2419
+ }
2420
+ if (!this.botUserId) return;
2421
+ const botVoiceState = await getGuildVoiceState(this.params.client.rest, guildId, this.botUserId).catch((err) => {
2422
+ if (!isUnknownDiscordVoiceStateError(err)) {
2423
+ logger.warn(`discord voice: follow reconcile skipped transient bot voice state error guild=${guildId} reason=${reason}: ${formatErrorMessage(err)}`);
2424
+ return "transient-error";
2425
+ }
2426
+ logVoiceVerbose(`follow user reconcile reason=${reason}: no bot voice state guild ${guildId}: ${formatErrorMessage(err)}`);
2427
+ });
2428
+ if (this.destroyed || botVoiceState === "transient-error") return;
2429
+ const botChannelId = botVoiceState?.channel_id?.trim();
2430
+ if (!botChannelId) return;
2431
+ const gateway = this.params.client.getPlugin("voice")?.getGateway(guildId);
2432
+ if (!gateway) {
2433
+ logger.warn(`discord voice: follow reconcile cannot disconnect stale bot voice state guild=${guildId} channel=${botChannelId}; gateway unavailable`);
2434
+ return;
2435
+ }
2436
+ logger.info(`discord voice: follow reconcile disconnecting stale bot voice state guild=${guildId} channel=${botChannelId} reason=${reason}`);
2437
+ gateway.updateVoiceState({
2438
+ guild_id: guildId,
2439
+ channel_id: null,
2440
+ self_mute: false,
2441
+ self_deaf: false
2442
+ });
2443
+ }
2444
+ resolveVoiceResidencyTarget(guildId) {
2445
+ const autoJoinTarget = normalizeVoiceChannelResidencies(this.params.discordConfig.voice?.autoJoin).toReversed().find((entry) => entry.guildId === guildId);
2446
+ if (autoJoinTarget && this.isAllowedVoiceChannel(autoJoinTarget)) return autoJoinTarget;
2447
+ if (this.allowedChannels === null) return null;
2448
+ const guildAllowed = this.allowedChannels.filter((entry) => entry.guildId === guildId);
2449
+ return guildAllowed.length === 1 ? guildAllowed[0] : null;
2450
+ }
2451
+ enqueueProcessing(entry, task) {
2452
+ entry.processingQueue = entry.processingQueue.then(task).catch((err) => logger.warn(`discord voice: processing failed: ${formatErrorMessage(err)}`));
2453
+ }
2454
+ enqueuePlayback(entry, task) {
2455
+ entry.playbackQueue = entry.playbackQueue.then(task).catch((err) => logger.warn(`discord voice: playback failed: ${formatErrorMessage(err)}`));
2456
+ }
2457
+ clearCaptureFinalizeTimer(entry, userId, generation) {
2458
+ return clearVoiceCaptureFinalizeTimer(entry.capture, userId, generation);
2459
+ }
2460
+ scheduleCaptureFinalize(entry, userId, reason) {
2461
+ const graceMs = resolveVoiceTimeoutMs(this.params.discordConfig.voice?.captureSilenceGraceMs, CAPTURE_FINALIZE_GRACE_MS);
2462
+ scheduleVoiceCaptureFinalize({
2463
+ state: entry.capture,
2464
+ userId,
2465
+ delayMs: graceMs,
2466
+ onFinalize: () => {
2467
+ logVoiceVerbose(`capture finalize: guild ${entry.guildId} channel ${entry.channelId} user ${userId} reason=${reason} grace=${graceMs}ms`);
2468
+ }
2469
+ });
2470
+ }
2471
+ async handleSpeakingStart(entry, userId) {
2472
+ if (!userId) return;
2473
+ if (this.botUserId && userId === this.botUserId) return;
2474
+ if (isVoiceCaptureActive(entry.capture, userId)) {
2475
+ const activeCapture = getActiveVoiceCapture(entry.capture, userId);
2476
+ const extended = activeCapture ? this.clearCaptureFinalizeTimer(entry, userId, activeCapture.generation) : false;
2477
+ logVoiceVerbose(`capture start ignored (already active): guild ${entry.guildId} channel ${entry.channelId} user ${userId}${extended ? " (finalize canceled)" : ""}`);
2478
+ return;
2479
+ }
2480
+ logVoiceVerbose(`capture start: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2481
+ const voiceSdk = loadDiscordVoiceSdk();
2482
+ const voiceMode = resolveDiscordVoiceMode(this.params.discordConfig.voice);
2483
+ const realtime = entry.realtime && isDiscordRealtimeVoiceMode(voiceMode) ? entry.realtime : void 0;
2484
+ if (entry.player.state.status === voiceSdk.AudioPlayerStatus.Playing && !realtime) {
2485
+ logVoiceVerbose(`capture ignored during playback: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2486
+ return;
2487
+ }
2488
+ const realtimeIngress = realtime ? await this.resolveDiscordVoiceIngressContext(entry, userId) : void 0;
2489
+ if (realtime && !realtimeIngress) {
2490
+ logVoiceVerbose(`realtime capture unauthorized: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2491
+ return;
2492
+ }
2493
+ if (entry.player.state.status === voiceSdk.AudioPlayerStatus.Playing && realtime) {
2494
+ if (!realtime.isBargeInEnabled()) {
2495
+ logger.info(`discord voice: realtime capture ignored during playback (barge-in disabled): guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2496
+ return;
2497
+ }
2498
+ logVoiceVerbose(`realtime barge-in: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2499
+ logger.info(`discord voice: realtime barge-in detected source=speaker-start guild=${entry.guildId} channel=${entry.channelId} user=${userId} playerStatus=${entry.player.state.status}`);
2500
+ realtime.handleBargeIn("speaker-start");
2501
+ }
2502
+ this.enableDaveReceivePassthrough(entry, `speaker ${userId} start`, 15);
2503
+ const stream = entry.connection.receiver.subscribe(userId, { end: { behavior: voiceSdk.EndBehaviorType.Manual } });
2504
+ const generation = beginVoiceCapture(entry.capture, userId, stream);
2505
+ let streamAborted = false;
2506
+ stream.on("error", (err) => {
2507
+ streamAborted = analyzeVoiceReceiveError(err).isAbortLike;
2508
+ this.handleReceiveError(entry, err);
2509
+ });
2510
+ try {
2511
+ if (realtime && realtimeIngress) {
2512
+ const turn = realtime.beginSpeakerTurn(realtimeIngress, userId);
2513
+ try {
2514
+ await this.processRealtimeAudioCapture({
2515
+ entry,
2516
+ stream,
2517
+ turn
2518
+ });
2519
+ } finally {
2520
+ turn.close();
2521
+ }
2522
+ return;
2523
+ }
2524
+ const pcm = await decodeOpusStream(stream, {
2525
+ onVerbose: logVoiceVerbose,
2526
+ onWarn: (message) => logger.warn(message)
2527
+ });
2528
+ if (pcm.length === 0) {
2529
+ logVoiceVerbose(`capture empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2530
+ return;
2531
+ }
2532
+ this.resetDecryptFailureState(entry);
2533
+ const { path: wavPath, durationSeconds } = await writeVoiceWavFile(pcm);
2534
+ if (durationSeconds < (streamAborted ? .2 : .35)) {
2535
+ logVoiceVerbose(`capture too short (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2536
+ return;
2537
+ }
2538
+ logVoiceVerbose(`capture ready (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2539
+ this.enqueueProcessing(entry, async () => {
2540
+ await this.processSegment({
2541
+ entry,
2542
+ wavPath,
2543
+ userId,
2544
+ durationSeconds
2545
+ });
2546
+ });
2547
+ } finally {
2548
+ finishVoiceCapture(entry.capture, userId, generation);
2549
+ }
2550
+ }
2551
+ async processRealtimeAudioCapture(params) {
2552
+ const { entry, stream, turn } = params;
2553
+ let resetReceiveRecovery = false;
2554
+ await decodeOpusStreamChunks(stream, {
2555
+ onChunk: (pcm) => {
2556
+ if (!resetReceiveRecovery && pcm.length > 0) {
2557
+ resetReceiveRecovery = true;
2558
+ this.resetDecryptFailureState(entry);
2559
+ }
2560
+ turn.sendInputAudio(pcm);
2561
+ },
2562
+ onVerbose: logVoiceVerbose,
2563
+ onWarn: (message) => logger.warn(message)
2564
+ });
2565
+ }
2566
+ async resolveDiscordVoiceIngressContext(entry, userId) {
2567
+ return await resolveDiscordVoiceIngressContext({
2568
+ entry,
2569
+ userId,
2570
+ cfg: this.params.cfg,
2571
+ discordConfig: this.params.discordConfig,
2572
+ ownerAllowFrom: this.ownerAllowFrom,
2573
+ fetchGuildName: async (guildId) => {
2574
+ const guild = await this.params.client.fetchGuild(guildId).catch(() => null);
2575
+ return guild && typeof guild.name === "string" && guild.name.trim() ? guild.name : void 0;
2576
+ },
2577
+ speakerContext: this.speakerContext
2578
+ });
2579
+ }
2580
+ async runDiscordRealtimeAgentTurn(params) {
2581
+ const { context, entry, message, toolsAllow, userId } = params;
2582
+ logger.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)}`);
2583
+ const turn = await runDiscordVoiceAgentTurn({
2584
+ entry,
2585
+ userId,
2586
+ message,
2587
+ cfg: this.params.cfg,
2588
+ discordConfig: this.params.discordConfig,
2589
+ runtime: this.params.runtime,
2590
+ context,
2591
+ toolsAllow,
2592
+ ownerAllowFrom: this.ownerAllowFrom,
2593
+ fetchGuildName: async (guildId) => {
2594
+ const guild = await this.params.client.fetchGuild(guildId).catch(() => null);
2595
+ return guild && typeof guild.name === "string" && guild.name.trim() ? guild.name : void 0;
2596
+ },
2597
+ speakerContext: this.speakerContext
2598
+ });
2599
+ if (!turn) {
2600
+ logVoiceVerbose(`realtime agent unauthorized: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
2601
+ return "";
2602
+ }
2603
+ logger.info(`discord voice: agent turn answer (${turn.text.length} chars) guild=${entry.guildId} channel=${entry.channelId} voiceSession=${entry.voiceSessionKey} supervisorSession=${entry.route.sessionKey} agent=${entry.route.agentId}: ${formatVoiceLogPreview(turn.text)}`);
2604
+ return turn.text;
2605
+ }
2606
+ async processSegment(params) {
2607
+ await processDiscordVoiceSegment({
2608
+ ...params,
2609
+ cfg: this.params.cfg,
2610
+ discordConfig: this.params.discordConfig,
2611
+ ownerAllowFrom: this.ownerAllowFrom,
2612
+ runtime: this.params.runtime,
2613
+ speakerContext: this.speakerContext,
2614
+ fetchGuildName: async (guildId) => {
2615
+ const guild = await this.params.client.fetchGuild(guildId).catch(() => null);
2616
+ return guild && typeof guild.name === "string" && guild.name.trim() ? guild.name : void 0;
2617
+ },
2618
+ enqueuePlayback: (entry, task) => {
2619
+ this.enqueuePlayback(entry, task);
2620
+ }
2621
+ });
2622
+ }
2623
+ handleReceiveError(entry, err) {
2624
+ const analysis = analyzeVoiceReceiveError(err);
2625
+ if (analysis.isAbortLike && !analysis.countsAsDecryptFailure) {
2626
+ logVoiceVerbose(`receive stream ended: ${analysis.message}`);
2627
+ return;
2628
+ }
2629
+ logger.warn(`discord voice: receive error: ${analysis.message}`);
2630
+ if (analysis.shouldAttemptPassthrough) this.enableDaveReceivePassthrough(entry, "receive decrypt error", 15);
2631
+ if (!analysis.countsAsDecryptFailure) return;
2632
+ const decryptFailure = noteVoiceDecryptFailure(entry.receiveRecovery);
2633
+ if (decryptFailure.firstFailure) logger.warn("discord voice: DAVE decrypt failures detected; voice receive may be unstable (upstream: discordjs/discord.js#11419)");
2634
+ if (!decryptFailure.shouldRecover) return;
2635
+ this.recoverFromDecryptFailures(entry).catch((recoverErr) => logger.warn(`discord voice: decrypt recovery failed: ${formatErrorMessage(recoverErr)}`)).finally(() => {
2636
+ finishVoiceDecryptRecovery(entry.receiveRecovery);
2637
+ });
2638
+ }
2639
+ enableDaveReceivePassthrough(entry, reason, expirySeconds) {
2640
+ const voiceSdk = loadDiscordVoiceSdk();
2641
+ return enableDaveReceivePassthrough({
2642
+ target: {
2643
+ guildId: entry.guildId,
2644
+ channelId: entry.channelId,
2645
+ connection: entry.connection
2646
+ },
2647
+ sdk: {
2648
+ VoiceConnectionStatus: { Ready: voiceSdk.VoiceConnectionStatus.Ready },
2649
+ NetworkingStatusCode: {
2650
+ Ready: voiceSdk.NetworkingStatusCode.Ready,
2651
+ Resuming: voiceSdk.NetworkingStatusCode.Resuming
2652
+ }
2653
+ },
2654
+ reason,
2655
+ expirySeconds,
2656
+ onVerbose: logVoiceVerbose,
2657
+ onWarn: (message) => logger.warn(message)
2658
+ });
2659
+ }
2660
+ resetDecryptFailureState(entry) {
2661
+ resetVoiceReceiveRecoveryState(entry.receiveRecovery);
2662
+ }
2663
+ async recoverFromDecryptFailures(entry) {
2664
+ const active = this.sessions.get(entry.guildId);
2665
+ if (!active || active.connection !== entry.connection) return;
2666
+ const preserveFollowState = this.isFollowOwnedGuild(entry.guildId);
2667
+ logger.warn(`discord voice: repeated decrypt failures; attempting rejoin for guild ${entry.guildId} channel ${entry.channelId}`);
2668
+ const leaveResult = await this.leave({ guildId: entry.guildId }, { preserveFollowState });
2669
+ if (!leaveResult.ok) {
2670
+ logger.warn(`discord voice: decrypt recovery leave failed: ${leaveResult.message}`);
2671
+ return;
2672
+ }
2673
+ const result = await this.join({
2674
+ guildId: entry.guildId,
2675
+ channelId: entry.channelId
2676
+ }, { preserveFollowState });
2677
+ if (!result.ok) logger.warn(`discord voice: rejoin after decrypt failures failed: ${result.message}`);
2678
+ }
2679
+ };
2680
+ var DiscordVoiceReadyListener$1 = class extends ReadyListener {
2681
+ constructor(manager) {
2682
+ super();
2683
+ this.manager = manager;
2684
+ }
2685
+ async handle(_data, _client) {
2686
+ startAutoJoin(this.manager);
2687
+ }
2688
+ };
2689
+ var DiscordVoiceResumedListener$1 = class extends ResumedListener {
2690
+ constructor(manager) {
2691
+ super();
2692
+ this.manager = manager;
2693
+ }
2694
+ async handle(_data, _client) {
2695
+ startAutoJoin(this.manager);
2696
+ }
2697
+ };
2698
+ var DiscordVoiceStateUpdateListener$1 = class extends VoiceStateUpdateListener {
2699
+ constructor(manager) {
2700
+ super();
2701
+ this.manager = manager;
2702
+ }
2703
+ async handle(data, _client) {
2704
+ await this.manager.handleVoiceStateUpdate(data);
2705
+ }
2706
+ };
2707
+ //#endregion
2708
+ //#region extensions/discord/src/voice/manager.runtime.ts
2709
+ var DiscordVoiceManager = class extends DiscordVoiceManager$1 {};
2710
+ var DiscordVoiceReadyListener = class extends DiscordVoiceReadyListener$1 {};
2711
+ var DiscordVoiceResumedListener = class extends DiscordVoiceResumedListener$1 {};
2712
+ var DiscordVoiceStateUpdateListener = class extends DiscordVoiceStateUpdateListener$1 {};
2713
+ //#endregion
2714
+ export { DiscordVoiceManager, DiscordVoiceReadyListener, DiscordVoiceResumedListener, DiscordVoiceStateUpdateListener };