UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

336 lines (335 loc) • 15.8 kB
import { F as resolveNonNegativeIntegerOption, R as resolveTimerTimeoutMs } from "../number-coercion-D6u-4YD8.mjs"; import { i as truncateWithMarker } from "../utf16-slice-CuDyEXgS.mjs"; import { t as formatErrorMessage } from "../errors-BKzCeTYb.mjs"; import { A as withTimeout } from "../fs-safe-BbWvmdVn.mjs"; import { n as TALK_EVENT_TYPES } from "../talk-event-vocabulary-BcwhoICH.mjs"; import { n as createRealtimeVoiceAudioQueue, t as RealtimeVoiceSessionLifecycle } from "../realtime-session-lifecycle-CalKzaqB.mjs"; import { _ as toOpenAICompatibleRealtimeAudioFormat, f as shouldAutoControlRealtimeVoiceAgentText, g as realtimeVoiceAudioDurationMs, h as normalizeRealtimeVoiceResponseOutcome, i as buildRealtimeVoiceAgentCancelProviderResult, m as REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ, n as REALTIME_VOICE_AGENT_CONTROL_TOOL, p as REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ, r as REALTIME_VOICE_AGENT_CONTROL_TOOL_NAME, s as classifyRealtimeVoiceAgentControlText, u as parseRealtimeVoiceAgentControlToolArgs } from "../agent-run-control-shared-BSSIeKkd.mjs"; import { c as resamplePcmTo8k, i as mulawToPcm, n as convertPcmToMulaw8k, s as resamplePcm, t as createRealtimeVoiceOutputActivityTracker } from "../output-activity-tracker-B0aXImJ4.mjs"; import { a as buildRealtimeVoiceAgentConsultPolicyInstructions, c as buildRealtimeVoiceSessionInstructions, d as parseRealtimeVoiceAgentConsultArgs, f as resolveRealtimeVoiceAgentConsultToolPolicy, i as buildRealtimeVoiceAgentConsultChatMessage, m as resolveRealtimeVoiceAgentConsultToolsAllow, n as REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME, p as resolveRealtimeVoiceAgentConsultTools, r as REALTIME_VOICE_AGENT_CONSULT_TOOL_POLICIES, s as buildRealtimeVoiceAgentConsultWorkingResponse, t as REALTIME_VOICE_AGENT_CONSULT_TOOL, u as isRealtimeVoiceAgentConsultToolPolicy } from "../agent-consult-tool-DTRzLYLc.mjs"; import { t as createRealtimeVoiceAudioPortSender } from "../audio-output-port-lTm7lMxt.mjs"; import { i as readPcm16AudioStats, n as createSpeechThresholdGate, r as isRealtimeVoiceAudioAudible, t as calculateMulawRms } from "../audio-energy-EzCntkPJ.mjs"; import { a as sortRealtimeVoiceActivationNames, i as normalizeSupportedRealtimeVoiceActivationName, n as matchRealtimeVoiceActivationName, r as normalizeRealtimeVoiceActivationNamePrefix, t as isSupportedRealtimeVoiceActivationName } from "../activation-name-CEC5KqSy.mjs"; import { a as classifyRealtimeVoiceConsultToolCall, i as buildRealtimeVoiceSpeakExactMessage, n as controlRealtimeVoiceAgentRun, s as registerRealtimeVoiceSelection, t as buildRealtimeVoiceAgentErrorProviderResult } from "../agent-run-control--XOOWbJ9.mjs"; import { A as readRealtimeVoiceConsultQuestion, C as isRealtimeVoiceWakeNameRequired, D as resolveRealtimeVoiceSessionPolicy, E as resolveRealtimeVoiceMinBargeInAudioEndMs, F as projectInternalRealtimeVoicePublicConfig, M as createTalkSessionController, N as recordTalkObservabilityEvent, O as createRealtimeVoiceForcedConsultCoordinator, S as consultRealtimeVoiceAgent, T as resolveRealtimeVoiceInterruptResponseOnInputAudio, _ as createRealtimeVoiceAgentTalkbackQueue, a as getRealtimeVoiceTranscriptHealth, b as assertRealtimeVoiceAgentConsultModelSelectionUnlockedAsync, c as recordRealtimeVoiceTranscript, d as resolveConfiguredRealtimeVoiceProvider, f as resolveConfiguredRealtimeVoiceProviderAsync, g as listRealtimeVoiceProviders, h as getRealtimeVoiceProvider, i as getRealtimeVoiceBridgeEventHealth, j as readSpeakableRealtimeVoiceToolResult, k as matchRealtimeVoiceConsultQuestions, l as createRealtimeVoiceBridgeSession, m as canonicalizeRealtimeVoiceProviderId, o as isLikelyRealtimeVoiceAssistantEchoTranscript, r as extendRealtimeVoiceOutputEchoSuppression, s as recordRealtimeVoiceBridgeEvent, t as createRealtimeVoiceSessionHarness, v as REALTIME_VOICE_AGENT_CONSULT_SENDER_AUTH_VERSION, w as resolveRealtimeVoiceBargeIn, y as assertRealtimeVoiceAgentConsultModelSelectionUnlocked } from "../realtime-session-harness-DxmMQ7E9.mjs"; //#region src/talk/consult-transcript.ts /** * ASR often emits partial fragments or polite closings that should not trigger * an OpenClaw consult. This classifier names those skip reasons for callers. */ const REALTIME_VOICE_CONSULT_TRAILING_FRAGMENT_WORDS = /* @__PURE__ */ new Set([ "a", "about", "an", "and", "as", "at", "because", "but", "by", "for", "from", "in", "of", "on", "or", "so", "that", "the", "then", "to", "with" ]); const REALTIME_VOICE_CLOSING_REMAINDER = new RegExp(String.raw`^(?:(?:${[ "ok(?:ay)?|all right|alright|well|so|and", "thanks(?: a lot| so much)?|thank you(?: very much)?|take care", "have a (?:good|nice|great) (?:day|night|evening|weekend)", "guys|everyone|everybody|all|folks|you all", "for now|now|later|soon|tomorrow|tonight|next (?:time|week|month|year|weekend)", "(?:on |next )?(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday)", String.raw`in (?:a|a few|few|one|two|three|four|five|six|seven|eight|nine|ten|\d+) (?:second|minute|moment)s?`, "in a bit|in the (?:morning|afternoon|evening)" ].join("|")})\b|[.! ,;:—–-])*$`); function classifySkippableRealtimeVoiceConsultTranscript(e) { const t = e.replace(/\s+/g, " ").trim().toLowerCase(); if (!t) return "empty"; if (/(\.\.\.|…)\s*$/.test(t)) return "incomplete-transcript"; const n = t.match(/[a-z']+$/)?.[0]?.replace(/^'+|'+$/g, ""); if (n && REALTIME_VOICE_CONSULT_TRAILING_FRAGMENT_WORDS.has(n)) return "trailing-fragment"; const r = t.replace(/\b(?:(?:i['’]?ll|i will) be (?:right )?back|see you|bye(?:[- ]bye)?|good[- ]?bye)\b/g, ""); if (r !== t && REALTIME_VOICE_CLOSING_REMAINDER.test(r)) return "non-actionable-closing"; } //#endregion //#region src/talk/turn-context-tracker.ts const DEFAULT_REALTIME_VOICE_TURN_CONTEXT_LIMIT = 32; const DEFAULT_REALTIME_VOICE_IGNORED_CONTEXT_TTL_MS = 1e4; function createRealtimeVoiceTurnContextTracker(e = {}) { const t = []; let n; let r = 0; const i = Symbol("realtimeVoiceTurnContextTracker"); const a = e.now ?? Date.now; const o = resolveNonNegativeIntegerOption(e.limit, DEFAULT_REALTIME_VOICE_TURN_CONTEXT_LIMIT); const s = resolveNonNegativeIntegerOption(e.ignoredContextTtlMs, DEFAULT_REALTIME_VOICE_IGNORED_CONTEXT_TTL_MS); const c = e.deferUntilAudio === true; const prune = () => { for (let e = t.length - 1; e >= 0; e -= 1) { const n = t[e]; if (n?.closed && !n.hasAudio) t.splice(e, 1); } while (t.length > o) { const e = t.findIndex((e) => e.closed); t.splice(Math.max(e, 0), 1); } }; const expireClosedTurnsBeforeLaterAudio = () => { let e = false; for (let n = t.length - 1; n >= 0; n -= 1) { const r = t[n]; if (!r?.hasAudio) continue; if (r.closed && e) { t.splice(n, 1); continue; } e = true; } }; const prepareForAudioContextRead = () => { prune(); expireClosedTurnsBeforeLaterAudio(); }; const owns = (e) => e[i] === true; return { open(e, ...n) { const o = a(); const s = { ...n[0] ?? {}, [i]: true, id: `realtime-turn:${o}:${++r}`, context: e, hasAudio: false, closed: false, startedAt: o }; if (!c) { t.push(s); prune(); } return s; }, markAudio(e) { if (!owns(e)) return; e.hasAudio = true; e.lastAudioAt = a(); if (!t.includes(e)) { t.push(e); prune(); } }, close(e) { if (!owns(e)) return; e.closed = true; if (!t.includes(e)) return; prune(); }, consumeAudioContext() { prepareForAudioContextRead(); const e = t.findIndex((e) => e.hasAudio); if (e < 0) return; const [n] = t.splice(e, 1); prune(); return n?.context; }, peekAudioTurn() { prepareForAudioContextRead(); return t.find((e) => e.hasAudio); }, hasAudioContext() { prepareForAudioContextRead(); return t.some((e) => e.hasAudio); }, rememberIgnoredContext(e) { if (e === void 0) return; n = { context: e, createdAt: a() }; }, consumeIgnoredContext() { const e = n; n = void 0; if (!e || a() - e.createdAt > s) return; return e.context; }, size() { prune(); return t.length; }, clear() { t.length = 0; n = void 0; } }; } //#endregion //#region src/talk/fast-context-runtime.ts /** * When memory/session search can answer quickly, Talk can return concise * context without launching a full agent consult; otherwise callers may fall * back to the normal consult flow. */ const MAX_SNIPPET_CHARS = 700; function buildContextText(e) { const t = e.hits.map((e, t) => { const n = truncateWithMarker(e.snippet.replace(/\s+/g, " ").trim(), MAX_SNIPPET_CHARS, { marker: "...", reserve: 1, trimEnd: true }); return `${t + 1}. [${e.source}] ${e.location}\n${n}`; }).join("\n\n"); return [ `Fast ${e.labels.contextName} found for the live ${e.labels.audienceLabel}.`, `Use this context only if it answers the ${e.labels.audienceLabel}'s question. If it is not relevant, say briefly that you do not have that context handy.`, `Question:\n${e.query}`, `Context:\n${t}` ].join("\n\n"); } function buildMissText(e, t) { return [ `No relevant ${t.contextName} was found quickly for the live ${t.audienceLabel}.`, `Answer briefly that you do not have that context handy. Do not keep checking unless the ${t.audienceLabel} asks you to.`, `Question:\n${e}` ].join("\n\n"); } function toNativeFastContextHit(e) { return { source: e.source ?? e.reference.providerId, location: e.citations?.map((e) => e.label).join(", ") || `${e.reference.providerId}:${e.reference.id}`, snippet: e.excerpt }; } async function lookupFastContext(e) { const { authorizeActiveMemorySearchHits: t, getActiveMemoryProviderCore: n, getActiveMemorySearchManagerCore: r, isActiveMemoryProviderNative: i } = await import("../memory-runtime-ppPZJk8v.mjs"); if (i({ cfg: e.cfg, agentId: e.agentId })) { if (!e.callerSuppliedLiveness) return { status: "unavailable", error: "caller supplied no request liveness" }; const t = await n({ cfg: e.cfg, agentId: e.agentId, context: e.context }); if (!t.provider) return { status: "unavailable", error: t.error ?? "no active memory provider" }; try { const { hits: n } = await t.provider.search({ query: e.query, maxResults: e.config.maxResults, sources: e.config.sources }); e.context.assertCurrent(); return { status: "hits", hits: n.map(toNativeFastContextHit) }; } finally { await t.provider.close(); e.context.assertCurrent(); } } const a = await r({ cfg: e.cfg, agentId: e.agentId }); e.context.assertCurrent(); if (!a.manager) return { status: "unavailable", error: a.error ?? "no active memory manager" }; const o = await a.manager.search(e.query, { maxResults: e.config.maxResults, sessionKey: e.sessionKey, sources: e.config.sources }); e.context.assertCurrent(); const s = await t({ cfg: e.cfg, agentId: e.agentId, requesterSessionKey: e.sessionKey, sandboxed: false, hits: o }); e.context.assertCurrent(); return { status: "hits", hits: s.map((e) => ({ source: e.source, location: `${e.path}:${e.startLine}-${e.endLine}`, snippet: e.snippet })) }; } async function resolveRealtimeVoiceFastContextConsult(e) { if (!e.config.enabled) return { handled: false }; const t = { audienceLabel: e.labels?.audienceLabel?.trim() || "person", contextName: e.labels?.contextName?.trim() || "OpenClaw memory context" }; const n = parseRealtimeVoiceAgentConsultArgs(e.args); const r = [n.question, n.context].filter(Boolean).join("\n\n"); const i = new AbortController(); const a = e.liveness?.signal ? AbortSignal.any([e.liveness.signal, i.signal]) : i.signal; const o = { authority: { kind: "session", sessionKey: e.sessionKey, sandboxed: false }, signal: a, assertCurrent() { if (i.signal.aborted) throw new Error("voice context request has ended"); a.throwIfAborted(); e.liveness?.assertCurrent(); } }; try { const n = resolveTimerTimeoutMs(e.config.timeoutMs, 1); const i = await withTimeout(lookupFastContext({ cfg: e.cfg, agentId: e.agentId, sessionKey: e.sessionKey, config: e.config, query: r, context: o, callerSuppliedLiveness: e.liveness !== void 0 }), n, { createError: () => /* @__PURE__ */ new Error(`fast context lookup timed out after ${n}ms`) }); o.assertCurrent(); if (i.status === "unavailable") e.logger.debug?.(`[talk] fast context unavailable: ${i.error}`); else if (i.hits.length > 0) return { handled: true, result: { text: buildContextText({ query: r, hits: i.hits, labels: t }) } }; } catch (t) { const n = formatErrorMessage(t); e.logger.debug?.(`[talk] fast context lookup failed: ${n}`); } finally { i.abort(/* @__PURE__ */ new Error("voice context request has ended")); } return e.config.fallbackToConsult ? { handled: false } : { handled: true, result: { text: buildMissText(r, t) } }; } //#endregion export { REALTIME_VOICE_AGENT_CONSULT_SENDER_AUTH_VERSION, REALTIME_VOICE_AGENT_CONSULT_TOOL, REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME, REALTIME_VOICE_AGENT_CONSULT_TOOL_POLICIES, REALTIME_VOICE_AGENT_CONTROL_TOOL, REALTIME_VOICE_AGENT_CONTROL_TOOL_NAME, REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ, REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ, RealtimeVoiceSessionLifecycle, TALK_EVENT_TYPES, assertRealtimeVoiceAgentConsultModelSelectionUnlocked, assertRealtimeVoiceAgentConsultModelSelectionUnlockedAsync, buildRealtimeVoiceAgentCancelProviderResult, buildRealtimeVoiceAgentConsultChatMessage, buildRealtimeVoiceAgentConsultPolicyInstructions, buildRealtimeVoiceAgentConsultWorkingResponse, buildRealtimeVoiceAgentErrorProviderResult, buildRealtimeVoiceSessionInstructions, buildRealtimeVoiceSpeakExactMessage, calculateMulawRms, canonicalizeRealtimeVoiceProviderId, classifyRealtimeVoiceAgentControlText, classifyRealtimeVoiceConsultToolCall, classifySkippableRealtimeVoiceConsultTranscript, consultRealtimeVoiceAgent, controlRealtimeVoiceAgentRun, convertPcmToMulaw8k, createRealtimeVoiceAgentTalkbackQueue, createRealtimeVoiceAudioPortSender, createRealtimeVoiceAudioQueue, createRealtimeVoiceBridgeSession, createRealtimeVoiceForcedConsultCoordinator, createRealtimeVoiceOutputActivityTracker, createRealtimeVoiceSessionHarness, createRealtimeVoiceTurnContextTracker, createSpeechThresholdGate, createTalkSessionController, extendRealtimeVoiceOutputEchoSuppression, getRealtimeVoiceBridgeEventHealth, getRealtimeVoiceProvider, getRealtimeVoiceTranscriptHealth, isLikelyRealtimeVoiceAssistantEchoTranscript, isRealtimeVoiceAgentConsultToolPolicy, isRealtimeVoiceAudioAudible, isRealtimeVoiceWakeNameRequired, isSupportedRealtimeVoiceActivationName, listRealtimeVoiceProviders, matchRealtimeVoiceActivationName, matchRealtimeVoiceConsultQuestions, mulawToPcm, normalizeRealtimeVoiceActivationNamePrefix, normalizeRealtimeVoiceResponseOutcome, normalizeSupportedRealtimeVoiceActivationName, parseRealtimeVoiceAgentControlToolArgs, projectInternalRealtimeVoicePublicConfig, readPcm16AudioStats, readRealtimeVoiceConsultQuestion, readSpeakableRealtimeVoiceToolResult, realtimeVoiceAudioDurationMs, recordRealtimeVoiceBridgeEvent, recordRealtimeVoiceTranscript, recordTalkObservabilityEvent, registerRealtimeVoiceSelection, resamplePcm, resamplePcmTo8k, resolveConfiguredRealtimeVoiceProvider, resolveConfiguredRealtimeVoiceProviderAsync, resolveRealtimeVoiceAgentConsultToolPolicy, resolveRealtimeVoiceAgentConsultTools, resolveRealtimeVoiceAgentConsultToolsAllow, resolveRealtimeVoiceBargeIn, resolveRealtimeVoiceFastContextConsult, resolveRealtimeVoiceInterruptResponseOnInputAudio, resolveRealtimeVoiceMinBargeInAudioEndMs, resolveRealtimeVoiceSessionPolicy, shouldAutoControlRealtimeVoiceAgentText, sortRealtimeVoiceActivationNames, toOpenAICompatibleRealtimeAudioFormat };