UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

13 lines (12 loc) • 13.3 kB
import{i as resolveGlobalMap}from"./global-singleton-DolL9xGt.mjs";import{n as materializeErrorStack}from"./error-graph-internal-Bt2pFJBM.mjs";import{t as isAbortError}from"./abort-signal-BKkRe6pu.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{y as wrapCurrentPluginInstance}from"./plugin-instance-scope-Bx-frH07.mjs";import{x as runOutsideGatewayRootWorkAdmission}from"./gateway-work-admission-CnMW3_qr.mjs";import{St as resolveReplyRunForCurrentSessionId,l as getAttachedBackend}from"./session-controller.state-BIDbpLPn.mjs";import{p as getEmbeddedRunAttachment,u as getActiveNativeAttempt}from"./run-state-Bd0P0LYH.mjs";import{t as TALK_VOICE_CHANGE_TIMEOUT_MS}from"./talk-voice-limits-AKbItBcj.mjs";import{o as bindWorkerToolPreparation}from"./host-private-capabilities-B_SEzbNU.mjs";import{i as getDiagnosticSessionActivitySnapshot}from"./diagnostic-run-activity-D_NQZV7c.mjs";import{d as parseRealtimeVoiceAgentConsultArgs,i as buildRealtimeVoiceAgentConsultChatMessage}from"./agent-consult-tool-CCU5qa7O.mjs";import{a as buildRealtimeVoiceAgentCancelProviderResult,f as resolveRealtimeVoiceAgentControlIntent,l as formatRealtimeVoiceAgentQueueRejection,s as buildRealtimeVoiceAgentFollowupSteeringText,t as AGENT_INPUT_UNCONFIRMED_MESSAGE,u as formatRealtimeVoiceAgentStatus}from"./agent-run-control-shared-N-ErZ7z4.mjs";import{r as bindPreparedToolAuthority}from"./tool-authority-preparation-Dgurlhwb.mjs"; //!src/talk/voice-selection-control.ts const runs=resolveGlobalMap(Symbol.for(`openclaw.realtimeVoiceSelectionRuns`),`close-and-restart`);function registerRealtimeVoiceSelection(e){const t=wrapCurrentPluginInstance(e);let n=true;let r=false;const i=new AbortController;const a=/* @__PURE__ */ new Set;const assertCurrent=()=>{if(!n)throw new Error(`Voice call is no longer active`);t.assertCurrent()};const o={...t,assertCurrent,read:()=>{const e=t.read();return{...e,voices:[...e.voices]}},changeVoice:async(e,n)=>{const a=AbortSignal.any([i.signal,AbortSignal.timeout(TALK_VOICE_CHANGE_TIMEOUT_MS),...n.signal?[n.signal]:[]]);const assertRequestCurrent=()=>{a.throwIfAborted();n.assertCurrent()};assertRequestCurrent();if(r)throw new Error(`A voice change is already in progress for this call`);const o=t.read();if(!o.canChange)throw new Error(`This call cannot change voices`);const s=o.voices.find(t=>t.toLowerCase()===e.trim().toLowerCase());if(!s)throw new Error(`Voice is not in this call's catalog; list the available voices first`);if(s===o.voice)return;r=true;try{await runOutsideGatewayRootWorkAdmission(()=>t.changeVoice(s,{assertCurrent:assertRequestCurrent,signal:a}));assertRequestCurrent();if(t.read().voice!==s)throw new Error(`The replacement call did not apply the requested voice`)}finally{r=false}}};return{bindRun:({runId:e,assertCurrent:t})=>{assertCurrent();t();if(runs.has(e))throw new Error(`The agent run already belongs to a voice call`);const n={owner:o,assertCurrent:()=>{assertCurrent();t();if(runs.get(e)!==n)throw new Error(`The agent no longer owns this voice call`)}};runs.set(e,n);a.add(e);return()=>{if(runs.get(e)===n)runs.delete(e);a.delete(e)}},unregister:()=>{n=false;i.abort(/* @__PURE__ */ new Error(`Voice call closed`));materializeErrorStack(i.signal.reason);for(const e of a)if(runs.get(e)?.owner===o)runs.delete(e);a.clear()}}}function resolveRealtimeVoiceSelectionRun(e){const t=runs.get(e);if(!t)return;const{owner:n}=t;const read=()=>{t.assertCurrent();return{...n.read(),voiceSessionId:n.voiceSessionId,sessionKey:n.sessionKey}};return{agentId:n.agentId,sessionKey:n.sessionKey,voiceSessionId:n.voiceSessionId,assertCurrent:t.assertCurrent,read,changeVoice:async(e,r)=>{const assertCurrent=()=>{t.assertCurrent();r.assertCurrent()};await n.changeVoice(e,{assertCurrent,signal:r.signal});assertCurrent();return{...read(),status:`applied`}}}} //!src/talk/exact-speech-protocol.ts function buildRealtimeVoiceSpeakExactMessage(e){return[`Internal OpenClaw voice playback result.`,`Do not call openclaw_agent_consult or any other tool for this message.`,`Speak this exact OpenClaw answer to ${e.surfaceLabel}, without adding, removing, or rephrasing words.`,`Answer: ${JSON.stringify(e.text)}`].join(` `)}function readRealtimeVoicePlaybackEcho(e,t){let n;try{n=typeof e===`string`?e:parseRealtimeVoiceAgentConsultArgs(e).question}catch{return}return t.retainedExactSpeechTexts.find(e=>n===buildRealtimeVoiceSpeakExactMessage({text:e,surfaceLabel:t.surfaceLabel}))}function classifyRealtimeVoiceConsultToolCall(e,t){const n=collectRealtimeConsultArgStrings(e).join(` `);if(n.includes(`Speak this exact OpenClaw answer`)){const e=readJsonStringAfterLabel(n,`Answer:`);if(e!==void 0&&t.retainedExactSpeechTexts.includes(e))return{kind:`exact-speech-echo`,text:e}}for(const e of t.retainedExactSpeechTexts)if(e&&n.includes(JSON.stringify(e)))return{kind:`exact-speech-echo`,text:e};try{return{kind:`consult`,message:buildRealtimeVoiceAgentConsultChatMessage(e)}}catch(e){return{kind:`malformed`,error:formatErrorMessage(e)}}}function collectRealtimeConsultArgStrings(e){if(!e||typeof e!==`object`)return typeof e===`string`?[e]:[];const t=[];for(const n of[`question`,`prompt`,`query`,`task`,`context`,`responseStyle`]){const r=e[n];if(typeof r===`string`)t.push(r)}return t}function readJsonStringAfterLabel(e,t){const n=e.indexOf(t);if(n<0)return;const r=e.indexOf(`"`,n+t.length);if(r<0)return;for(let t=r+1;t<e.length;t+=1){if(e[t]!==`"`||isEscapedQuote(e,t))continue;try{const n=JSON.parse(e.slice(r,t+1));return typeof n===`string`?n:void 0}catch{return}}}function isEscapedQuote(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;r-=1)n+=1;return n%2===1} //!src/talk/agent-run-control-owner.ts function captureRealtimeVoiceRunOwner(e,t){const n=getActiveNativeAttempt(e);const r=n?getEmbeddedRunAttachment(n):void 0;const i=resolveReplyRunForCurrentSessionId(e);const a=i.kind===`one`?i.operation:void 0;if(!n&&i.kind!==`one`)return;const o=n?.runId;const s=n?.toolAuthorityFingerprint;const c=s??a?.toolAuthorityFingerprint;const isCurrent=()=>{const i=resolveReplyRunForCurrentSessionId(e);if(a&&(a.result||a.key!==t||a.sessionId!==e||i.kind!==`one`||i.operation!==a||n&&getAttachedBackend(a)!==n))return false;if(n&&(getActiveNativeAttempt(e)!==n||getEmbeddedRunAttachment(n)!==r||r?.sessionKey!==void 0&&r.sessionKey!==t||n.runId!==o||n.toolAuthorityFingerprint!==s||n.isStopped?.()||n.isAborted?.()))return false;try{r?.toolAuthority?.assertActive();return true}catch{return false}};return{operation:a,isCurrent,matchesCaller:e=>{if(!isCurrent())return false;const t=r?.toolAuthority?r.toolAuthority.project(e):a?.projectToolAuthorityFingerprint(e);return Boolean(c&&t===c&&isCurrent())}}} //!src/talk/agent-run-control.ts const controlResultPresentation={speak:true,show:true,suppress:false};function buildRealtimeVoiceAgentErrorProviderResult(e){return isAbortError(e)?buildRealtimeVoiceAgentCancelProviderResult():{error:formatErrorMessage(e)}}async function controlRealtimeVoiceAgentRun(e,t){return await controlTalkAgentRun(e,t)}async function controlTalkAgentRun(e,t){const n=e.sessionKey.trim();const r=e.text.trim();const i=resolveRealtimeVoiceAgentControlIntent({text:r,mode:e.mode}).mode;const a={mode:i,sessionKey:n};const o=e.runTarget;let s;if(!t&&o&&!o.signal.aborted&&o.isCurrent())s=(await import(`./agent-run-control.runtime-U7uiscyc.mjs`)).realtimeVoiceControlRuntime;const c=s??(!t&&o===void 0?await import(`./session-controller.queries-Buk5t0AN.mjs`):void 0);const resolveCurrentRun=()=>{const e=o&&!o.signal.aborted&&o.isCurrent()?o:void 0;const r=!t&&e?s?.resolveSourceRunOwner(e.runId,e.signal):void 0;const i=e?t?t.resolveActiveEmbeddedRunOwnerByRunId?.(e.runId)??t.resolveActiveReplyRunOwnerForSignal?.(e.signal):r:void 0;const a=i?.sessionKey===n&&o?.isCurrent(i.sessionId)?i:void 0;return{sessionId:o===void 0?t?t.resolveActiveEmbeddedRunSessionId(n):c?.resolveActiveSessionRunId(n):a?.sessionId,exactOwner:a,operation:a?r?.operation:void 0}};let l=resolveCurrentRun();const u=o===void 0&&!t&&l.sessionId?captureRealtimeVoiceRunOwner(l.sessionId,n):void 0;const d=l.sessionId;const isLegacyCurrent=()=>t!==void 0||l.sessionId===d&&u?.isCurrent()===true;const f=t?.getDiagnosticSessionActivitySnapshot??getDiagnosticSessionActivitySnapshot;const p=o===void 0?f({sessionId:l.sessionId,sessionKey:n}):l.sessionId?f({sessionId:l.sessionId}):void 0;const m=Boolean(l.sessionId||p?.activeWorkKind||p?.hasActiveEmbeddedRun);if(i===`status`)return{ok:true,...a,...l.sessionId?{sessionId:l.sessionId}:{},active:m,message:formatRealtimeVoiceAgentStatus({active:m,recentEvents:e.recentEvents,activity:p}),...controlResultPresentation};const noActiveRun=()=>({ok:false,...a,active:false,...i===`cancel`?{aborted:false}:{queued:false},reason:`no_active_run`,message:`There is no active OpenClaw run to ${i===`cancel`?`cancel`:`steer`}.`,...controlResultPresentation});if(!l.sessionId||o===void 0&&!isLegacyCurrent())return noActiveRun();if(!t&&!s){s=(await import(`./agent-run-control.runtime-U7uiscyc.mjs`)).realtimeVoiceControlRuntime;l=resolveCurrentRun()}const{sessionId:h}=l;if(!h||o===void 0&&!isLegacyCurrent())return noActiveRun();const g=!t&&Boolean(o||u);const _=e.getToolAuthorityOverlayAsync?await e.getToolAuthorityOverlayAsync():e.getToolAuthorityOverlay?.();e.assertCurrent?.();if(_&&(i===`cancel`||!g))await e.prepareToolAuthorityOverlay?.(_);const v=resolveCurrentRun();e.assertCurrent?.();if(v.sessionId!==h||(o?!o.isCurrent(h):!isLegacyCurrent()))return noActiveRun();if(i===`cancel`){const r=o===void 0?t?t.abortEmbeddedAgentRun(h):await s.stopRealtimeVoiceSessionRun({sessionKey:n,sessionId:h,assertCurrent:()=>{e.assertCurrent?.();_?.operatorAuthority?.assertCurrent()}}):o!==null&&(e.cancelRun?await e.cancelRun(o.runId):v.exactOwner?.abort()===true);const i=r?`Cancelled the active OpenClaw run.`:`OpenClaw could not cancel the active run.`;return{ok:r,...a,sessionId:h,active:true,aborted:r,...r?{}:{reason:`abort_rejected`},message:i,...controlResultPresentation,...r?{providerResult:buildRealtimeVoiceAgentCancelProviderResult(i)}:{}}}const prepareMessage=()=>{const t=[e.getSteeringContext?.(),r].filter(Boolean).join(` `);const n=i===`followup`?buildRealtimeVoiceAgentFollowupSteeringText(t):t;y.userTurnTranscriptRecorder=e.createUserTurnTranscriptRecorder?.(n);return n};const y={steeringMode:`all`,debounceMs:0,isInboundUserMessage:true,toolAuthorityOverlay:_,taskSuggestionDeliveryMode:void 0};const b=g?r:prepareMessage();const prepareCurrent=async()=>{const t=e.getToolAuthorityOverlayAsync?await e.getToolAuthorityOverlayAsync():e.getToolAuthorityOverlay?.();if(t)await e.prepareToolAuthorityOverlay?.(t);e.assertCurrent?.();y.toolAuthorityOverlay=t};const canInject=()=>{e.assertCurrent?.();y.toolAuthorityOverlay?.operatorAuthority?.assertCurrent();return o?!o.signal.aborted&&o.isCurrent(h):u?.isCurrent()===true};const x=bindPreparedToolAuthority(bindWorkerToolPreparation({assertCurrent:()=>{if(!canInject())throw new Error(`The original Talk run is no longer current`)},compatAssertCurrent:()=>{e.assertCurrent?.();const t=e.getToolAuthorityOverlayAsync?y.toolAuthorityOverlay:e.getToolAuthorityOverlay?.();y.toolAuthorityOverlay=t;if(t&&u&&!u.matchesCaller(t))throw new Error(`The original Talk caller authority no longer matches`)},prepareCurrent,prepareMessage:g?async()=>{await prepareCurrent();return prepareMessage()}:void 0}));let S;if(t)S=o?t.queueGuardedEmbeddedAgentMessageWithOutcomeAsync?await t.queueGuardedEmbeddedAgentMessageWithOutcomeAsync(h,b,y,canInject,x):{queued:false,sessionId:h,gatewayHealth:`live`,reason:`guarded_injection_unsupported`}:await t.queueEmbeddedAgentMessageWithOutcomeAsync(h,b,y);else{const e=y;e.assertCurrent=x.assertCurrent;e.toolAuthorityPreparation=x;let t;e.onQueueAccepted=e=>{t=t===true||e};let n;try{n=await s.steerActiveRun(v.operation??u?.operation,b,e)}catch(e){const r=formatErrorMessage(e);n=t===false?{status:`rejected`,reason:`runtime_rejected`,errorMessage:r}:{status:`indeterminate`,errorMessage:r}}if(n.status===`rejected`)return{ok:false,...a,sessionId:h,active:true,queued:false,reason:n.reason,message:formatRealtimeVoiceAgentQueueRejection(i,n.reason),...controlResultPresentation};S={queued:true,sessionId:h,gatewayHealth:`live`,...n.status===`indeterminate`||n.result?.transcriptCommit===`unconfirmed`?{transcriptCommit:`unconfirmed`}:{}}}if(!S.queued)return{ok:false,...a,sessionId:S.sessionId,active:true,queued:false,reason:S.reason,message:formatRealtimeVoiceAgentQueueRejection(i,S.reason),...controlResultPresentation};const C=S.transcriptCommit===`unconfirmed`;const w=C?AGENT_INPUT_UNCONFIRMED_MESSAGE:i===`followup`?`Queued that follow-up for the active OpenClaw run.`:`Got it. I steered the active run.`;return{ok:!C,...a,sessionId:S.sessionId,active:true,queued:true,...S.target?{target:S.target}:{},...C?{reason:`delivery_unconfirmed`}:{},message:w,...controlResultPresentation,...S.enqueuedAtMs!==void 0?{enqueuedAtMs:S.enqueuedAtMs}:{},...S.deliveredAtMs!==void 0?{deliveredAtMs:S.deliveredAtMs}:{}}}export{classifyRealtimeVoiceConsultToolCall as a,resolveRealtimeVoiceSelectionRun as c,buildRealtimeVoiceSpeakExactMessage as i,controlRealtimeVoiceAgentRun as n,readRealtimeVoicePlaybackEcho as o,controlTalkAgentRun as r,registerRealtimeVoiceSelection as s,buildRealtimeVoiceAgentErrorProviderResult as t};