Skip to content

Commit 1acabe4

Browse files
authored
feat(voice-call): let realtime agents end calls (#125525)
1 parent a0c5937 commit 1acabe4

8 files changed

Lines changed: 357 additions & 8 deletions

File tree

‎docs/plugins/voice-call.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ Current runtime behavior:
275275
- `realtime.provider` is optional. If unset, Voice Call uses the first registered realtime voice provider.
276276
- Bundled realtime voice providers: Google Gemini Live (`google`) and OpenAI (`openai`), registered by their provider plugins.
277277
- Provider-owned raw config lives under `realtime.providers.<providerId>`.
278+
- Voice Call exposes the built-in `openclaw_end_call` realtime tool on every call. It takes no arguments or call ID; the active voice bridge binds it to the current call.
278279
- Voice Call exposes the shared `openclaw_agent_consult` realtime tool by default. The realtime model can call it when the caller asks for deeper reasoning, current information, or normal OpenClaw tools.
279280
- `realtime.consultPolicy` optionally adds guidance for when the realtime model should call `openclaw_agent_consult`.
280281
- `realtime.agentContext.enabled` is default-off. When enabled, Voice Call injects a bounded agent identity and selected workspace-file capsule into the realtime provider instructions at session setup.
@@ -290,6 +291,13 @@ the media WebSocket. If an intermediary does not promptly forward that close,
290291
OpenClaw treats 30 seconds without inbound media as a disconnect, waits a
291292
2-second grace period for media to resume, and then ends the call.
292293

294+
The realtime model can also call `openclaw_end_call` when the caller asks to
295+
hang up. The model must speak any final words before calling the tool: a
296+
successful call ends the current provider session and phone connection
297+
immediately, so no later reply is spoken. If the carrier cannot end the call,
298+
the bridge stays connected and the model receives an error it can explain to
299+
the caller. Configured `realtime.tools` cannot replace this built-in by name.
300+
293301
For inbound Twilio numbers, also configure a Status Callback using `POST` to
294302
your public webhook URL with `?type=status` appended, for example
295303
`https://voice.example.com/voice/webhook?type=status`. Include the `completed`
@@ -299,13 +307,14 @@ close and the inactivity backstop remain independent of it.
299307

300308
### Tool policy
301309

302-
`realtime.toolPolicy` controls the consult run:
310+
`realtime.toolPolicy` controls only the consult run. It never disables
311+
`openclaw_end_call`:
303312

304313
| Policy | Behavior |
305314
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
306315
| `safe-read-only` | Expose the consult tool and limit the regular agent to `read`, `web_search`, `web_fetch`, `x_search`, `memory_search`, and `memory_get`. |
307316
| `owner` | Expose the consult tool and let the regular agent use the normal agent tool policy. |
308-
| `none` | Do not expose the consult tool. Custom `realtime.tools` are still passed through to the realtime provider. |
317+
| `none` | Do not expose the consult tool. The built-in end-call tool and custom `realtime.tools` remain available. |
309318

310319
`realtime.consultPolicy` controls only the realtime model instructions:
311320

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,8 @@ describe("normalizeVoiceCallConfig", () => {
783783
files: ["SOUL.md", "IDENTITY.md", "USER.md"],
784784
});
785785
expect(normalized.realtime.instructions).toContain("openclaw_agent_consult");
786+
expect(normalized.realtime.instructions).toContain("openclaw_end_call");
787+
expect(normalized.realtime.instructions).toContain("speak any final words first");
786788
expect(normalized.tunnel.provider).toBe("none");
787789
expect(normalized.webhookSecurity.allowedHosts).toStrictEqual([]);
788790
});
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Voice Call plugin module defines provider-facing realtime call controls.
2+
import {
3+
resolveRealtimeVoiceAgentConsultTools,
4+
type RealtimeVoiceAgentConsultToolPolicy,
5+
type RealtimeVoiceTool,
6+
} from "openclaw/plugin-sdk/realtime-voice";
7+
8+
/** Stable provider-facing tool name for ending the current phone call. */
9+
export const REALTIME_VOICE_END_CALL_TOOL_NAME = "openclaw_end_call";
10+
11+
/** Closure-bound end-call control exposed on every realtime phone call. */
12+
const REALTIME_VOICE_END_CALL_TOOL: RealtimeVoiceTool = {
13+
type: "function",
14+
name: REALTIME_VOICE_END_CALL_TOOL_NAME,
15+
description:
16+
"End the current phone call immediately. Speak any final words to the caller before invoking this tool because the call ends as soon as it is invoked and no further reply will be spoken.",
17+
parameters: {
18+
type: "object",
19+
properties: {},
20+
},
21+
};
22+
23+
/** Merge built-in call controls with consult and configured realtime tools. */
24+
export function resolveVoiceCallRealtimeTools(
25+
policy: RealtimeVoiceAgentConsultToolPolicy,
26+
customTools: RealtimeVoiceTool[] = [],
27+
): RealtimeVoiceTool[] {
28+
const tools = resolveRealtimeVoiceAgentConsultTools(policy, customTools).filter(
29+
(tool) => tool.name !== REALTIME_VOICE_END_CALL_TOOL_NAME,
30+
);
31+
return [REALTIME_VOICE_END_CALL_TOOL, ...tools];
32+
}
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// Voice Call plugin module implements realtime defaults behavior.
22
import { REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME } from "openclaw/plugin-sdk/realtime-voice";
3+
import { REALTIME_VOICE_END_CALL_TOOL_NAME } from "./realtime-call-control.js";
34

