Skip to content

Commit 80c187b

Browse files
vincentkocPeter Steinberger
andauthored
fix(xai): preserve terminal realtime voice outcomes (#117600)
* fix(xai): preserve canonical realtime terminal outcomes * fix(xai): bound terminal tool outcome state * test(xai): bound realtime outcome harness payloads --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent c6bad23 commit 80c187b

4 files changed

Lines changed: 290 additions & 24 deletions

File tree

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

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ export class XaiRealtimeVoiceBridge extends XaiRealtimeVoiceEvents implements Re
124124
if (this.lifecycle.phase() === "terminal") {
125125
return;
126126
}
127-
if (!this.canSubmitToolResult()) {
127+
if (!this.canSubmitInput()) {
128128
if (this.pendingToolResults.length < XAI_REALTIME_MAX_PENDING_TOOL_RESULTS) {
129129
this.pendingToolResults.push({ callId, result, ...(options ? { options } : {}) });
130130
} else {
@@ -538,10 +538,6 @@ export class XaiRealtimeVoiceBridge extends XaiRealtimeVoiceEvents implements Re
538538
ws.send(payload);
539539
}
540540

541-
private canSubmitToolResult(): boolean {
542-
return this.isConnected();
543-
}
544-
545541
private canSubmitInput(): boolean {
546542
return this.isConnected();
547543
}

‎extensions/xai/realtime-voice-config.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,17 @@ export type XaiRealtimeVoiceBridgeConfig = RealtimeVoiceBridgeCreateRequest & {
4444
resolveApiKey?: () => Promise<string>;
4545
};
4646

47+
type XaiRealtimeResponseItem = {
48+
id?: string;
49+
type?: string;
50+
status?: "completed" | "incomplete" | "in_progress";
51+
role?: string;
52+
call_id?: string;
53+
name?: string;
54+
arguments?: string;
55+
content?: Array<{ type?: string; text?: string; transcript?: string }>;
56+
};
57+
4758
export type XaiRealtimeEvent = {
4859
type: string;
4960
delta?: string;
@@ -59,15 +70,10 @@ export type XaiRealtimeEvent = {
5970
id?: string;
6071
status?: string;
6172
status_details?: unknown;
73+
output?: XaiRealtimeResponseItem[];
6274
};
6375
conversation?: { id?: string };
64-
item?: {
65-
id?: string;
66-
type?: string;
67-
call_id?: string;
68-
name?: string;
69-
arguments?: string;
70-
};
76+
item?: XaiRealtimeResponseItem;
7177
error?: unknown;
7278
};
7379

‎extensions/xai/realtime-voice-events.ts‎

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { canonicalizeBase64 } from "openclaw/plugin-sdk/media-runtime";
2-
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2+
import { isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
33
import {
44
XAI_REALTIME_ACTIVE_RESPONSE_ERROR_PREFIX,
55
XAI_REALTIME_NO_ACTIVE_RESPONSE_CANCEL_ERROR,
@@ -50,15 +50,8 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
5050
this.pendingToolResultAcks.delete(callId);
5151
return;
5252
}
53-
if (event.type === "conversation.item.created" && item?.type === "function_call") {
54-
// Resumption replays persisted items instead of replaying the original
55-
// response event. Re-emit only calls this bridge did not already deliver.
56-
this.emitToolCallOnce({
57-
itemId: item.id ?? event.item_id,
58-
callId: item.call_id,
59-
name: item.name,
60-
rawArgs: item.arguments,
61-
});
53+
if (event.type === "conversation.item.created") {
54+
this.emitCompletedToolCall(item, event);
6255
}
6356
return;
6457
}
@@ -133,13 +126,35 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
133126
this.inputTranscriptReplacements.delete(this.inputTranscriptKey(event));
134127
this.config.onError?.(new Error(readXaiRealtimeErrorDetail(event.error)));
135128
return;
136-
case "response.done":
137-
this.flushAssistantTranscript();
129+
case "response.done": {
130+
const status = event.response?.status;
131+
const output = event.response?.output ?? [];
132+
if (status === undefined || status === "completed") {
133+
for (const item of output) {
134+
this.emitCompletedToolCall(item, event);
135+
}
136+
}
137+
const terminalTranscript = output
138+
.filter((item) => item.type === "message" && item.role === "assistant")
139+
.flatMap((item) => item.content ?? [])
140+
.map((content) => content.transcript ?? content.text ?? "")
141+
.join("");
142+
this.flushAssistantTranscript(terminalTranscript);
138143
this.responseActive = false;
139144
this.responseCreateInFlight = false;
140145
this.responseCancelInFlight = false;
146+
if (status === "failed" || status === "incomplete") {
147+
const details = event.response?.status_details;
148+
const error = isRecord(details) ? details.error : undefined;
149+
const reason = isRecord(details) ? normalizeOptionalString(details.reason) : undefined;
150+
const message = error
151+
? readXaiRealtimeErrorDetail(error)
152+
: `xAI realtime voice response ${status}${reason ? `: ${reason}` : ""}`;
153+
this.config.onError?.(new Error(message));
154+
}
141155
this.flushPendingResponseCreate();
142156
return;
157+
}
143158
case "response.function_call_arguments.delta": {
144159
const key = event.item_id ?? "unknown";
145160
const existing = this.toolCallBuffers.get(key);
@@ -157,6 +172,8 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
157172
case "response.function_call_arguments.done": {
158173
const key = event.item_id ?? "unknown";
159174
const buffered = this.toolCallBuffers.get(key);
175+
// xAI's documented Function Call Flow requires executing finalized
176+
// arguments immediately so tool results can continue the response.
160177
this.emitToolCallOnce({
161178
itemId: event.item_id,
162179
callId: buffered?.callId || event.call_id,
@@ -177,6 +194,19 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
177194
this.inputTranscriptReplacements.clear();
178195
}
179196

197+
private emitCompletedToolCall(item: XaiRealtimeEvent["item"], event: XaiRealtimeEvent): void {
198+
if (item?.type === "function_call" && (!item.status || item.status === "completed")) {
199+
// Completed items and resumed replay are authoritative; added items can
200+
// still be in progress and must not dispatch incomplete arguments.
201+
this.emitToolCallOnce({
202+
itemId: item.id ?? event.item_id,
203+
callId: item.call_id,
204+
name: item.name,
205+
rawArgs: item.arguments,
206+
});
207+
}
208+
}
209+
180210
private appendAssistantTranscriptDelta(delta: string): void {
181211
if (this.assistantTranscriptFinalized) {
182212
this.assistantTranscriptBuffer = "";
Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
import { createServer } from "node:http";
2+
import type { AddressInfo } from "node:net";
3+
import { describe, expect, it } from "vitest";
4+
import type WebSocket from "ws";
5+
import { WebSocketServer } from "ws";
6+
import { buildXaiRealtimeVoiceProvider } from "./realtime-voice-provider.js";
7+
8+
type RealtimeOutcome = {
9+
errors: string[];
10+
transcripts: Array<{ speaker: string; text: string; final: boolean }>;
11+
tools: Array<{ itemId: string; callId: string; name: string; args: unknown }>;
12+
};
13+
14+
async function captureRealtimeOutcome(
15+
eventInput: Record<string, unknown> | Record<string, unknown>[],
16+
): Promise<RealtimeOutcome> {
17+
const events = Array.isArray(eventInput) ? eventInput : [eventInput];
18+
const outcome: RealtimeOutcome = { errors: [], transcripts: [], tools: [] };
19+
let markServerEventHandled: () => void = () => {};
20+
const serverEventHandled = new Promise<void>((resolve) => {
21+
markServerEventHandled = resolve;
22+
});
23+
const server = createServer();
24+
const sockets = new Set<WebSocket>();
25+
const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });
26+
server.on("upgrade", (request, socket, head) => {
27+
wss.handleUpgrade(request, socket, head, (ws) => {
28+
sockets.add(ws);
29+
ws.on("message", (message) => {
30+
if (JSON.parse(Buffer.from(message as Buffer).toString("utf8")).type !== "session.update") {
31+
return;
32+
}
33+
ws.send(JSON.stringify({ type: "session.updated" }));
34+
ws.send(JSON.stringify({ type: "response.created", response: { id: "response_1" } }));
35+
for (const event of events) {
36+
ws.send(JSON.stringify(event));
37+
}
38+
});
39+
});
40+
});
41+
await new Promise<void>((resolve) => {
42+
server.listen(0, "127.0.0.1", resolve);
43+
});
44+
const port = (server.address() as AddressInfo).port;
45+
const bridge = buildXaiRealtimeVoiceProvider().createBridge({
46+
providerConfig: { apiKey: "fixture-value", baseUrl: `http://127.0.0.1:${port}/v1` },
47+
onAudio() {},
48+
onClearAudio() {},
49+
onError: (error) => outcome.errors.push(error.message),
50+
onTranscript: (speaker, text, final) => outcome.transcripts.push({ speaker, text, final }),
51+
onToolCall: (tool) => outcome.tools.push(tool),
52+
onEvent: (observed) => {
53+
if (observed.direction === "server" && observed.type === events.at(-1)?.type) {
54+
markServerEventHandled();
55+
}
56+
},
57+
});
58+
59+
try {
60+
await bridge.connect();
61+
await serverEventHandled;
62+
return outcome;
63+
} finally {
64+
bridge.close();
65+
for (const socket of sockets) {
66+
socket.terminate();
67+
}
68+
await new Promise<void>((resolve) => {
69+
wss.close(() => resolve());
70+
});
71+
await new Promise<void>((resolve) => {
72+
server.close(() => resolve());
73+
});
74+
}
75+
}
76+
77+
const completedTool = {
78+
id: "item_tool",
79+
type: "function_call",
80+
call_id: "call_tool",
81+
name: "lookup_weather",
82+
arguments: JSON.stringify({ city: "Paris" }),
83+
};
84+
const expectedTool = {
85+
itemId: "item_tool",
86+
callId: "call_tool",
87+
name: "lookup_weather",
88+
args: { city: "Paris" },
89+
};
90+
91+
describe("xAI realtime terminal event ownership", () => {
92+
it.each([
93+
{
94+
name: "preserves assistant transcripts carried only by terminal output",
95+
event: {
96+
type: "response.done",
97+
response: {
98+
status: "completed",
99+
output: [
100+
{
101+
type: "message",
102+
role: "assistant",
103+
content: [{ type: "output_audio", transcript: "terminal answer" }],
104+
},
105+
],
106+
},
107+
},
108+
expected: {
109+
errors: [],
110+
transcripts: [{ speaker: "assistant", text: "terminal answer", final: true }],
111+
tools: [],
112+
},
113+
},
114+
{
115+
name: "surfaces failed responses with provider error details",
116+
event: {
117+
type: "response.done",
118+
response: { status: "failed", status_details: { error: { code: "rate_limit_exceeded" } } },
119+
},
120+
expected: { errors: ["rate_limit_exceeded"], transcripts: [], tools: [] },
121+
},
122+
{
123+
name: "surfaces incomplete responses with their authoritative reason",
124+
event: {
125+
type: "response.done",
126+
response: { status: "incomplete", status_details: { reason: "max_output_tokens" } },
127+
},
128+
expected: {
129+
errors: ["xAI realtime voice response incomplete: max_output_tokens"],
130+
transcripts: [],
131+
tools: [],
132+
},
133+
},
134+
{
135+
name: "does not mistake intentional cancellation for a provider failure",
136+
event: {
137+
type: "response.done",
138+
response: { status: "cancelled", status_details: { reason: "client_cancelled" } },
139+
},
140+
expected: { errors: [], transcripts: [], tools: [] },
141+
},
142+
{
143+
name: "ignores output-item events and waits for canonical terminal output",
144+
event: { type: "response.output_item.done", item: completedTool },
145+
expected: { errors: [], transcripts: [], tools: [] },
146+
},
147+
{
148+
name: "retains immediate completed replay delivery for resumed conversations",
149+
event: { type: "conversation.item.created", item: completedTool },
150+
expected: { errors: [], transcripts: [], tools: [expectedTool] },
151+
},
152+
{
153+
name: "retains immediate authoritative function-call argument completion",
154+
event: {
155+
type: "response.function_call_arguments.done",
156+
item_id: completedTool.id,
157+
call_id: completedTool.call_id,
158+
name: completedTool.name,
159+
arguments: completedTool.arguments,
160+
},
161+
expected: { errors: [], transcripts: [], tools: [expectedTool] },
162+
},
163+
{
164+
name: "preserves required streamed-call timing when the response later fails",
165+
event: [
166+
{
167+
type: "response.function_call_arguments.done",
168+
item_id: completedTool.id,
169+
call_id: completedTool.call_id,
170+
name: completedTool.name,
171+
arguments: completedTool.arguments,
172+
},
173+
{ type: "response.done", response: { status: "failed", output: [] } },
174+
],
175+
expected: {
176+
errors: ["xAI realtime voice response failed"],
177+
transcripts: [],
178+
tools: [expectedTool],
179+
},
180+
},
181+
{
182+
name: "does not dispatch incomplete replayed function-call items",
183+
event: {
184+
type: "conversation.item.created",
185+
item: { ...completedTool, status: "incomplete" },
186+
},
187+
expected: { errors: [], transcripts: [], tools: [] },
188+
},
189+
{
190+
name: "recovers completed tool calls from terminal response output",
191+
event: {
192+
type: "response.done",
193+
response: { status: "completed", output: [completedTool] },
194+
},
195+
expected: { errors: [], transcripts: [], tools: [expectedTool] },
196+
},
197+
{
198+
name: "deduplicates immediate tool delivery against terminal output",
199+
event: [
200+
{
201+
type: "response.function_call_arguments.done",
202+
item_id: completedTool.id,
203+
call_id: completedTool.call_id,
204+
name: completedTool.name,
205+
arguments: completedTool.arguments,
206+
},
207+
{ type: "response.done", response: { status: "completed", output: [completedTool] } },
208+
],
209+
expected: { errors: [], transcripts: [], tools: [expectedTool] },
210+
},
211+
...["failed", "incomplete", "cancelled"].map((status) => ({
212+
name: `does not recover terminal-output tool calls from a ${status} response`,
213+
event: {
214+
type: "response.done",
215+
response: { status, output: [completedTool] },
216+
},
217+
expected: {
218+
errors: status === "cancelled" ? [] : [`xAI realtime voice response ${status}`],
219+
transcripts: [],
220+
tools: [],
221+
},
222+
})),
223+
{
224+
name: "does not dispatch incomplete items from a completed terminal response",
225+
event: {
226+
type: "response.done",
227+
response: { status: "completed", output: [{ ...completedTool, status: "incomplete" }] },
228+
},
229+
expected: { errors: [], transcripts: [], tools: [] },
230+
},
231+
])("$name", async ({ event, expected }) => {
232+
expect(await captureRealtimeOutcome(event)).toEqual(expected);
233+
});
234+
});

0 commit comments

Comments
 (0)