Skip to content

Commit 5275eae

Browse files
authored
fix(voice-call): honor routed agent credentials for realtime calls (#125144)
* fix(voice-call): select realtime provider per routed call * test(voice-call): track routing temp directory * fix(ci): stop counting node check as environment variable
1 parent 65d1fa4 commit 5275eae

10 files changed

Lines changed: 573 additions & 146 deletions

File tree

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2+
import type { OpenKeyedStoreOptions } from "openclaw/plugin-sdk/plugin-state-runtime";
3+
import {
4+
createPluginStateSyncKeyedStoreForTests,
5+
resetPluginStateStoreForTests,
6+
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
7+
import type {
8+
RealtimeVoiceBridge,
9+
RealtimeVoiceProviderPlugin,
10+
} from "openclaw/plugin-sdk/realtime-voice";
11+
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
12+
import { afterEach, describe, expect, it, vi } from "vitest";
13+
import { WebSocket } from "ws";
14+
import type { VoiceCallStateRuntime } from "./runtime-state.js";
15+
import { createVoiceCallRuntime, type VoiceCallRuntime } from "./runtime.js";
16+
import { createVoiceCallBaseConfig } from "./test-fixtures.js";
17+
import { connectWs, startUpgradeWsServer, waitForClose } from "./websocket-test-support.js";
18+
19+
const mocks = vi.hoisted(() => ({
20+
resolveConfiguredRealtimeVoiceProvider: vi.fn(),
21+
}));
22+
23+
vi.mock("./realtime-voice.runtime.js", async (importOriginal) => {
24+
const actual = await importOriginal<typeof import("./realtime-voice.runtime.js")>();
25+
return {
26+
...actual,
27+
resolveConfiguredRealtimeVoiceProvider: mocks.resolveConfiguredRealtimeVoiceProvider,
28+
};
29+
});
30+
31+
function createStateRuntime(): VoiceCallStateRuntime["state"] {
32+
return {
33+
resolveStateDir: () => "",
34+
openKeyedStore: (() => {
35+
throw new Error("openKeyedStore is not used by realtime routing tests");
36+
}) as VoiceCallStateRuntime["state"]["openKeyedStore"],
37+
openSyncKeyedStore: <T>(options: OpenKeyedStoreOptions) =>
38+
createPluginStateSyncKeyedStoreForTests<T>("voice-call", options),
39+
openChannelIngressQueue: (() => {
40+
throw new Error("openChannelIngressQueue is not used by realtime routing tests");
41+
}) as VoiceCallStateRuntime["state"]["openChannelIngressQueue"],
42+
openChannelIngressDrain: (() => {
43+
throw new Error("openChannelIngressDrain is not used by realtime routing tests");
44+
}) as VoiceCallStateRuntime["state"]["openChannelIngressDrain"],
45+
};
46+
}
47+
48+
function createRealtimeProvider(params: {
49+
id: string;
50+
connect: ReturnType<typeof vi.fn<() => Promise<void>>>;
51+
}): RealtimeVoiceProviderPlugin {
52+
return {
53+
id: params.id,
54+
label: params.id,
55+
isConfigured: () => true,
56+
createBridge: vi.fn(
57+
(): RealtimeVoiceBridge => ({
58+
connect: params.connect,
59+
sendAudio: vi.fn(),
60+
setMediaTimestamp: vi.fn(),
61+
submitToolResult: vi.fn(),
62+
acknowledgeMark: vi.fn(),
63+
close: vi.fn(),
64+
isConnected: () => true,
65+
triggerGreeting: vi.fn(),
66+
}),
67+
),
68+
};
69+
}
70+
71+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
72+
73+
afterEach(() => {
74+
mocks.resolveConfiguredRealtimeVoiceProvider.mockReset();
75+
resetPluginStateStoreForTests();
76+
});
77+
78+
describe("voice-call realtime route ownership", () => {
79+
it("selects provider readiness and bridge auth from each inbound number owner", async () => {
80+
const storePath = tempDirs.make("openclaw-voice-routing-");
81+
const sockets: WebSocket[] = [];
82+
const servers: Array<Awaited<ReturnType<typeof startUpgradeWsServer>>> = [];
83+
let runtime: VoiceCallRuntime | undefined;
84+
const salesConnect = vi.fn(async () => {});
85+
const supportConnect = vi.fn(async () => {});
86+
const salesProvider = createRealtimeProvider({ id: "openai", connect: salesConnect });
87+
const supportProvider = createRealtimeProvider({ id: "xai", connect: supportConnect });
88+
const registrations = new Map([
89+
[
90+
"sales",
91+
{
92+
provider: salesProvider,
93+
providerConfig: { credentialOwner: "sales", model: "gpt-realtime" },
94+
},
95+
],
96+
[
97+
"support",
98+
{
99+
provider: supportProvider,
100+
providerConfig: { credentialOwner: "support", model: "grok-voice" },
101+
},
102+
],
103+
]);
104+
mocks.resolveConfiguredRealtimeVoiceProvider.mockImplementation(
105+
({ agentId }: { agentId?: string }) => {
106+
const registration = agentId ? registrations.get(agentId) : undefined;
107+
if (!registration) {
108+
throw new Error(`No simulated realtime credentials for ${agentId ?? "unknown"}`);
109+
}
110+
return registration;
111+
},
112+
);
113+
114+
try {
115+
const config = createVoiceCallBaseConfig();
116+
config.agentId = "main";
117+
config.store = storePath;
118+
config.inboundPolicy = "open";
119+
config.maxConcurrentCalls = 2;
120+
config.staleCallReaperSeconds = 0;
121+
config.serve = { ...config.serve, port: 0 };
122+
config.realtime.enabled = true;
123+
config.numbers = {
124+
"+15550001001": { agentId: "sales" },
125+
"+15550001002": { agentId: "support" },
126+
};
127+
const fullConfig = {
128+
agents: {
129+
list: [{ id: "main", default: true }, { id: "sales" }, { id: "support" }],
130+
},
131+
} as OpenClawConfig;
132+
133+
runtime = await createVoiceCallRuntime({
134+
config,
135+
coreConfig: fullConfig,
136+
fullConfig,
137+
agentRuntime: {} as never,
138+
stateRuntime: createStateRuntime(),
139+
});
140+
expect(mocks.resolveConfiguredRealtimeVoiceProvider).not.toHaveBeenCalled();
141+
142+
const handler = runtime.webhookServer.getRealtimeHandler();
143+
if (!handler) {
144+
throw new Error("expected realtime handler");
145+
}
146+
const routes = [
147+
{ to: "+15550001001", callSid: "CA-sales", streamSid: "MZ-sales" },
148+
{ to: "+15550001002", callSid: "CA-support", streamSid: "MZ-support" },
149+
];
150+
for (const route of routes) {
151+
const { streamUrl } = handler.issueStreamSession({
152+
providerName: "twilio",
153+
direction: "inbound",
154+
from: "+15550009999",
155+
to: route.to,
156+
});
157+
const server = await startUpgradeWsServer({
158+
urlPath: new URL(streamUrl).pathname,
159+
onUpgrade: (request, socket, head) => {
160+
handler.handleWebSocketUpgrade(request, socket, head);
161+
},
162+
});
163+
servers.push(server);
164+
const ws = await connectWs(server.url);
165+
sockets.push(ws);
166+
ws.send(
167+
JSON.stringify({
168+
event: "start",
169+
start: { streamSid: route.streamSid, callSid: route.callSid },
170+
}),
171+
);
172+
}
173+
174+
await vi.waitFor(() => {
175+
expect(salesProvider.createBridge).toHaveBeenCalledTimes(1);
176+
expect(supportProvider.createBridge).toHaveBeenCalledTimes(1);
177+
expect(salesConnect).toHaveBeenCalledTimes(1);
178+
expect(supportConnect).toHaveBeenCalledTimes(1);
179+
});
180+
expect(salesProvider.createBridge).toHaveBeenCalledWith(
181+
expect.objectContaining({
182+
agentId: "sales",
183+
providerConfig: { credentialOwner: "sales", model: "gpt-realtime" },
184+
}),
185+
);
186+
expect(supportProvider.createBridge).toHaveBeenCalledWith(
187+
expect.objectContaining({
188+
agentId: "support",
189+
providerConfig: { credentialOwner: "support", model: "grok-voice" },
190+
}),
191+
);
192+
expect(
193+
mocks.resolveConfiguredRealtimeVoiceProvider.mock.calls.map(
194+
([options]) => (options as { agentId?: string }).agentId,
195+
),
196+
).toEqual(["sales", "support"]);
197+
198+
for (const ws of sockets) {
199+
const closed = waitForClose(ws);
200+
ws.close(1000);
201+
await closed;
202+
}
203+
await vi.waitFor(() => expect(runtime?.manager.getActiveCalls()).toHaveLength(0));
204+
} finally {
205+
await runtime?.stop();
206+
for (const ws of sockets) {
207+
if (ws.readyState !== WebSocket.CLOSED) {
208+
ws.terminate();
209+
}
210+
}
211+
await Promise.all(servers.map((server) => server.close()));
212+
resetPluginStateStoreForTests();
213+
}
214+
});
215+
});

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

Lines changed: 68 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ describe("createVoiceCallRuntime lifecycle", () => {
242242
mocks.realtimeHandlerCtorArgs.length = 0;
243243
mocks.realtimeHandlerRegisterToolHandler.mockReset();
244244
mocks.realtimeHandlerSetPublicUrl.mockReset();
245-
mocks.resolveConfiguredRealtimeVoiceProvider.mockResolvedValue({
245+
mocks.resolveConfiguredRealtimeVoiceProvider.mockReturnValue({
246246
provider: { id: "openai" },
247247
providerConfig: { model: "gpt-realtime" },
248248
});
@@ -365,42 +365,95 @@ describe("createVoiceCallRuntime lifecycle", () => {
365365
} as never,
366366
});
367367

368-
const resolveInstructions = mocks.realtimeHandlerCtorArgs[0]?.[7];
369-
expect(mocks.resolveConfiguredRealtimeVoiceProvider).toHaveBeenCalledWith(
370-
expect.objectContaining({ agentId: "operator" }),
371-
);
372-
if (typeof resolveInstructions !== "function") {
373-
throw new Error("expected per-call realtime instruction resolver");
368+
const resolveCallRegistration = mocks.realtimeHandlerCtorArgs[0]?.[3];
369+
expect(mocks.resolveConfiguredRealtimeVoiceProvider).not.toHaveBeenCalled();
370+
if (typeof resolveCallRegistration !== "function") {
371+
throw new Error("expected per-call realtime registration resolver");
374372
}
375373
expect(runtime.config.agentId).toBe("operator");
376-
const defaultInstructions = resolveInstructions({
374+
const defaultRegistration = resolveCallRegistration({
377375
callId: "call-default",
378376
direction: "outbound",
379377
from: "+15550001111",
380378
to: "+15550002222",
381379
});
382-
expect(defaultInstructions).toContain("- Agent id: operator");
380+
expect(defaultRegistration.agentId).toBe("operator");
381+
expect(defaultRegistration.instructions).toContain("- Agent id: operator");
383382
expect(resolveAgentIdentity).toHaveBeenCalledWith(fullConfig, "operator");
384383

385-
const supportInstructions = resolveInstructions({
384+
const supportRegistration = resolveCallRegistration({
386385
callId: "call-support",
387386
agentId: "support",
388387
direction: "outbound",
389388
from: "+15550001111",
390389
to: "+15550002222",
391390
});
392-
expect(supportInstructions).toContain("- Agent id: support");
393-
expect(supportInstructions).toContain("- Name: Support Voice");
394-
expect(supportInstructions).not.toContain("Main Voice");
391+
expect(supportRegistration.agentId).toBe("support");
392+
expect(supportRegistration.instructions).toContain("- Agent id: support");
393+
expect(supportRegistration.instructions).toContain("- Name: Support Voice");
394+
expect(supportRegistration.instructions).not.toContain("Main Voice");
395395

396-
const unknownInstructions = resolveInstructions({
396+
const unknownRegistration = resolveCallRegistration({
397397
callId: "call-unknown",
398398
agentId: "unknown",
399399
direction: "outbound",
400400
from: "+15550001111",
401401
to: "+15550002222",
402402
});
403-
expect(unknownInstructions).not.toContain("OpenClaw agent voice context:");
403+
expect(unknownRegistration.instructions).not.toContain("OpenClaw agent voice context:");
404+
});
405+
406+
it("selects realtime provider readiness from the routed call owner", async () => {
407+
const config = createBaseConfig();
408+
config.agentId = "main";
409+
config.realtime.enabled = true;
410+
config.numbers["+15550009999"] = { agentId: "support" };
411+
const fullConfig = {
412+
agents: { list: [{ id: "main", default: true }, { id: "support" }] },
413+
} as OpenClawConfig;
414+
mocks.resolveConfiguredRealtimeVoiceProvider.mockImplementation(
415+
({ agentId }: { agentId?: string }) => {
416+
if (agentId !== "support") {
417+
throw new Error(`OpenAI realtime is not configured for ${agentId ?? "unknown"}`);
418+
}
419+
return {
420+
provider: { id: "openai-support" },
421+
providerConfig: { model: "gpt-realtime", owner: agentId },
422+
};
423+
},
424+
);
425+
426+
await expect(
427+
createVoiceCallRuntime({
428+
config,
429+
coreConfig: {} as OpenClawConfig,
430+
fullConfig,
431+
agentRuntime: {} as never,
432+
}),
433+
).resolves.toMatchObject({ config: { agentId: "main" } });
434+
expect(mocks.resolveConfiguredRealtimeVoiceProvider).not.toHaveBeenCalled();
435+
436+
const resolveCallRegistration = mocks.realtimeHandlerCtorArgs[0]?.[3];
437+
if (typeof resolveCallRegistration !== "function") {
438+
throw new Error("expected per-call realtime registration resolver");
439+
}
440+
const registration = resolveCallRegistration({
441+
callId: "call-support",
442+
agentId: "support",
443+
direction: "inbound",
444+
from: "+15550001234",
445+
to: "+15550009999",
446+
metadata: { numberRouteKey: "+15550009999" },
447+
});
448+
449+
expect(registration).toMatchObject({
450+
agentId: "support",
451+
provider: { id: "openai-support" },
452+
providerConfig: { model: "gpt-realtime", owner: "support" },
453+
});
454+
expect(mocks.resolveConfiguredRealtimeVoiceProvider).toHaveBeenCalledExactlyOnceWith(
455+
expect.objectContaining({ agentId: "support" }),
456+
);
404457
});
405458

406459
it.each(["twilio", "telnyx", "plivo"] as const)(

0 commit comments

Comments
 (0)