45
// Default realtime instructions for the voice-call plugin's phone interface.
56

67
/** Baseline instructions that keep realtime calls brief and route deep work to agent consult. */
7-
export const DEFAULT_VOICE_CALL_REALTIME_INSTRUCTIONS = `You are OpenClaw's phone-call realtime voice interface. Keep spoken replies brief and natural. When a question needs deeper reasoning, current information, or tools, call ${REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME} before answering.`;
8+
export const DEFAULT_VOICE_CALL_REALTIME_INSTRUCTIONS = `You are OpenClaw's phone-call realtime voice interface. Keep spoken replies brief and natural. When a question needs deeper reasoning, current information, or tools, call ${REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME} before answering. When the caller asks to end the call, speak any final words first, then call ${REALTIME_VOICE_END_CALL_TOOL_NAME}; it ends the call immediately and nothing after it will be spoken.`;

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,7 @@ describe("createVoiceCallRuntime lifecycle", () => {
617617
throw new Error("expected realtime handler tools to be an array");
618618
}
619619
expect(tools.map((tool) => requireRecord(tool, "realtime tool").name)).toEqual([
620+
"openclaw_end_call",
620621
"openclaw_agent_consult",
621622
"custom_tool",
622623
]);
@@ -653,6 +654,53 @@ describe("createVoiceCallRuntime lifecycle", () => {
653654
expect(consultParams.prompt).toContain("Caller: Also check the ETA.");
654655
});
655656

657+
it("always exposes the built-in end-call tool without allowing configured replacement", async () => {
658+
const config = createBaseConfig();
659+
config.realtime.enabled = true;
660+
config.realtime.toolPolicy = "none";
661+
config.realtime.tools = [
662+
{
663+
type: "function",
664+
name: "openclaw_end_call",
665+
description: "Configured replacement",
666+
parameters: { type: "object", properties: { callId: { type: "string" } } },
667+
},
668+
{
669+
type: "function",
670+
name: "custom_tool",
671+
description: "Custom tool",
672+
parameters: { type: "object", properties: {} },
673+
},
674+
];
675+
676+
await createVoiceCallRuntime({
677+
config,
678+
coreConfig: {} as OpenClawConfig,
679+
agentRuntime: {} as never,
680+
});
681+
682+
const realtimeHandlerOptions = requireRecord(
683+
mocks.realtimeHandlerCtorArgs[0]?.[0],
684+
"realtime handler options",
685+
);
686+
const tools = realtimeHandlerOptions.tools;
687+
if (!Array.isArray(tools)) {
688+
throw new Error("expected realtime handler tools to be an array");
689+
}
690+
expect(tools.map((tool) => requireRecord(tool, "realtime tool").name)).toEqual([
691+
"openclaw_end_call",
692+
"custom_tool",
693+
]);
694+
const endCallTool = requireRecord(tools[0], "end-call tool");
695+
expect(endCallTool.description).toContain("final words");
696+
expect(endCallTool.description).toContain("no further reply");
697+
expect(requireRecord(endCallTool.parameters, "end-call parameters")).toEqual({
698+
type: "object",
699+
properties: {},
700+
});
701+
expect(mocks.realtimeHandlerRegisterToolHandler).not.toHaveBeenCalled();
702+
});
703+
656704
it("rejects a realtime consult whose lifecycle owner already aborted", async () => {
657705
const config = createBaseConfig();
658706
config.realtime.enabled = true;

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import {
88
assertRealtimeVoiceAgentConsultModelSelectionUnlocked,
99
consultRealtimeVoiceAgent,
1010
REALTIME_VOICE_AGENT_CONSULT_TOOL_NAME,
11-
resolveRealtimeVoiceAgentConsultTools,
1211
resolveRealtimeVoiceAgentConsultToolsAllow,
1312
type RealtimeVoiceAgentConsultTranscriptEntry,
1413
} from "openclaw/plugin-sdk/realtime-voice";
@@ -28,6 +27,7 @@ import { CallManager } from "./manager.js";
2827
import type { VoiceCallProvider } from "./providers/base.js";
2928
import type { TwilioProvider } from "./providers/twilio.js";
3029
import { buildRealtimeVoiceInstructions } from "./realtime-agent-context.js";
30+
import { resolveVoiceCallRealtimeTools } from "./realtime-call-control.js";
3131
import { resolveRealtimeFastContextConsult } from "./realtime-fast-context.js";
3232
import { resolveCallAgentId } from "./resolve-call-agent-id.js";
3333
import { resolveVoiceResponseModel } from "./response-model.js";
@@ -352,10 +352,7 @@ export async function createVoiceCallRuntime(params: {
352352
});
353353
const realtimeConfig = {
354354
...config.realtime,
355-
tools: resolveRealtimeVoiceAgentConsultTools(
356-
config.realtime.toolPolicy,
357-
config.realtime.tools,
358-
),
355+
tools: resolveVoiceCallRealtimeTools(config.realtime.toolPolicy, config.realtime.tools),
359356
};
360357
const resolveCallRegistration = (call: CallRecord) => {
361358
const numberRouteKey = resolveVoiceCallNumberRouteKeyForCall(call);

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

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,6 +1356,197 @@ describe("RealtimeCallHandler path routing", () => {
13561356
);
13571357
});
13581358

1359+
it("ends the closure-bound current call without requesting another provider response", async () => {
1360+
let callbacks: RealtimeBridgeRequest | undefined;
1361+
const closeBridge = vi.fn();
1362+
const submitToolResult = vi.fn();
1363+
const createBridge = vi.fn((request: RealtimeBridgeRequest) => {
1364+
callbacks = request;
1365+
return makeBridge({ close: closeBridge, submitToolResult });
1366+
});
1367+
const call = makeCallRecord("CA-end-current");
1368+
const endCall = vi.fn(async (_callId: string) => ({ success: true }));
1369+
const handler = makeHandler(undefined, {
1370+
manager: {
1371+
endCall,
1372+
getCallByProviderCallId: vi.fn(() => call),
1373+
},
1374+
realtimeProvider: makeRealtimeProvider(createBridge),
1375+
});
1376+
const server = await startRealtimeServer(handler);
1377+
const ws = await connectWs(server.url);
1378+
1379+
try {
1380+
ws.send(
1381+
JSON.stringify({
1382+
event: "start",
1383+
start: { streamSid: "MZ-end-current", callSid: "CA-end-current" },
1384+
}),
1385+
);
1386+
await waitForRealtimeTest(() => expect(createBridge).toHaveBeenCalledOnce());
1387+
1388+
const closed = waitForClose(ws);
1389+
callbacks?.onToolCall?.({
1390+
itemId: "item-end-current",
1391+
callId: "provider-end-current",
1392+
name: "openclaw_end_call",
1393+
args: {},
1394+
});
1395+
1396+
await waitForRealtimeTest(() => {
1397+
expect(endCall).toHaveBeenCalledExactlyOnceWith("call-1");
1398+
expect(closeBridge).toHaveBeenCalledOnce();
1399+
});
1400+
expect(await closed).toEqual({ code: 1000, reason: "Call ended" });
1401+
expect(submitToolResult).not.toHaveBeenCalled();
1402+
expect(recentTalkEvents(call)).toEqual(
1403+
expect.arrayContaining([expect.objectContaining({ type: "tool.result" })]),
1404+
);
1405+
} finally {
1406+
if (ws.readyState !== WebSocket.CLOSED) {
1407+
ws.terminate();
1408+
}
1409+
await handler.close();
1410+
await server.close();
1411+
}
1412+
});
1413+
1414+
it("reports an actionable end-call failure while leaving the current call connected", async () => {
1415+
let callbacks: RealtimeBridgeRequest | undefined;
1416+
const closeBridge = vi.fn();
1417+
const submitToolResult = vi.fn();
1418+
const createBridge = vi.fn((request: RealtimeBridgeRequest) => {
1419+
callbacks = request;
1420+
return makeBridge({ close: closeBridge, submitToolResult });
1421+
});
1422+
const call = makeCallRecord("CA-end-failed");
1423+
const endCall = vi.fn(async () => ({ success: false, error: "carrier rejected hangup" }));
1424+
const handler = makeHandler(undefined, {
1425+
manager: {
1426+
endCall,
1427+
getCallByProviderCallId: vi.fn(() => call),
1428+
},
1429+
realtimeProvider: makeRealtimeProvider(createBridge),
1430+
});
1431+
const server = await startRealtimeServer(handler);
1432+
const ws = await connectWs(server.url);
1433+
1434+
try {
1435+
ws.send(
1436+
JSON.stringify({
1437+
event: "start",
1438+
start: { streamSid: "MZ-end-failed", callSid: "CA-end-failed" },
1439+
}),
1440+
);
1441+
await waitForRealtimeTest(() => expect(createBridge).toHaveBeenCalledOnce());
1442+
1443+
callbacks?.onToolCall?.({
1444+
itemId: "item-end-failed",
1445+
callId: "provider-end-failed",
1446+
name: "openclaw_end_call",
1447+
args: {},
1448+
});
1449+
1450+
await waitForRealtimeTest(() => {
1451+
expect(submitToolResult).toHaveBeenCalledWith(
1452+
"provider-end-failed",
1453+
{
1454+
error:
1455+
"Could not end the current phone call: carrier rejected hangup. Tell the caller the call could not be ended and they can hang up or ask you to try again.",
1456+
},
1457+
undefined,
1458+
);
1459+
});
1460+
expect(endCall).toHaveBeenCalledExactlyOnceWith("call-1");
1461+
expect(closeBridge).not.toHaveBeenCalled();
1462+
expect(ws.readyState).toBe(WebSocket.OPEN);
1463+
expect(recentTalkEvents(call)).toEqual(
1464+
expect.arrayContaining([expect.objectContaining({ type: "tool.error" })]),
1465+
);
1466+
} finally {
1467+
if (ws.readyState !== WebSocket.CLOSED && ws.readyState !== WebSocket.CLOSING) {
1468+
ws.close();
1469+
}
1470+
await handler.close();
1471+
await server.close();
1472+
}
1473+
});
1474+
1475+
it("ignores an end-call callback from a retired predecessor bridge", async () => {
1476+
const callbacks: RealtimeBridgeRequest[] = [];
1477+
const predecessorClose = vi.fn();
1478+
const replacementClose = vi.fn();
1479+
const createBridge = vi.fn((request: RealtimeBridgeRequest) => {
1480+
callbacks.push(request);
1481+
return makeBridge({ close: callbacks.length === 1 ? predecessorClose : replacementClose });
1482+
});
1483+
const call = makeCallRecord("CA-end-replacement");
1484+
const endCall = vi.fn(async (_callId: string) => ({ success: true }));
1485+
const handler = makeHandler(undefined, {
1486+
manager: {
1487+
endCall,
1488+
getCallByProviderCallId: vi.fn(() => call),
1489+
},
1490+
realtimeProvider: makeRealtimeProvider(createBridge),
1491+
});
1492+
const predecessorServer = await startRealtimeServer(handler);
1493+
const predecessorWs = await connectWs(predecessorServer.url);
1494+
let replacementServer: Awaited<ReturnType<typeof startRealtimeServer>> | undefined;
1495+
let replacementWs: WebSocket | undefined;
1496+
1497+
try {
1498+
predecessorWs.send(
1499+
JSON.stringify({
1500+
event: "start",
1501+
start: { streamSid: "MZ-end-predecessor", callSid: "CA-end-replacement" },
1502+
}),
1503+
);
1504+
await waitForRealtimeTest(() => expect(createBridge).toHaveBeenCalledTimes(1));
1505+
1506+
replacementServer = await startRealtimeServer(handler);
1507+
replacementWs = await connectWs(replacementServer.url);
1508+
replacementWs.send(
1509+
JSON.stringify({
1510+
event: "start",
1511+
start: { streamSid: "MZ-end-replacement", callSid: "CA-end-replacement" },
1512+
}),
1513+
);
1514+
await waitForRealtimeTest(() => expect(createBridge).toHaveBeenCalledTimes(2));
1515+
expect(predecessorClose).toHaveBeenCalledOnce();
1516+
1517+
callbacks[0]?.onToolCall?.({
1518+
itemId: "item-end-stale",
1519+
callId: "provider-end-stale",
1520+
name: "openclaw_end_call",
1521+
args: {},
1522+
});
1523+
await new Promise<void>((resolve) => {
1524+
setImmediate(resolve);
1525+
});
1526+
1527+
expect(endCall).not.toHaveBeenCalled();
1528+
expect(replacementClose).not.toHaveBeenCalled();
1529+
expect(replacementWs.readyState).toBe(WebSocket.OPEN);
1530+
} finally {
1531+
if (
1532+
replacementWs &&
1533+
replacementWs.readyState !== WebSocket.CLOSED &&
1534+
replacementWs.readyState !== WebSocket.CLOSING
1535+
) {
1536+
replacementWs.close();
1537+
}
1538+
if (
1539+
predecessorWs.readyState !== WebSocket.CLOSED &&
1540+
predecessorWs.readyState !== WebSocket.CLOSING
1541+
) {
1542+
predecessorWs.close();
1543+
}
1544+
await handler.close();
1545+
await replacementServer?.close();
1546+
await predecessorServer.close();
1547+
}
1548+
});
1549+
13591550
it("submits continuing responses only for realtime agent consult calls", async () => {
13601551
let callbacks:
13611552
| {

0 commit comments

Comments
 (0)