UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

823 lines (822 loc) • 30.2 kB
import "./redact-BDinS1q9.js"; import { r as formatErrorMessage } from "./errors-BxyFnvP3.js"; import "./unhandled-rejections-CDJ8dOVP.js"; import "./logger-kwZIqwuw.js"; import "./paths-ViKUYWUK.js"; import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-idKIOMmb.js"; import "./theme-CdOoMzRk.js"; import { a as logVerbose, l as shouldLogVerbose } from "./globals-DBUMOBZ8.js"; import { t as createSubsystemLogger } from "./subsystem-DISldKSB.js"; import "./ansi-BEJF8NKS.js"; import "./boolean-C3GkJetE.js"; import "./env-Dnra1IpT.js"; import "./warning-filter-CBhOcgHd.js"; import "./utils-CS0Ikux6.js"; import "./links-8xRhWBQL.js"; import "./paths-C4Oy7wjk.js"; import "./auth-profiles-DRuJBw5y.js"; import { a as resolveAgentDir } from "./agent-scope-bjWqU22i.js"; import "./boundary-path-Dm0QJ7-y.js"; import "./boundary-file-read-DcZxlWD8.js"; import "./logger-BmpSCz93.js"; import "./exec-B5_AYfQG.js"; import "./workspace-D4K6QX9X.js"; import "./model-selection-BnFtDmP7.js"; import "./io-y3Az_Onx.js"; import "./shell-env-BOu7XeT_.js"; import "./safe-text-yavot2qw.js"; import "./version-CD3oP1-d.js"; import "./env-substitution-O6uabUmO.js"; import "./includes-Bj3eLUWH.js"; import "./zod-schema.providers-core-COy5nBQ0.js"; import "./legacy-web-search-BB-ZHEhz.js"; import "./registry-C5UkPpaO.js"; import "./config-state-Br0ucqMb.js"; import "./min-host-version-RMBWtIAR.js"; import "./manifest-registry-B5JNQdOM.js"; import "./runtime-guard-PhQ6PwQa.js"; import "./avatar-policy-B5nOfso_.js"; import "./ip-Ce8EDTBZ.js"; import "./zod-schema.agent-runtime-Dtg4Jy6G.js"; import "./zod-schema.core-BuVz8Rk7.js"; import "./config-D4zN4BRl.js"; import "./file-lock-DEiVq2ow.js"; import "./audit-fs-DTQIjp2r.js"; import "./resolve-B7S4PlnO.js"; import "./profiles-COPO-hHI.js"; import "./tailscale-CxY-91GZ.js"; import "./tailnet-DHiKSG7V.js"; import "./net-JAg9zL0G.js"; import "./auth-Buq0Niri.js"; import "./credentials-D8pfRimu.js"; import "./message-channel-BliByQBl.js"; import "./store-C5UK26Ce.js"; import "./runtime-Iz8uZ7EU.js"; import "./plugins-B09-vgme.js"; import "./sessions-D9ZgHCHb.js"; import "./paths-rhN9LKM_.js"; import "./session-write-lock-va3qZE6f.js"; import "./method-scopes-BiEi0X2g.js"; import "./call-CQbSO4Fr.js"; import "./prompt-style-C4CV4Y_p.js"; import "./ports-lsof-BLEgL_Gn.js"; import "./restart-stale-pids-BsPvlGJd.js"; import "./ports-FldL_Lhq.js"; import "./logging-CznuqaMu.js"; import "./commands-C6oAw_H-.js"; import "./issue-format-BtLIwOtN.js"; import "./identity-Dp-UIak4.js"; import "./heartbeat-Bdfr_onc.js"; import { Bi as ChannelType, Ci as ReadyListener, Fh as transcribeAudioFile, Kr as resolveDiscordOwnerAccess, Nm as resolveTtsConfig, Qr as formatDiscordUserTag, Um as textToSpeech, Zn as formatMention, nh as parseTtsDirectives, ta as agentCommandFromIngress } from "./pi-embedded-CbCYZxIb.js"; import "./internal-hooks-CIUghoK4.js"; import "./multimodal-B8yEZcl5.js"; import "./memory-search-B_aq08y5.js"; import "./provider-catalog-rVN7ZbR5.js"; import "./secret-input-DXoOLNgb.js"; import "./bindings-CFudGB9Z.js"; import { i as resolveAgentRoute } from "./resolve-route-DwFWP4JW.js"; import "./routing-zOQ0wwtV.js"; import "./identity-file-DVLib087.js"; import "./outbound-runtime-m-y0nd6F.js"; import "./provider-env-vars-CpUJqT5v.js"; import "./provider-auth-input-Bus9W_qh.js"; import "./provider-model-minimax-DSmX4BNO.js"; import "./provider-models-BKjzpTsb.js"; import "./anthropic-vertex-provider-B2x4YywE.js"; import "./provider-catalog-BTgF8VyO.js"; import "./provider-catalog-D0IlX18O.js"; import "./provider-catalog-BTmUX0Mp.js"; import "./provider-catalog-sph_Rl63.js"; import "./provider-catalog-C7tUyBwV.js"; import "./provider-catalog-C8dPZpHW.js"; import "./provider-catalog-BJNff1VI.js"; import "./provider-catalog-IAdymoqT.js"; import "./provider-catalog-Bjc7evzh.js"; import "./models-config.providers.discovery-CjkO08q6.js"; import "./text-runtime-DVXt5xhi.js"; import "./tool-catalog-BjSY4C4F.js"; import "./docker-Bhjg8g2t.js"; import "./sandbox-DTlKNieF.js"; import "./common-zReYuoMM.js"; import "./image-ops-By4YfyWa.js"; import "./thinking-CJoSRIGR.js"; import "./path-alias-guards-CwRM04O1.js"; import "./sandbox-paths-Cn8i8Jxm.js"; import "./channel-actions-fV93bLjV.js"; import "./mime-CsUtzcn2.js"; import "./ssrf-0bPJMoZR.js"; import "./fetch-guard-CYl1q2XH.js"; import "./provider-web-search-COZNygbd.js"; import "./manager-Bw8JrihM.js"; import "./config-schema-CPzP2Ds6.js"; import "./channel-plugin-common-ClptUZHU.js"; import "./status-helpers-Cflmo90d.js"; import "./conversation-runtime-nmWgJSXS.js"; import "./runtime-whatsapp-boundary-XjdkYMz_.js"; import "./pairing-store-BGKLrjo6.js"; import "./json-store--JDX3zNL.js"; import "./secret-file-Bif7RlZ-.js"; import "./channel-config-schema-CgpS17zB.js"; import "./setup-binary-C2MYZTCc.js"; import "./archive-pOxyr9r4.js"; import "./fs-safe-DZyOgpPN.js"; import "./signal-cli-install-fVOL9FvX.js"; import "./setup-wizard-proxy-DoOpOF8S.js"; import "./setup-BI3ohdrT.js"; import "./dm-policy-shared-DtcQProI.js"; import "./runtime-env-DQOYrXVl.js"; import "./temp-path-B91lt0LF.js"; import "./diagnostic-CDTtMQBT.js"; import "./logging-CCTKg_fh.js"; import "./config-runtime-BYNizC50.js"; import { n as isDangerousNameMatchingEnabled } from "./dangerous-name-matching-BQW4HoPt.js"; import "./level-overrides-DzIzQ3ZY.js"; import "./exec-approvals-BF_Qfdq8.js"; import "./webhook-ingress-D-H5frou.js"; import "./system-events-BU_NYynX.js"; import "./ssrf-policy-DYINyIKC.js"; import "./hook-runtime-BUYmDbaA.js"; import "./templating-BDXRiJUh.js"; import "./channel-reply-pipeline-BxH4-AP2.js"; import "./reply-history-n7nOPLta.js"; import "./commands-registry.data-BFXJWoqi.js"; import "./commands-registry-Bh9pJ817.js"; import "./frontmatter-CP5371Rm.js"; import "./env-overrides-BNSo89u5.js"; import "./skills-M0AZJeXx.js"; import "./skills-remote-BHxDA4Jw.js"; import "./workspace-dirs-DqDLiRvZ.js"; import "./pairing-token-DAszGmwD.js"; import "./skill-commands-D73dGR_l.js"; import "./config-CLRQPUSt.js"; import "./routes-XT2JfvT-.js"; import "./ssh-tunnel-LM52qY6N.js"; import "./server-middleware-BP59C6FL.js"; import "./provider-auth-ref-CQEp9sp3.js"; import "./provider-auth-helpers-Do3RFvdi.js"; import "./provider-api-key-auth-BEeRW3dq.js"; import "./pairing-labels-D27Y4Vv6.js"; import "./directory-runtime-D9Y42mW-.js"; import "./read-only-account-inspect-CJPRBFj7.js"; import "./src-BoNU6eQs.js"; import "./web-media-PKy3RbRG.js"; import "./media-understanding-BDOSvuM9.js"; import "./web-media-CiSbdGPs.js"; import "./state-paths-Dvb3Mfl3.js"; import "./llm-task-Br6Ixjlh.js"; import "./pi-model-discovery-DO3tFksS.js"; import "./exec-inline-eval-CpmxWJsW.js"; import "./target-registry-9OUOvlxj.js"; import "./external-content-DZI9vlJn.js"; import "./brave-onFD06fq.js"; import "./duckduckgo-CZuAOfiQ.js"; import "./exa-5bwgY04k.js"; import "./security-runtime-xlw0Fxx2.js"; import "./provider-usage-ClxTGn5c.js"; import "./provider-models-Bjv0V4OP.js"; import "./media-understanding-provider-DllGbg-v.js"; import "./media-understanding-provider-BDq4rFL-.js"; import "./provider-onboard-CSnPvkMM.js"; import "./onboard-BU8aRvq7.js"; import "./perplexity-web-search-provider-CI38RNUU.js"; import "./perplexity-CMZbsreI.js"; import "./model-definitions-CLagLj0g.js"; import "./onboard-0P7GBI2D.js"; import "./provider-catalog-CKHo9CRM.js"; import "./provider-models-Dmjtw6kn.js"; import "./stream-C-KGzzT0.js"; import "./web-search-CO1hvu_l.js"; import "./stagger-CFqdtCYL.js"; import "./command-secret-targets-DLs8jC2H.js"; import "./delivery-queue-DHURMSqX.js"; import "./channel-summary-Ctrv7moa.js"; import "./follow-redirects-CVAaqIk4.js"; import "./tool-policy-match-DQWWRSN4.js"; import "./runtime-CAdCdG-M.js"; import "./channel-status-BfM90KqH.js"; import "./discord-core-DLbIyXWy.js"; import "./cli-runtime-Cx1v7N7v.js"; import "./config-presence-DA3j8Nmi.js"; import "./query-expansion-BOJBTXsp.js"; import "./search-manager-DNBHwaee.js"; import "./acp-runtime-BHZj-SLU.js"; import "./telegram-core-DD8gCuaX.js"; import "./audit-BI48Fi3j.js"; import "./gateway-runtime-Dn2qAGY7.js"; import "./connection-auth-Nl2a3tDb.js"; import "./mcp-config-CDIWSqVk.js"; import "./runtime-OwPxoM0l.js"; import "./speech-runtime-Df1eEAUb.js"; import { createRequire } from "node:module"; import path from "node:path"; import fs from "node:fs/promises"; import { randomUUID } from "node:crypto"; //#region extensions/discord/src/voice/sdk-runtime.ts let cachedDiscordVoiceSdk = null; function loadDiscordVoiceSdk() { if (cachedDiscordVoiceSdk) return cachedDiscordVoiceSdk; cachedDiscordVoiceSdk = createRequire(import.meta.url)("@discordjs/voice"); return cachedDiscordVoiceSdk; } //#endregion //#region extensions/discord/src/voice/manager.ts const require = createRequire(import.meta.url); const SAMPLE_RATE = 48e3; const CHANNELS = 2; const BIT_DEPTH = 16; const MIN_SEGMENT_SECONDS = .35; const SILENCE_DURATION_MS = 1e3; const PLAYBACK_READY_TIMEOUT_MS = 15e3; const SPEAKING_READY_TIMEOUT_MS = 6e4; const DECRYPT_FAILURE_WINDOW_MS = 3e4; const DECRYPT_FAILURE_RECONNECT_THRESHOLD = 3; const DECRYPT_FAILURE_PATTERN = /DecryptionFailed\(/; const SPEAKER_CONTEXT_CACHE_TTL_MS = 6e4; const logger = createSubsystemLogger("discord/voice"); const logVoiceVerbose = (message) => { logVerbose(`discord voice: ${message}`); }; function mergeTtsConfig(base, override) { if (!override) return base; return { ...base, ...override, modelOverrides: { ...base.modelOverrides, ...override.modelOverrides }, elevenlabs: { ...base.elevenlabs, ...override.elevenlabs, voiceSettings: { ...base.elevenlabs?.voiceSettings, ...override.elevenlabs?.voiceSettings } }, openai: { ...base.openai, ...override.openai }, edge: { ...base.edge, ...override.edge } }; } function resolveVoiceTtsConfig(params) { if (!params.override) return { cfg: params.cfg, resolved: resolveTtsConfig(params.cfg) }; const merged = mergeTtsConfig(params.cfg.messages?.tts ?? {}, params.override); const messages = params.cfg.messages ?? {}; const cfg = { ...params.cfg, messages: { ...messages, tts: merged } }; return { cfg, resolved: resolveTtsConfig(cfg) }; } function buildWavBuffer(pcm) { const blockAlign = CHANNELS * BIT_DEPTH / 8; const byteRate = SAMPLE_RATE * blockAlign; const header = Buffer.alloc(44); header.write("RIFF", 0); header.writeUInt32LE(36 + pcm.length, 4); header.write("WAVE", 8); header.write("fmt ", 12); header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(CHANNELS, 22); header.writeUInt32LE(SAMPLE_RATE, 24); header.writeUInt32LE(byteRate, 28); header.writeUInt16LE(blockAlign, 32); header.writeUInt16LE(BIT_DEPTH, 34); header.write("data", 36); header.writeUInt32LE(pcm.length, 40); return Buffer.concat([header, pcm]); } let warnedOpusMissing = false; function createOpusDecoder() { try { const OpusScript = require("opusscript"); return { decoder: new OpusScript(SAMPLE_RATE, CHANNELS, OpusScript.Application.AUDIO), name: "opusscript" }; } catch (err) { if (!warnedOpusMissing) { warnedOpusMissing = true; logger.warn(`discord voice: opusscript unavailable (${formatErrorMessage(err)}); cannot decode voice audio`); } } return null; } async function decodeOpusStream(stream) { const selected = createOpusDecoder(); if (!selected) return Buffer.alloc(0); logVoiceVerbose(`opus decoder: ${selected.name}`); const chunks = []; try { for await (const chunk of stream) { if (!chunk || !(chunk instanceof Buffer) || chunk.length === 0) continue; const decoded = selected.decoder.decode(chunk); if (decoded && decoded.length > 0) chunks.push(Buffer.from(decoded)); } } catch (err) { if (shouldLogVerbose()) logVerbose(`discord voice: opus decode failed: ${formatErrorMessage(err)}`); } return chunks.length > 0 ? Buffer.concat(chunks) : Buffer.alloc(0); } function estimateDurationSeconds(pcm) { const bytesPerSample = BIT_DEPTH / 8 * CHANNELS; if (bytesPerSample <= 0) return 0; return pcm.length / (bytesPerSample * SAMPLE_RATE); } async function writeWavFile(pcm) { const tempDir = await fs.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), "discord-voice-")); const filePath = path.join(tempDir, `segment-${randomUUID()}.wav`); const wav = buildWavBuffer(pcm); await fs.writeFile(filePath, wav); scheduleTempCleanup(tempDir); return { path: filePath, durationSeconds: estimateDurationSeconds(pcm) }; } function scheduleTempCleanup(tempDir, delayMs = 1800 * 1e3) { setTimeout(() => { fs.rm(tempDir, { recursive: true, force: true }).catch((err) => { if (shouldLogVerbose()) logVerbose(`discord voice: temp cleanup failed for ${tempDir}: ${formatErrorMessage(err)}`); }); }, delayMs).unref(); } async function transcribeAudio(params) { return (await transcribeAudioFile({ filePath: params.filePath, cfg: params.cfg, agentDir: resolveAgentDir(params.cfg, params.agentId), mime: "audio/wav" })).text?.trim() || void 0; } var DiscordVoiceManager$1 = class { constructor(params) { this.params = params; this.sessions = /* @__PURE__ */ new Map(); this.autoJoinTask = null; this.speakerContextCache = /* @__PURE__ */ new Map(); this.botUserId = params.botUserId; this.voiceEnabled = params.discordConfig.voice?.enabled !== false; this.ownerAllowFrom = params.discordConfig.allowFrom ?? params.discordConfig.dm?.allowFrom ?? []; this.allowDangerousNameMatching = isDangerousNameMatchingEnabled(params.discordConfig); } setBotUserId(id) { if (id) this.botUserId = id; } isEnabled() { return this.voiceEnabled; } async autoJoin() { if (!this.voiceEnabled) return; if (this.autoJoinTask) return this.autoJoinTask; this.autoJoinTask = (async () => { const entries = this.params.discordConfig.voice?.autoJoin ?? []; logVoiceVerbose(`autoJoin: ${entries.length} entries`); const seenGuilds = /* @__PURE__ */ new Set(); for (const entry of entries) { const guildId = entry.guildId.trim(); if (!guildId) continue; if (seenGuilds.has(guildId)) { logger.warn(`discord voice: autoJoin has multiple entries for guild ${guildId}; skipping`); continue; } seenGuilds.add(guildId); logVoiceVerbose(`autoJoin: joining guild ${guildId} channel ${entry.channelId}`); await this.join({ guildId: entry.guildId, channelId: entry.channelId }); } })().finally(() => { this.autoJoinTask = null; }); return this.autoJoinTask; } status() { return Array.from(this.sessions.values()).map((session) => ({ ok: true, message: `connected: guild ${session.guildId} channel ${session.channelId}`, guildId: session.guildId, channelId: session.channelId })); } async join(params) { if (!this.voiceEnabled) return { ok: false, message: "Discord voice is disabled (channels.discord.voice.enabled)." }; const guildId = params.guildId.trim(); const channelId = params.channelId.trim(); if (!guildId || !channelId) return { ok: false, message: "Missing guildId or channelId." }; logVoiceVerbose(`join requested: guild ${guildId} channel ${channelId}`); const existing = this.sessions.get(guildId); if (existing && existing.channelId === channelId) { logVoiceVerbose(`join: already connected to guild ${guildId} channel ${channelId}`); return { ok: true, message: `Already connected to ${formatMention({ channelId })}.`, guildId, channelId }; } if (existing) { logVoiceVerbose(`join: replacing existing session for guild ${guildId}`); await this.leave({ guildId }); } const channelInfo = await this.params.client.fetchChannel(channelId).catch(() => null); if (!channelInfo || "type" in channelInfo && !isVoiceChannel(channelInfo.type)) return { ok: false, message: `Channel ${channelId} is not a voice channel.` }; const channelGuildId = "guildId" in channelInfo ? channelInfo.guildId : void 0; if (channelGuildId && channelGuildId !== guildId) return { ok: false, message: "Voice channel is not in this guild." }; const voicePlugin = this.params.client.getPlugin("voice"); if (!voicePlugin) return { ok: false, message: "Discord voice plugin is not available." }; const adapterCreator = voicePlugin.getGatewayAdapterCreator(guildId); const daveEncryption = this.params.discordConfig.voice?.daveEncryption; const decryptionFailureTolerance = this.params.discordConfig.voice?.decryptionFailureTolerance; logVoiceVerbose(`join: DAVE settings encryption=${daveEncryption === false ? "off" : "on"} tolerance=${decryptionFailureTolerance ?? "default"}`); const voiceSdk = loadDiscordVoiceSdk(); const connection = voiceSdk.joinVoiceChannel({ channelId, guildId, adapterCreator, selfDeaf: false, selfMute: false, daveEncryption, decryptionFailureTolerance }); try { await voiceSdk.entersState(connection, voiceSdk.VoiceConnectionStatus.Ready, PLAYBACK_READY_TIMEOUT_MS); logVoiceVerbose(`join: connected to guild ${guildId} channel ${channelId}`); } catch (err) { connection.destroy(); return { ok: false, message: `Failed to join voice channel: ${formatErrorMessage(err)}` }; } const sessionChannelId = channelInfo?.id ?? channelId; if (sessionChannelId !== channelId) logVoiceVerbose(`join: using session channel ${sessionChannelId} for voice channel ${channelId}`); const route = resolveAgentRoute({ cfg: this.params.cfg, channel: "discord", accountId: this.params.accountId, guildId, peer: { kind: "channel", id: sessionChannelId } }); const player = voiceSdk.createAudioPlayer(); connection.subscribe(player); let speakingHandler; let disconnectedHandler; let destroyedHandler; let playerErrorHandler; const clearSessionIfCurrent = () => { if (this.sessions.get(guildId)?.connection === connection) this.sessions.delete(guildId); }; const entry = { guildId, channelId, sessionChannelId, route, connection, player, playbackQueue: Promise.resolve(), processingQueue: Promise.resolve(), activeSpeakers: /* @__PURE__ */ new Set(), decryptFailureCount: 0, lastDecryptFailureAt: 0, decryptRecoveryInFlight: false, stop: () => { if (speakingHandler) connection.receiver.speaking.off("start", speakingHandler); if (disconnectedHandler) connection.off(voiceSdk.VoiceConnectionStatus.Disconnected, disconnectedHandler); if (destroyedHandler) connection.off(voiceSdk.VoiceConnectionStatus.Destroyed, destroyedHandler); if (playerErrorHandler) player.off("error", playerErrorHandler); player.stop(); connection.destroy(); } }; speakingHandler = (userId) => { this.handleSpeakingStart(entry, userId).catch((err) => { logger.warn(`discord voice: capture failed: ${formatErrorMessage(err)}`); }); }; disconnectedHandler = async () => { try { await Promise.race([voiceSdk.entersState(connection, voiceSdk.VoiceConnectionStatus.Signalling, 5e3), voiceSdk.entersState(connection, voiceSdk.VoiceConnectionStatus.Connecting, 5e3)]); } catch { clearSessionIfCurrent(); connection.destroy(); } }; destroyedHandler = () => { clearSessionIfCurrent(); }; playerErrorHandler = (err) => { logger.warn(`discord voice: playback error: ${formatErrorMessage(err)}`); }; connection.receiver.speaking.on("start", speakingHandler); connection.on(voiceSdk.VoiceConnectionStatus.Disconnected, disconnectedHandler); connection.on(voiceSdk.VoiceConnectionStatus.Destroyed, destroyedHandler); player.on("error", playerErrorHandler); this.sessions.set(guildId, entry); return { ok: true, message: `Joined ${formatMention({ channelId })}.`, guildId, channelId }; } async leave(params) { const guildId = params.guildId.trim(); logVoiceVerbose(`leave requested: guild ${guildId} channel ${params.channelId ?? "current"}`); const entry = this.sessions.get(guildId); if (!entry) return { ok: false, message: "Not connected to a voice channel." }; if (params.channelId && params.channelId !== entry.channelId) return { ok: false, message: "Not connected to that voice channel." }; entry.stop(); this.sessions.delete(guildId); logVoiceVerbose(`leave: disconnected from guild ${guildId} channel ${entry.channelId}`); return { ok: true, message: `Left ${formatMention({ channelId: entry.channelId })}.`, guildId, channelId: entry.channelId }; } async destroy() { for (const entry of this.sessions.values()) entry.stop(); this.sessions.clear(); } enqueueProcessing(entry, task) { entry.processingQueue = entry.processingQueue.then(task).catch((err) => logger.warn(`discord voice: processing failed: ${formatErrorMessage(err)}`)); } enqueuePlayback(entry, task) { entry.playbackQueue = entry.playbackQueue.then(task).catch((err) => logger.warn(`discord voice: playback failed: ${formatErrorMessage(err)}`)); } async handleSpeakingStart(entry, userId) { if (!userId || entry.activeSpeakers.has(userId)) return; if (this.botUserId && userId === this.botUserId) return; entry.activeSpeakers.add(userId); logVoiceVerbose(`capture start: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`); const voiceSdk = loadDiscordVoiceSdk(); if (entry.player.state.status === voiceSdk.AudioPlayerStatus.Playing) entry.player.stop(true); const stream = entry.connection.receiver.subscribe(userId, { end: { behavior: voiceSdk.EndBehaviorType.AfterSilence, duration: SILENCE_DURATION_MS } }); stream.on("error", (err) => { this.handleReceiveError(entry, err); }); try { const pcm = await decodeOpusStream(stream); if (pcm.length === 0) { logVoiceVerbose(`capture empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`); return; } this.resetDecryptFailureState(entry); const { path: wavPath, durationSeconds } = await writeWavFile(pcm); if (durationSeconds < MIN_SEGMENT_SECONDS) { logVoiceVerbose(`capture too short (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId} user ${userId}`); return; } logVoiceVerbose(`capture ready (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId} user ${userId}`); this.enqueueProcessing(entry, async () => { await this.processSegment({ entry, wavPath, userId, durationSeconds }); }); } finally { entry.activeSpeakers.delete(userId); } } async processSegment(params) { const { entry, wavPath, userId, durationSeconds } = params; logVoiceVerbose(`segment processing (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId}`); const transcript = await transcribeAudio({ cfg: this.params.cfg, agentId: entry.route.agentId, filePath: wavPath }); if (!transcript) { logVoiceVerbose(`transcription empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`); return; } logVoiceVerbose(`transcription ok (${transcript.length} chars): guild ${entry.guildId} channel ${entry.channelId}`); const speaker = await this.resolveSpeakerContext(entry.guildId, userId); const replyText = ((await agentCommandFromIngress({ message: speaker.label ? `${speaker.label}: ${transcript}` : transcript, sessionKey: entry.route.sessionKey, agentId: entry.route.agentId, messageChannel: "discord", senderIsOwner: speaker.senderIsOwner, allowModelOverride: false, deliver: false }, this.params.runtime)).payloads ?? []).map((payload) => payload.text).filter((text) => typeof text === "string" && text.trim()).join("\n").trim(); if (!replyText) { logVoiceVerbose(`reply empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`); return; } logVoiceVerbose(`reply ok (${replyText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`); const { cfg: ttsCfg, resolved: ttsConfig } = resolveVoiceTtsConfig({ cfg: this.params.cfg, override: this.params.discordConfig.voice?.tts }); const directive = parseTtsDirectives(replyText, ttsConfig.modelOverrides, ttsConfig.openai.baseUrl); const speakText = directive.overrides.ttsText ?? directive.cleanedText.trim(); if (!speakText) { logVoiceVerbose(`tts skipped (empty): guild ${entry.guildId} channel ${entry.channelId} user ${userId}`); return; } const ttsResult = await textToSpeech({ text: speakText, cfg: ttsCfg, channel: "discord", overrides: directive.overrides }); if (!ttsResult.success || !ttsResult.audioPath) { logger.warn(`discord voice: TTS failed: ${ttsResult.error ?? "unknown error"}`); return; } const audioPath = ttsResult.audioPath; logVoiceVerbose(`tts ok (${speakText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`); this.enqueuePlayback(entry, async () => { logVoiceVerbose(`playback start: guild ${entry.guildId} channel ${entry.channelId} file ${path.basename(audioPath)}`); const voiceSdk = loadDiscordVoiceSdk(); const resource = voiceSdk.createAudioResource(audioPath); entry.player.play(resource); await voiceSdk.entersState(entry.player, voiceSdk.AudioPlayerStatus.Playing, PLAYBACK_READY_TIMEOUT_MS).catch(() => void 0); await voiceSdk.entersState(entry.player, voiceSdk.AudioPlayerStatus.Idle, SPEAKING_READY_TIMEOUT_MS).catch(() => void 0); logVoiceVerbose(`playback done: guild ${entry.guildId} channel ${entry.channelId}`); }); } handleReceiveError(entry, err) { const message = formatErrorMessage(err); logger.warn(`discord voice: receive error: ${message}`); if (!DECRYPT_FAILURE_PATTERN.test(message)) return; const now = Date.now(); if (now - entry.lastDecryptFailureAt > DECRYPT_FAILURE_WINDOW_MS) entry.decryptFailureCount = 0; entry.lastDecryptFailureAt = now; entry.decryptFailureCount += 1; if (entry.decryptFailureCount === 1) logger.warn("discord voice: DAVE decrypt failures detected; voice receive may be unstable (upstream: discordjs/discord.js#11419)"); if (entry.decryptFailureCount < DECRYPT_FAILURE_RECONNECT_THRESHOLD || entry.decryptRecoveryInFlight) return; entry.decryptRecoveryInFlight = true; this.resetDecryptFailureState(entry); this.recoverFromDecryptFailures(entry).catch((recoverErr) => logger.warn(`discord voice: decrypt recovery failed: ${formatErrorMessage(recoverErr)}`)).finally(() => { entry.decryptRecoveryInFlight = false; }); } resetDecryptFailureState(entry) { entry.decryptFailureCount = 0; entry.lastDecryptFailureAt = 0; } async recoverFromDecryptFailures(entry) { const active = this.sessions.get(entry.guildId); if (!active || active.connection !== entry.connection) return; logger.warn(`discord voice: repeated decrypt failures; attempting rejoin for guild ${entry.guildId} channel ${entry.channelId}`); const leaveResult = await this.leave({ guildId: entry.guildId }); if (!leaveResult.ok) { logger.warn(`discord voice: decrypt recovery leave failed: ${leaveResult.message}`); return; } const result = await this.join({ guildId: entry.guildId, channelId: entry.channelId }); if (!result.ok) logger.warn(`discord voice: rejoin after decrypt failures failed: ${result.message}`); } resolveSpeakerIsOwner(params) { return resolveDiscordOwnerAccess({ allowFrom: this.ownerAllowFrom, sender: { id: params.id, name: params.name, tag: params.tag }, allowNameMatching: this.allowDangerousNameMatching }).ownerAllowed; } resolveSpeakerContextCacheKey(guildId, userId) { return `${guildId}:${userId}`; } getCachedSpeakerContext(guildId, userId) { const key = this.resolveSpeakerContextCacheKey(guildId, userId); const cached = this.speakerContextCache.get(key); if (!cached) return; if (cached.expiresAt <= Date.now()) { this.speakerContextCache.delete(key); return; } return { label: cached.label, senderIsOwner: cached.senderIsOwner }; } setCachedSpeakerContext(guildId, userId, context) { const key = this.resolveSpeakerContextCacheKey(guildId, userId); this.speakerContextCache.set(key, { label: context.label, senderIsOwner: context.senderIsOwner, expiresAt: Date.now() + SPEAKER_CONTEXT_CACHE_TTL_MS }); } async resolveSpeakerContext(guildId, userId) { const cached = this.getCachedSpeakerContext(guildId, userId); if (cached) return cached; const identity = await this.resolveSpeakerIdentity(guildId, userId); const context = { label: identity.label, senderIsOwner: this.resolveSpeakerIsOwner({ id: identity.id, name: identity.name, tag: identity.tag }) }; this.setCachedSpeakerContext(guildId, userId, context); return context; } async resolveSpeakerIdentity(guildId, userId) { try { const member = await this.params.client.fetchMember(guildId, userId); const username = member.user?.username ?? void 0; return { id: userId, label: member.nickname ?? member.user?.globalName ?? username ?? userId, name: username, tag: member.user ? formatDiscordUserTag(member.user) : void 0 }; } catch { try { const user = await this.params.client.fetchUser(userId); const username = user.username ?? void 0; return { id: userId, label: user.globalName ?? username ?? userId, name: username, tag: formatDiscordUserTag(user) }; } catch { return { id: userId, label: userId }; } } } }; var DiscordVoiceReadyListener$1 = class extends ReadyListener { constructor(manager) { super(); this.manager = manager; } async handle() { await this.manager.autoJoin(); } }; function isVoiceChannel(type) { return type === ChannelType.GuildVoice || type === ChannelType.GuildStageVoice; } //#endregion //#region extensions/discord/src/voice/manager.runtime.ts var DiscordVoiceManager = class extends DiscordVoiceManager$1 {}; var DiscordVoiceReadyListener = class extends DiscordVoiceReadyListener$1 {}; //#endregion export { DiscordVoiceManager, DiscordVoiceReadyListener };