Skip to content

Commit 131b9e3

Browse files
authored
refactor(voice): share realtime session lifecycle (#117865)
* refactor(voice): share realtime session lifecycle * test(voice): normalize abort rejection
1 parent f7ddcdb commit 131b9e3

16 files changed

Lines changed: 999 additions & 1197 deletions

‎extensions/google/index.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type {
99
RealtimeVoiceProviderConfig,
1010
RealtimeVoiceProviderPlugin,
1111
} from "openclaw/plugin-sdk/realtime-voice";
12+
import { createRealtimeVoiceAudioQueue } from "openclaw/plugin-sdk/realtime-voice";
1213
import { normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input";
1314
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
1415
import type { VideoGenerationProvider } from "openclaw/plugin-sdk/video-generation";
@@ -20,7 +21,6 @@ import {
2021
} from "./generation-provider-metadata.js";
2122
import { geminiMemoryEmbeddingProviderAdapter } from "./memory-embedding-adapter.js";
2223
import { registerGoogleProvider } from "./provider-registration.js";
23-
import { createGoogleRealtimeAudioQueue } from "./realtime-audio-queue.js";
2424
import { buildGoogleSpeechProvider } from "./speech-provider.js";
2525
import { createGeminiWebSearchProvider } from "./src/gemini-web-search-provider.js";
2626

@@ -219,7 +219,7 @@ function createLazyGoogleRealtimeVoiceBridge(
219219
let latestMediaTimestamp: number | undefined;
220220
let pendingGreeting: string | undefined;
221221
// Lazy startup keeps the newest microphone tail when loading stalls.
222-
const pendingAudio = createGoogleRealtimeAudioQueue("drop-oldest");
222+
const pendingAudio = createRealtimeVoiceAudioQueue("drop-oldest");
223223
const pendingUserMessages: string[] = [];
224224
let pendingUserMessageBytes = 0;
225225
// Loading and connecting finish on separate async boundaries. Keep close ownership

‎extensions/google/realtime-audio-queue.test.ts‎

Lines changed: 0 additions & 34 deletions
This file was deleted.

‎extensions/google/realtime-audio-queue.ts‎

Lines changed: 0 additions & 49 deletions
This file was deleted.

‎extensions/google/realtime-voice-provider.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import type {
3838
} from "openclaw/plugin-sdk/realtime-voice";
3939
import {
4040
convertPcmToMulaw8k,
41+
createRealtimeVoiceAudioQueue,
4142
mulawToPcm,
4243
REALTIME_VOICE_AUDIO_FORMAT_G711_ULAW_8KHZ,
4344
REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
@@ -52,7 +53,6 @@ import {
5253
normalizeOptionalString,
5354
} from "openclaw/plugin-sdk/string-coerce-runtime";
5455
import { createGoogleGenAI } from "./google-genai-runtime.js";
55-
import { createGoogleRealtimeAudioQueue } from "./realtime-audio-queue.js";
5656
import { resolveGoogleGemini3ThinkingLevel } from "./thinking.js";
5757

5858
const GOOGLE_REALTIME_DEFAULT_MODEL = "gemini-3.1-flash-live-preview";
@@ -472,7 +472,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
472472
private sessionConfigured = false;
473473
private intentionallyClosed = false;
474474
// Native reconnect keeps the already accepted FIFO prefix stable.
475-
private readonly pendingAudio = createGoogleRealtimeAudioQueue("reject-newest");
475+
private readonly pendingAudio = createRealtimeVoiceAudioQueue("reject-newest");
476476
private sessionReadyFired = false;
477477
private consecutiveSilenceMs = 0;
478478
private audioStreamEnded = false;

‎extensions/openai/realtime-quicksilver-bridge.ts‎

Lines changed: 13 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ import {
1010
convertPcmToMulaw8k,
1111
mulawToPcm,
1212
REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME,
13+
RealtimeVoiceSessionLifecycle,
1314
resamplePcm,
1415
type RealtimeVoiceBridge,
1516
type RealtimeVoiceBridgeCreateRequest,
17+
type RealtimeVoiceSessionConnection,
1618
type RealtimeVoiceToolResultOptions,
1719
} from "openclaw/plugin-sdk/realtime-voice";
1820
import WebSocket, { type RawData } from "ws";
@@ -31,15 +33,9 @@ import {
3133
type OpenAIQuicksilverInboundEvent,
3234
type OpenAIQuicksilverRequestIds,
3335
} from "./realtime-quicksilver-wire.js";
34-
import {
35-
OpenAIRealtimeVoiceLifecycle,
36-
type OpenAIRealtimeVoiceConnection,
37-
} from "./realtime-voice-lifecycle.js";
3836

3937
const OPENAI_QUICKSILVER_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
4038
const OPENAI_QUICKSILVER_READY_TIMEOUT_MS = 15_000;
41-
const OPENAI_QUICKSILVER_PENDING_AUDIO_CHUNKS = 320;
42-
const OPENAI_QUICKSILVER_PENDING_AUDIO_BYTES = 1024 * 1024;
4339
const OPENAI_QUICKSILVER_SAMPLE_RATE = 24_000;
4440
const WEBSOCKET_OPEN = 1;
4541

@@ -86,11 +82,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
8682
readonly handlesInputAudioBargeIn = false;
8783

8884
private socket: OpenAIQuicksilverSocket | undefined;
89-
private connection: OpenAIRealtimeVoiceConnection | undefined;
90-
private connectPromise: Promise<void> | undefined;
91-
private readonly lifecycle = new OpenAIRealtimeVoiceLifecycle();
92-
private pendingAudio: Buffer[] = [];
93-
private pendingAudioBytes = 0;
85+
private readonly lifecycle = new RealtimeVoiceSessionLifecycle("OpenAI");
9486
private activeDelegations = new Set<string>();
9587
private readonly flowId = randomUUID();
9688
private readonly requestIds: OpenAIQuicksilverRequestIds = {
@@ -102,26 +94,10 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
10294
constructor(private readonly config: OpenAIQuicksilverVoiceBridgeConfig) {}
10395

10496
async connect(): Promise<void> {
105-
if (this.lifecycle.isReady()) {
106-
return;
107-
}
108-
if (this.connectPromise) {
109-
return this.connectPromise;
110-
}
111-
const connection = this.lifecycle.connect();
112-
this.connection = connection;
113-
const connectPromise = this.connectConnection(connection);
114-
this.connectPromise = connectPromise;
115-
try {
116-
await connectPromise;
117-
} finally {
118-
if (this.connectPromise === connectPromise) {
119-
this.connectPromise = undefined;
120-
}
121-
}
97+
await this.lifecycle.connect((connection) => this.connectConnection(connection));
12298
}
12399

124-
private async connectConnection(connection: OpenAIRealtimeVoiceConnection): Promise<void> {
100+
private async connectConnection(connection: RealtimeVoiceSessionConnection): Promise<void> {
125101
let connected: Awaited<ReturnType<typeof connectOpenAIQuicksilverSideband>>;
126102
try {
127103
const auth = await this.waitForConnection(this.config.resolveAuth(), connection);
@@ -316,7 +292,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
316292
return;
317293
}
318294
if (!this.lifecycle.isReady() || this.socket?.readyState !== WEBSOCKET_OPEN) {
319-
this.enqueuePendingAudio(audio);
295+
this.lifecycle.enqueuePendingAudio(audio);
320296
return;
321297
}
322298
this.sendAudioNow(audio);
@@ -360,7 +336,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
360336
acknowledgeMark(_markName?: string): void {}
361337

362338
close(): void {
363-
const connection = this.connection;
339+
const connection = this.lifecycle.currentConnection();
364340
if (!this.lifecycle.cancel()) {
365341
return;
366342
}
@@ -397,7 +373,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
397373

398374
private async waitForConnection<T>(
399375
promise: Promise<T>,
400-
connection: OpenAIRealtimeVoiceConnection,
376+
connection: RealtimeVoiceSessionConnection,
401377
): Promise<T | undefined> {
402378
if (connection.signal.aborted) {
403379
return undefined;
@@ -424,7 +400,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
424400

425401
private handleEvent(
426402
event: OpenAIQuicksilverInboundEvent,
427-
connection: OpenAIRealtimeVoiceConnection,
403+
connection: RealtimeVoiceSessionConnection,
428404
settleReady: () => void,
429405
failStartup: (error: Error, reason: string) => void,
430406
): void {
@@ -433,9 +409,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
433409
}
434410
if (event.kind === "session-started") {
435411
if (this.lifecycle.ready(connection)) {
436-
const pendingAudio = this.pendingAudio.splice(0);
437-
this.pendingAudioBytes = 0;
438-
for (const audio of pendingAudio) {
412+
for (const audio of this.lifecycle.drainPendingAudio()) {
439413
this.sendAudioNow(audio);
440414
}
441415
this.config.onReady?.();
@@ -541,7 +515,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
541515
}
542516

543517
private fail(
544-
connection: OpenAIRealtimeVoiceConnection,
518+
connection: RealtimeVoiceSessionConnection,
545519
error: Error,
546520
reason = "bridge error",
547521
): boolean {
@@ -553,30 +527,15 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
553527
return true;
554528
}
555529

556-
private failLifecycle(connection: OpenAIRealtimeVoiceConnection): boolean {
530+
private failLifecycle(connection: RealtimeVoiceSessionConnection): boolean {
557531
if (!this.lifecycle.failure(connection)) {
558532
return false;
559533
}
560534
this.resetTerminalState();
561535
return true;
562536
}
563537

564-
private enqueuePendingAudio(audio: Buffer): void {
565-
if (
566-
this.pendingAudio.length >= OPENAI_QUICKSILVER_PENDING_AUDIO_CHUNKS ||
567-
this.pendingAudioBytes + audio.byteLength > OPENAI_QUICKSILVER_PENDING_AUDIO_BYTES
568-
) {
569-
return;
570-
}
571-
// Capture transports can recycle caller-owned views before the provider becomes ready.
572-
const queuedAudio = Buffer.from(audio);
573-
this.pendingAudio.push(queuedAudio);
574-
this.pendingAudioBytes += queuedAudio.byteLength;
575-
}
576-
577538
private resetTerminalState(): void {
578-
this.pendingAudio = [];
579-
this.pendingAudioBytes = 0;
580539
this.activeDelegations.clear();
581540
}
582541

@@ -589,7 +548,7 @@ export class OpenAIQuicksilverVoiceBridge implements RealtimeVoiceBridge {
589548
}
590549

591550
private notifyClose(
592-
connection: OpenAIRealtimeVoiceConnection,
551+
connection: RealtimeVoiceSessionConnection,
593552
reason: "completed" | "error",
594553
): void {
595554
const outcome = this.lifecycle.close(connection, reason);

0 commit comments

Comments
 (0)