Skip to content

Commit c997a9f

Browse files
authored
feat(gateway): add VoiceClaw realtime brain endpoint (#70938)
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests. Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket. Co-authored-by: Michael Yagudaev <[email protected]>
1 parent 7536993 commit c997a9f

15 files changed

Lines changed: 2680 additions & 19 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ Docs: https://docs.openclaw.ai
4848
- Plugins/Bonjour: move LAN Gateway discovery advertising into a default-enabled bundled plugin with its own `@homebridge/ciao` dependency, so users can disable Bonjour without cutting wide-area discovery. Thanks @vincentkoc.
4949
- Providers/Google: add a Gemini Live realtime voice provider for backend Voice Call and Google Meet audio bridges, with bidirectional audio and function-call support.
5050
- Plugins/Google Meet: let realtime Meet sessions consult the full OpenClaw agent for deeper answers while staying in the live voice loop.
51+
- Gateway/VoiceClaw: add a realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating and async OpenClaw tool handoff. (#70938) Thanks @yagudaev.
5152
- Providers/DeepSeek: add DeepSeek V4 Flash and V4 Pro to the bundled catalog and make V4 Flash the onboarding default.
5253

5354
### Fixes

‎docs/gateway/index.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,42 @@ OPENCLAW_CONFIG_PATH=~/.openclaw/b.json OPENCLAW_STATE_DIR=~/.openclaw-b opencla
176176

177177
Detailed setup: [/gateway/multiple-gateways](/gateway/multiple-gateways).
178178

179+
## VoiceClaw real-time brain endpoint
180+
181+
OpenClaw exposes a VoiceClaw-compatible real-time WebSocket endpoint at
182+
`/voiceclaw/realtime`. Use it when a VoiceClaw desktop client should talk
183+
directly to a real-time OpenClaw brain instead of going through a separate relay
184+
process.
185+
186+
The endpoint uses Gemini Live for real-time audio and calls OpenClaw as the
187+
brain by exposing OpenClaw tools directly to Gemini Live. Tool calls return an
188+
immediate `working` result to keep the voice turn responsive, then OpenClaw
189+
executes the actual tool asynchronously and injects the result back into the
190+
live session. Set `GEMINI_API_KEY` in the gateway process environment. If
191+
gateway auth is enabled, the desktop client sends the gateway token or password
192+
in its first `session.config` message.
193+
194+
Real-time brain access runs owner-authorized OpenClaw agent commands. Keep
195+
`gateway.auth.mode: "none"` limited to loopback-only test instances. Non-local
196+
real-time brain connections require gateway auth.
197+
198+
For an isolated test gateway, run a separate instance with its own port, config,
199+
and state:
200+
201+
```bash
202+
OPENCLAW_CONFIG_PATH=/path/to/openclaw-realtime/openclaw.json \
203+
OPENCLAW_STATE_DIR=/path/to/openclaw-realtime/state \
204+
OPENCLAW_SKIP_CHANNELS=1 \
205+
GEMINI_API_KEY=... \
206+
openclaw gateway --port 19789
207+
```
208+
209+
Then configure VoiceClaw to use:
210+
211+
```text
212+
ws://127.0.0.1:19789/voiceclaw/realtime
213+
```
214+
179215
## Remote access
180216

181217
Preferred: Tailscale/VPN.

‎src/gateway/server-http.ts‎

Lines changed: 59 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ import {
7272
import type { PreauthConnectionBudget } from "./server/preauth-connection-budget.js";
7373
import type { ReadinessChecker } from "./server/readiness.js";
7474
import type { GatewayWsClient } from "./server/ws-types.js";
75+
import { VOICECLAW_REALTIME_PATH } from "./voiceclaw-realtime/paths.js";
7576

7677
type SubsystemLogger = ReturnType<typeof createSubsystemLogger>;
7778

@@ -92,6 +93,9 @@ let sessionHistoryHttpModulePromise:
9293
| undefined;
9394
let sessionKillHttpModulePromise: Promise<typeof import("./session-kill-http.js")> | undefined;
9495
let toolsInvokeHttpModulePromise: Promise<typeof import("./tools-invoke-http.js")> | undefined;
96+
let voiceClawRealtimeUpgradeModulePromise:
97+
| Promise<typeof import("./voiceclaw-realtime/upgrade.js")>
98+
| undefined;
9599

96100
function getIdentityAvatarModule() {
97101
identityAvatarModulePromise ??= import("../agents/identity-avatar.js");
@@ -143,6 +147,11 @@ function getToolsInvokeHttpModule() {
143147
return toolsInvokeHttpModulePromise;
144148
}
145149

150+
function getVoiceClawRealtimeUpgradeModule() {
151+
voiceClawRealtimeUpgradeModulePromise ??= import("./voiceclaw-realtime/upgrade.js");
152+
return voiceClawRealtimeUpgradeModulePromise;
153+
}
154+
146155
type HookDispatchers = {
147156
dispatchWakeHook: (value: { text: string; mode: "now" | "next-heartbeat" }) => void;
148157
dispatchAgentHook: (value: HookAgentDispatchPayload) => string;
@@ -377,6 +386,17 @@ function writeUpgradeAuthFailure(
377386
socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
378387
}
379388

389+
function writeUpgradeServiceUnavailable(socket: { write: (chunk: string) => void }, body: string) {
390+
socket.write(
391+
"HTTP/1.1 503 Service Unavailable\r\n" +
392+
"Connection: close\r\n" +
393+
"Content-Type: text/plain; charset=utf-8\r\n" +
394+
`Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n` +
395+
"\r\n" +
396+
body,
397+
);
398+
}
399+
380400
export type HooksRequestHandler = (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
381401

382402
type GatewayHttpRequestStage = {
@@ -1201,8 +1221,8 @@ export function attachGatewayUpgradeHandler(opts: {
12011221
req.url = scopedCanvas.rewrittenUrl;
12021222
}
12031223
const resolvedAuth = getResolvedAuth();
1224+
const url = new URL(req.url ?? "/", "http://localhost");
12041225
if (canvasHost) {
1205-
const url = new URL(req.url ?? "/", "http://localhost");
12061226
if (url.pathname === CANVAS_WS_PATH) {
12071227
const ok = await authorizeCanvasRequest({
12081228
req,
@@ -1225,29 +1245,49 @@ export function attachGatewayUpgradeHandler(opts: {
12251245
}
12261246
}
12271247
const preauthBudgetKey = resolveRequestClientIp(req, trustedProxies, allowRealIpFallback);
1248+
if (url.pathname === VOICECLAW_REALTIME_PATH) {
1249+
if (!preauthConnectionBudget.acquire(preauthBudgetKey)) {
1250+
writeUpgradeServiceUnavailable(socket, "Too many unauthenticated sockets");
1251+
socket.destroy();
1252+
return;
1253+
}
1254+
let budgetReleased = false;
1255+
const releasePreauthBudget = () => {
1256+
if (budgetReleased) {
1257+
return;
1258+
}
1259+
budgetReleased = true;
1260+
preauthConnectionBudget.release(preauthBudgetKey);
1261+
};
1262+
socket.once("close", releasePreauthBudget);
1263+
try {
1264+
const { handleVoiceClawRealtimeUpgrade } = await getVoiceClawRealtimeUpgradeModule();
1265+
handleVoiceClawRealtimeUpgrade({
1266+
req,
1267+
socket,
1268+
head,
1269+
auth: resolvedAuth,
1270+
config: configSnapshot,
1271+
trustedProxies,
1272+
allowRealIpFallback,
1273+
rateLimiter,
1274+
releasePreauthBudget,
1275+
});
1276+
return;
1277+
} catch (err) {
1278+
socket.off("close", releasePreauthBudget);
1279+
releasePreauthBudget();
1280+
socket.destroy();
1281+
throw new Error("VoiceClaw realtime websocket upgrade failed", { cause: err });
1282+
}
1283+
}
12281284
if (wss.listenerCount("connection") === 0) {
1229-
const responseBody = "Gateway websocket handlers unavailable";
1230-
socket.write(
1231-
"HTTP/1.1 503 Service Unavailable\r\n" +
1232-
"Connection: close\r\n" +
1233-
"Content-Type: text/plain; charset=utf-8\r\n" +
1234-
`Content-Length: ${Buffer.byteLength(responseBody, "utf8")}\r\n` +
1235-
"\r\n" +
1236-
responseBody,
1237-
);
1285+
writeUpgradeServiceUnavailable(socket, "Gateway websocket handlers unavailable");
12381286
socket.destroy();
12391287
return;
12401288
}
12411289
if (!preauthConnectionBudget.acquire(preauthBudgetKey)) {
1242-
const responseBody = "Too many unauthenticated sockets";
1243-
socket.write(
1244-
"HTTP/1.1 503 Service Unavailable\r\n" +
1245-
"Connection: close\r\n" +
1246-
"Content-Type: text/plain; charset=utf-8\r\n" +
1247-
`Content-Length: ${Buffer.byteLength(responseBody, "utf8")}\r\n` +
1248-
"\r\n" +
1249-
responseBody,
1250-
);
1290+
writeUpgradeServiceUnavailable(socket, "Too many unauthenticated sockets");
12511291
socket.destroy();
12521292
return;
12531293
}
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { VoiceClawGeminiLiveAdapter } from "./gemini-live.js";
3+
4+
describe("VoiceClawGeminiLiveAdapter watchdog", () => {
5+
afterEach(() => {
6+
vi.useRealTimers();
7+
});
8+
9+
it("stays paused while async OpenClaw tool work is still running", () => {
10+
vi.useFakeTimers();
11+
const adapter = new VoiceClawGeminiLiveAdapter();
12+
const internals = adapter as unknown as {
13+
watchdogEnabled: boolean;
14+
resetWatchdog: () => void;
15+
sendUpstream: (message: Record<string, unknown>) => void;
16+
};
17+
const sendUpstream = vi.fn();
18+
internals.watchdogEnabled = true;
19+
internals.sendUpstream = sendUpstream;
20+
21+
adapter.beginAsyncToolCall("call-1");
22+
internals.resetWatchdog();
23+
vi.advanceTimersByTime(21_000);
24+
25+
expect(sendUpstream).not.toHaveBeenCalled();
26+
27+
adapter.finishAsyncToolCall("call-1");
28+
vi.advanceTimersByTime(20_000);
29+
30+
expect(sendUpstream).toHaveBeenCalledOnce();
31+
expect(sendUpstream.mock.calls[0][0]).toMatchObject({
32+
realtimeInput: {
33+
text: expect.stringContaining("user has been silent"),
34+
},
35+
});
36+
});
37+
});
38+
39+
describe("VoiceClawGeminiLiveAdapter tool cancellation", () => {
40+
afterEach(() => {
41+
vi.useRealTimers();
42+
});
43+
44+
it("releases the watchdog hold when Gemini cancels an already-acked async tool", () => {
45+
vi.useFakeTimers();
46+
const adapter = new VoiceClawGeminiLiveAdapter();
47+
const events: unknown[] = [];
48+
const sendUpstream = vi.fn();
49+
const internals = adapter as unknown as {
50+
asyncToolCallIds: Set<string>;
51+
handleServerMessage: (message: Record<string, unknown>) => void;
52+
sendToClient: (event: unknown) => void;
53+
sendUpstream: (message: Record<string, unknown>) => void;
54+
watchdogEnabled: boolean;
55+
};
56+
internals.sendToClient = (event) => events.push(event);
57+
internals.sendUpstream = sendUpstream;
58+
internals.watchdogEnabled = true;
59+
60+
adapter.beginAsyncToolCall("call-1");
61+
internals.handleServerMessage({ toolCallCancellation: { ids: ["call-1"] } });
62+
vi.advanceTimersByTime(20_000);
63+
64+
expect(events).toContainEqual({ type: "tool.cancelled", callIds: ["call-1"] });
65+
expect(internals.asyncToolCallIds.size).toBe(0);
66+
expect(sendUpstream).toHaveBeenCalledOnce();
67+
});
68+
69+
it("cancels async OpenClaw tool work when Gemini closes after the working ack", () => {
70+
const adapter = new VoiceClawGeminiLiveAdapter();
71+
const events: unknown[] = [];
72+
const internals = adapter as unknown as {
73+
asyncToolCallIds: Set<string>;
74+
handleUpstreamClose: (code: number) => void;
75+
sendToClient: (event: unknown) => void;
76+
};
77+
internals.sendToClient = (event) => events.push(event);
78+
79+
adapter.beginAsyncToolCall("call-1");
80+
internals.handleUpstreamClose(1000);
81+
82+
expect(events).toContainEqual({ type: "tool.cancelled", callIds: ["call-1"] });
83+
expect(events).toContainEqual({
84+
type: "error",
85+
message: "Gemini Live closed while a tool call was in flight",
86+
code: 502,
87+
});
88+
expect(internals.asyncToolCallIds.size).toBe(0);
89+
});
90+
91+
it("defers goAway rotation until async OpenClaw tool work finishes", () => {
92+
const adapter = new VoiceClawGeminiLiveAdapter();
93+
const reconnect = vi.fn();
94+
const internals = adapter as unknown as {
95+
currentlyResumable: boolean;
96+
handleServerMessage: (message: Record<string, unknown>) => void;
97+
reconnect: (reason: string) => void;
98+
resumptionHandle: string;
99+
rotateAfterToolCalls: boolean;
100+
};
101+
internals.currentlyResumable = true;
102+
internals.resumptionHandle = "resume-1";
103+
internals.reconnect = reconnect;
104+
105+
adapter.beginAsyncToolCall("call-1");
106+
internals.handleServerMessage({ goAway: {} });
107+
108+
expect(reconnect).not.toHaveBeenCalled();
109+
expect(internals.rotateAfterToolCalls).toBe(true);
110+
111+
adapter.finishAsyncToolCall("call-1");
112+
113+
expect(internals.rotateAfterToolCalls).toBe(false);
114+
expect(reconnect).toHaveBeenCalledWith("deferred goAway");
115+
});
116+
117+
it("rotates after goAway when Gemini cancels the deferred async tool", () => {
118+
const adapter = new VoiceClawGeminiLiveAdapter();
119+
const reconnect = vi.fn();
120+
const internals = adapter as unknown as {
121+
currentlyResumable: boolean;
122+
handleServerMessage: (message: Record<string, unknown>) => void;
123+
reconnect: (reason: string) => void;
124+
resumptionHandle: string;
125+
rotateAfterToolCalls: boolean;
126+
};
127+
internals.currentlyResumable = true;
128+
internals.resumptionHandle = "resume-1";
129+
internals.reconnect = reconnect;
130+
131+
adapter.beginAsyncToolCall("call-1");
132+
internals.handleServerMessage({ goAway: {} });
133+
internals.handleServerMessage({ toolCallCancellation: { ids: ["call-1"] } });
134+
135+
expect(internals.rotateAfterToolCalls).toBe(false);
136+
expect(reconnect).toHaveBeenCalledWith("deferred goAway");
137+
});
138+
});

0 commit comments

Comments
 (0)