Skip to content

Commit 73ab74e

Browse files
authored
fix(discord): preserve routed agent for realtime voice (#125111)
1 parent 6b86199 commit 73ab74e

26 files changed

Lines changed: 312 additions & 16 deletions

‎extensions/discord/src/voice/realtime-session.runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
227227
providerConfigs: buildProviderConfigs(this.realtimeConfig),
228228
providerConfigOverrides: buildProviderConfigOverrides(this.realtimeConfig),
229229
cfg: this.params.cfg,
230+
agentId: this.params.entry.route.agentId,
230231
defaultModel: this.realtimeConfig?.model,
231232
noRegisteredProviderMessage: "No configured realtime voice provider registered",
232233
});
@@ -284,6 +285,7 @@ export class DiscordRealtimeVoiceSession implements VoiceRealtimeSession {
284285
this.bridge = this.harness.createBridge({
285286
provider: resolved.provider,
286287
cfg: this.params.cfg,
288+
agentId: this.params.entry.route.agentId,
287289
providerConfig: resolved.providerConfig,
288290
audioFormat: REALTIME_VOICE_AUDIO_FORMAT_PCM16_24KHZ,
289291
instructions,

‎extensions/discord/src/voice/voice-session.lifecycle.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ defineDiscordVoiceTests(
1515
joinVoiceChannelMock,
1616
entersStateMock,
1717
createAudioPlayerMock,
18+
resolveAgentRouteMock,
1819
resolveRealtimeBootstrapContextInstructionsMock,
20+
resolveConfiguredRealtimeVoiceProviderMock,
1921
createRealtimeVoiceBridgeSessionMock,
2022
realtimeSessionMock,
2123
managerModule,
@@ -420,6 +422,44 @@ defineDiscordVoiceTests(
420422
expectConnectedStatus(manager, "1002");
421423
});
422424

425+
it("preserves the routed agent through realtime autoJoin startup", async () => {
426+
resolveAgentRouteMock.mockReturnValue({
427+
agentId: "molty",
428+
sessionKey: "agent:molty:discord:channel:g1:1001",
429+
});
430+
resolveConfiguredRealtimeVoiceProviderMock.mockImplementation((params?: unknown) => {
431+
if (requireRecord(params, "provider resolution params").agentId !== "molty") {
432+
throw new Error("AGENT_SELECTION_REQUIRED: expected routed agent molty");
433+
}
434+
return {
435+
provider: { id: "openai", capabilities: { supportsActivationNameGating: true } },
436+
providerConfig: { model: "gpt-realtime-2", voice: "cedar" },
437+
};
438+
});
439+
createRealtimeVoiceBridgeSessionMock.mockImplementation((params?: unknown) => {
440+
if (requireRecord(params, "bridge session params").agentId !== "molty") {
441+
throw new Error("AGENT_SELECTION_REQUIRED: expected routed agent molty");
442+
}
443+
return realtimeSessionMock;
444+
});
445+
const manager = createManager(
446+
makeVoiceConfig({
447+
mode: "agent-proxy",
448+
autoJoin: [{ guildId: "g1", channelId: "1001" }],
449+
realtime: { provider: "openai" },
450+
}),
451+
undefined,
452+
{ agents: { list: [{ id: "helper" }, { id: "molty" }] } },
453+
);
454+
455+
await manager.autoJoin();
456+
457+
expect(resolveConfiguredRealtimeVoiceProviderMock).toHaveBeenCalledTimes(1);
458+
expect(createRealtimeVoiceBridgeSessionMock).toHaveBeenCalledTimes(1);
459+
expect(realtimeSessionMock.connect).toHaveBeenCalledTimes(1);
460+
expectConnectedStatus(manager, "1001");
461+
});
462+
423463
it("suppresses repeated autoJoin attempts after fatal realtime startup failures", async () => {
424464
realtimeSessionMock.connect.mockRejectedValueOnce(new Error("Incorrect API key provided"));
425465
const manager = createManager(

‎extensions/google-meet/src/realtime.process.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,60 @@ describe("local Meet realtime transport process stream errors", () => {
446446
});
447447

448448
describe("Google Meet bidi realtime engine cleanup", () => {
449+
it("preserves the configured realtime agent through provider startup", async () => {
450+
let bridgeRequest: Parameters<RealtimeVoiceProviderPlugin["createBridge"]>[0] | undefined;
451+
const isConfigured = vi.fn(({ agentId }) => agentId === "molty");
452+
const bridge = {
453+
connect: vi.fn(async () => {}),
454+
sendAudio: vi.fn(),
455+
sendUserMessage: vi.fn(),
456+
setMediaTimestamp: vi.fn(),
457+
submitToolResult: vi.fn(),
458+
acknowledgeMark: vi.fn(),
459+
close: vi.fn(),
460+
triggerGreeting: vi.fn(),
461+
isConnected: vi.fn(() => true),
462+
};
463+
const provider: RealtimeVoiceProviderPlugin = {
464+
id: "openai",
465+
label: "OpenAI",
466+
isConfigured,
467+
createBridge: (request) => {
468+
bridgeRequest = request;
469+
return bridge;
470+
},
471+
};
472+
const transport: MeetingRealtimeAudioTransport = {
473+
onFatal: vi.fn(),
474+
startInput: vi.fn(),
475+
stop: vi.fn(async () => {}),
476+
writeOutput: vi.fn(async () => {}),
477+
clearOutput: vi.fn(async () => {}),
478+
dispose: vi.fn(async () => {}),
479+
};
480+
const config = resolveGoogleMeetConfig({
481+
realtime: { strategy: "bidi", provider: "openai", agentId: "molty" },
482+
});
483+
const fullConfig = {
484+
agents: { list: [{ id: "helper" }, { id: "molty" }] },
485+
} as never;
486+
487+
const handle = await startMeetingRealtimeEngine({
488+
config,
489+
fullConfig,
490+
runtime: {} as never,
491+
...GOOGLE_MEET_ENGINE_BINDINGS,
492+
meetingSessionId: "meet-routed-agent",
493+
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
494+
providers: [provider],
495+
transport,
496+
});
497+
498+
expect(isConfigured).toHaveBeenCalledWith(expect.objectContaining({ agentId: "molty" }));
499+
expect(bridgeRequest?.agentId).toBe("molty");
500+
await handle.stop();
501+
});
502+
449503
it("disposes the audio transport when provider connection fails", async () => {
450504
const connectError = new Error("voice bridge connect failed");
451505
const stopError = new Error("transport stop failed");

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,7 @@ export class OpenAIRealtimeBridge extends OpenAIRealtimeEvents implements Realti
462462
const auth = await requireOpenAIRealtimePlatformAuth({
463463
configuredApiKey: this.config.apiKey,
464464
cfg: this.config.cfg,
465+
agentId: this.config.agentId,
465466
});
466467
return this.resolveApiKeyConnectionParams(auth.value, model);
467468
}

‎extensions/openai/realtime-voice-browser-auth.test.ts‎

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -448,15 +448,60 @@ describe("OpenAI realtime voice browser authentication", () => {
448448
).rejects.toThrow("OpenAI Realtime voice requires an OpenAI Platform API key");
449449
});
450450

451-
it("treats OpenAI API-key auth profiles as configured for browser realtime sessions", () => {
452-
isProviderAuthProfileConfiguredMock.mockReturnValue(true);
451+
it("checks bridge readiness in the selected agent directory", () => {
452+
isProviderAuthProfileConfiguredMock.mockImplementation(
453+
({ agentDir }: { agentDir?: string }) => agentDir === "/tmp/openclaw-molty-agent",
454+
);
453455
const provider = buildOpenAIRealtimeVoiceProvider();
454-
const cfg = { agents: { defaults: {} } } as never;
456+
const cfg = {
457+
agents: {
458+
list: [
459+
{ id: "helper", agentDir: "/tmp/openclaw-helper-agent" },
460+
{ id: "molty", agentDir: "/tmp/openclaw-molty-agent" },
461+
],
462+
},
463+
} as never;
455464

456-
expect(provider.isConfigured({ cfg, providerConfig: {} })).toBe(true);
465+
expect(provider.isConfigured({ cfg, providerConfig: {}, agentId: "molty" })).toBe(true);
457466
expect(isProviderAuthProfileConfiguredMock).toHaveBeenCalledWith({
458467
provider: "openai",
459468
cfg,
469+
agentDir: "/tmp/openclaw-molty-agent",
470+
profileTypes: ["api_key"],
471+
includeExternalCliAuth: false,
472+
});
473+
});
474+
475+
it("resolves bridge Platform auth from the selected agent directory", async () => {
476+
resolveProviderAuthProfileApiKeyMock.mockImplementation(
477+
async ({ agentDir }: { agentDir?: string }) =>
478+
agentDir === "/tmp/openclaw-molty-agent" ? "test-api-key-molty" : undefined,
479+
);
480+
const provider = buildOpenAIRealtimeVoiceProvider();
481+
const cfg = {
482+
agents: {
483+
list: [
484+
{ id: "helper", agentDir: "/tmp/openclaw-helper-agent" },
485+
{ id: "molty", agentDir: "/tmp/openclaw-molty-agent" },
486+
],
487+
},
488+
} as never;
489+
const bridge = provider.createBridge({
490+
cfg,
491+
agentId: "molty",
492+
providerConfig: { model: "gpt-realtime-2" },
493+
onAudio: vi.fn(),
494+
onClearAudio: vi.fn(),
495+
});
496+
497+
void bridge.connect();
498+
await vi.waitFor(() => expect(FakeWebSocket.instances.length).toBe(1));
499+
bridge.close();
500+
501+
expect(resolveProviderAuthProfileApiKeyMock).toHaveBeenCalledWith({
502+
provider: "openai",
503+
cfg,
504+
agentDir: "/tmp/openclaw-molty-agent",
460505
profileTypes: ["api_key"],
461506
includeExternalCliAuth: false,
462507
});

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ async function createOpenAIRealtimeBrowserSession(
187187
const auth = await requireOpenAIRealtimePlatformAuth({
188188
configuredApiKey: config.apiKey,
189189
cfg: req.cfg,
190+
agentId: req.agentId,
190191
});
191192
const voice = normalizeOpenAIRealtimeVoice(req.voice) ?? config.voice ?? "alloy";
192193
const sessionConfig = buildOpenAIRealtimeGaSessionPolicy({
@@ -268,12 +269,14 @@ async function createOpenAIRealtimeBrowserSession(
268269
const auth = await resolveOpenAIRealtimePlatformAuth({
269270
configuredApiKey: config.apiKey,
270271
cfg: req.cfg,
272+
agentId: req.agentId,
271273
});
272274
if (auth.status === "missing") {
273275
if (
274276
hasOpenAIRealtimePlatformAuthInput({
275277
configuredApiKey: config.apiKey,
276278
cfg: req.cfg,
279+
agentId: req.agentId,
277280
})
278281
) {
279282
throw new Error(OPENAI_REALTIME_PLATFORM_AUTH_REQUIRED);
@@ -334,7 +337,7 @@ export function buildOpenAIRealtimeVoiceProvider(options?: {
334337
autoSelectOrder: 10,
335338
capabilities: OPENAI_REALTIME_CAPABILITIES,
336339
resolveConfig: ({ rawConfig }) => normalizeProviderConfig(rawConfig),
337-
isConfigured: ({ cfg, providerConfig }) => {
340+
isConfigured: ({ cfg, providerConfig, agentId }) => {
338341
const config = normalizeProviderConfig(providerConfig);
339342
if (config.azureEndpoint || config.azureDeployment) {
340343
return hasOpenAIRealtimeApiKeyInput(config.apiKey);
@@ -343,6 +346,7 @@ export function buildOpenAIRealtimeVoiceProvider(options?: {
343346
hasOpenAIRealtimePlatformAuthInput({
344347
configuredApiKey: config.apiKey,
345348
cfg,
349+
agentId,
346350
})
347351
) {
348352
return true;
@@ -384,6 +388,7 @@ export function buildOpenAIRealtimeVoiceProvider(options?: {
384388
await requireOpenAIRealtimePlatformAuth({
385389
configuredApiKey: config.apiKey,
386390
cfg: req.cfg,
391+
agentId: req.agentId,
387392
})
388393
).value,
389394
}),
@@ -429,6 +434,7 @@ export function buildOpenAIRealtimeVoiceProvider(options?: {
429434
(hasOpenAIRealtimePlatformAuthInput({
430435
configuredApiKey: config.apiKey,
431436
cfg,
437+
agentId,
432438
}) ||
433439
hasOpenAIChatGptSubscriptionAuthInput({ cfg, agentId }))
434440
);
@@ -437,6 +443,7 @@ export function buildOpenAIRealtimeVoiceProvider(options?: {
437443
hasOpenAIRealtimePlatformAuthInput({
438444
configuredApiKey: config.apiKey,
439445
cfg,
446+
agentId,
440447
}) ||
441448
(options?.quicksilverBrowserSessionBroker !== undefined &&
442449
hasOpenAIChatGptSubscriptionAuthInput({ cfg, agentId }))
@@ -471,6 +478,7 @@ export function buildOpenAIRealtimeVoiceProvider(options?: {
471478
(hasOpenAIRealtimePlatformAuthInput({
472479
configuredApiKey: config.apiKey,
473480
cfg,
481+
agentId,
474482
}) ||
475483
hasOpenAIChatGptSubscriptionAuthInput({ cfg, agentId }))
476484
);

‎extensions/openai/realtime-voice-session-policy.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,7 @@ export function buildOpenAIRealtimeGaSessionPolicy(params: {
520520
export async function resolveOpenAIRealtimePlatformAuth(params: {
521521
configuredApiKey: string | undefined;
522522
cfg: RealtimeVoiceBrowserSessionCreateRequest["cfg"] | undefined;
523+
agentId?: string;
523524
}): Promise<OpenAIRealtimeApiKeyResolution> {
524525
const configured = resolveOpenAIRealtimeSecretInput(params.configuredApiKey);
525526
if (
@@ -532,6 +533,9 @@ export async function resolveOpenAIRealtimePlatformAuth(params: {
532533
const profileApiKey = await resolveProviderAuthProfileApiKey({
533534
provider: "openai",
534535
cfg: params.cfg,
536+
...(params.cfg && params.agentId
537+
? { agentDir: resolveAgentDir(params.cfg, params.agentId) }
538+
: {}),
535539
profileTypes: ["api_key"],
536540
includeExternalCliAuth: false,
537541
});
@@ -548,6 +552,7 @@ export async function resolveOpenAIRealtimePlatformAuth(params: {
548552
export async function requireOpenAIRealtimePlatformAuth(params: {
549553
configuredApiKey: string | undefined;
550554
cfg: RealtimeVoiceBrowserSessionCreateRequest["cfg"] | undefined;
555+
agentId?: string;
551556
}): Promise<Extract<OpenAIRealtimeApiKeyResolution, { status: "available" }>> {
552557
const resolved = await resolveOpenAIRealtimePlatformAuth(params);
553558
if (resolved.status === "available") {
@@ -577,6 +582,7 @@ export async function resolveOpenAIQuicksilverBridgeAuth(params: {
577582
hasOpenAIRealtimePlatformAuthInput({
578583
configuredApiKey: params.configuredApiKey,
579584
cfg: params.cfg,
585+
agentId: params.agentId,
580586
})
581587
) {
582588
throw new Error(OPENAI_GPT_LIVE_AUTHORED_PLATFORM_AUTH_UNAVAILABLE);
@@ -587,6 +593,7 @@ export async function resolveOpenAIQuicksilverBridgeAuth(params: {
587593
export function hasOpenAIRealtimePlatformAuthInput(params: {
588594
configuredApiKey: string | undefined;
589595
cfg: RealtimeVoiceBrowserSessionCreateRequest["cfg"] | undefined;
596+
agentId?: string;
590597
}): boolean {
591598
if (hasOpenAIRealtimeConfiguredApiKeyInput(params.configuredApiKey)) {
592599
return true;
@@ -595,6 +602,9 @@ export function hasOpenAIRealtimePlatformAuthInput(params: {
595602
isProviderAuthProfileConfigured({
596603
provider: "openai",
597604
cfg: params.cfg,
605+
...(params.cfg && params.agentId
606+
? { agentDir: resolveAgentDir(params.cfg, params.agentId) }
607+
: {}),
598608
profileTypes: ["api_key"],
599609
includeExternalCliAuth: false,
600610
})

‎extensions/voice-call/src/runtime.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,9 @@ describe("createVoiceCallRuntime lifecycle", () => {
366366
});
367367

368368
const resolveInstructions = mocks.realtimeHandlerCtorArgs[0]?.[7];
369+
expect(mocks.resolveConfiguredRealtimeVoiceProvider).toHaveBeenCalledWith(
370+
expect.objectContaining({ agentId: "operator" }),
371+
);
369372
if (typeof resolveInstructions !== "function") {
370373
throw new Error("expected per-call realtime instruction resolver");
371374
}

‎extensions/voice-call/src/runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@ async function resolveRealtimeProvider(params: {
238238
configuredProviderId: params.config.realtime.provider,
239239
providerConfigs: params.config.realtime.providers,
240240
cfg: params.fullConfig,
241+
agentId: params.config.agentId,
241242
});
242243
}
243244

‎extensions/voice-call/src/webhook/realtime-handler.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,7 @@ describe("RealtimeCallHandler path routing", () => {
572572
}),
573573
);
574574
expect(createBridge.mock.calls[0]?.[0].instructions).toBe("instructions:support");
575+
expect(createBridge.mock.calls[0]?.[0].agentId).toBe("support");
575576
} finally {
576577
if (ws.readyState !== WebSocket.CLOSED && ws.readyState !== WebSocket.CLOSING) {
577578
ws.close();

0 commit comments

Comments
 (0)