Skip to content

Commit a02cc5c

Browse files
author
Peter Steinberger
committed
fix(xai): preserve canonical realtime terminal outcomes
1 parent fdcb321 commit a02cc5c

4 files changed

Lines changed: 333 additions & 25 deletions

File tree

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

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export class XaiRealtimeVoiceBridge extends XaiRealtimeVoiceEvents implements Re
111111
if (this.intentionallyClosed) {
112112
return;
113113
}
114-
if (!this.canSubmitToolResult()) {
114+
if (!this.canSubmitInput()) {
115115
if (this.pendingToolResults.length < XAI_REALTIME_MAX_PENDING_TOOL_RESULTS) {
116116
this.pendingToolResults.push({ callId, result, ...(options ? { options } : {}) });
117117
} else {
@@ -469,10 +469,6 @@ export class XaiRealtimeVoiceBridge extends XaiRealtimeVoiceEvents implements Re
469469
ws.send(payload);
470470
}
471471

472-
private canSubmitToolResult(): boolean {
473-
return this.connected && this.sessionConfigured && this.ws?.readyState === WebSocket.OPEN;
474-
}
475-
476472
private canSubmitInput(): boolean {
477473
return this.connected && this.sessionConfigured && this.ws?.readyState === WebSocket.OPEN;
478474
}

‎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: 54 additions & 13 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,
@@ -14,6 +14,7 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
1414
private assistantTranscriptBuffer = "";
1515
private assistantTranscriptFinalized = false;
1616
private inputTranscriptReplacements = new Map<string, string>();
17+
private completedResponseToolItems: XaiRealtimeEvent["item"][] = [];
1718

1819
protected abstract onSessionUpdated(): void;
1920

@@ -38,22 +39,22 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
3839
return;
3940
}
4041
case "conversation.item.created":
41-
case "conversation.item.added": {
42+
case "conversation.item.added":
43+
case "response.output_item.done": {
4244
const item = event.item;
4345
const callId = normalizeOptionalString(item?.call_id);
4446
if (item?.type === "function_call_output" && callId) {
4547
this.pendingToolResultAcks.delete(callId);
4648
return;
4749
}
48-
if (event.type === "conversation.item.created" && item?.type === "function_call") {
49-
// Resumption replays persisted items instead of replaying the original
50-
// response event. Re-emit only calls this bridge did not already deliver.
51-
this.emitToolCallOnce({
52-
itemId: item.id ?? event.item_id,
53-
callId: item.call_id,
54-
name: item.name,
55-
rawArgs: item.arguments,
56-
});
50+
if (event.type === "response.output_item.done") {
51+
// Output items precede their response outcome, so side effects must
52+
// wait until response.done confirms this response succeeded.
53+
if (item?.type === "function_call" && (!item.status || item.status === "completed")) {
54+
this.completedResponseToolItems.push(item);
55+
}
56+
} else if (event.type === "conversation.item.created") {
57+
this.emitCompletedToolCall(item, event);
5758
}
5859
return;
5960
}
@@ -66,6 +67,7 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
6667
this.markQueue = [];
6768
this.lastAssistantItemId = null;
6869
this.responseStartTimestamp = null;
70+
this.completedResponseToolItems = [];
6971
this.resetAssistantTranscript();
7072
return;
7173
case "response.output_audio.delta": {
@@ -128,13 +130,36 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
128130
this.inputTranscriptReplacements.delete(this.inputTranscriptKey(event));
129131
this.config.onError?.(new Error(readXaiRealtimeErrorDetail(event.error)));
130132
return;
131-
case "response.done":
132-
this.flushAssistantTranscript();
133+
case "response.done": {
134+
const status = event.response?.status;
135+
const output = event.response?.output ?? [];
136+
if (status === undefined || status === "completed") {
137+
for (const item of [...output, ...this.completedResponseToolItems]) {
138+
this.emitCompletedToolCall(item, event);
139+
}
140+
}
141+
this.completedResponseToolItems = [];
142+
const terminalTranscript = output
143+
.filter((item) => item.type === "message" && item.role === "assistant")
144+
.flatMap((item) => item.content ?? [])
145+
.map((content) => content.transcript ?? content.text ?? "")
146+
.join("");
147+
this.flushAssistantTranscript(terminalTranscript);
133148
this.responseActive = false;
134149
this.responseCreateInFlight = false;
135150
this.responseCancelInFlight = false;
151+
if (status === "failed" || status === "incomplete") {
152+
const details = event.response?.status_details;
153+
const error = isRecord(details) ? details.error : undefined;
154+
const reason = isRecord(details) ? normalizeOptionalString(details.reason) : undefined;
155+
const message = error
156+
? readXaiRealtimeErrorDetail(error)
157+
: `xAI realtime voice response ${status}${reason ? `: ${reason}` : ""}`;
158+
this.config.onError?.(new Error(message));
159+
}
136160
this.flushPendingResponseCreate();
137161
return;
162+
}
138163
case "response.function_call_arguments.delta": {
139164
const key = event.item_id ?? "unknown";
140165
const existing = this.toolCallBuffers.get(key);
@@ -152,6 +177,8 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
152177
case "response.function_call_arguments.done": {
153178
const key = event.item_id ?? "unknown";
154179
const buffered = this.toolCallBuffers.get(key);
180+
// xAI's documented Function Call Flow requires executing finalized
181+
// arguments immediately so tool results can continue the response.
155182
this.emitToolCallOnce({
156183
itemId: event.item_id,
157184
callId: buffered?.callId || event.call_id,
@@ -170,6 +197,20 @@ export abstract class XaiRealtimeVoiceEvents extends XaiRealtimeVoiceProtocol {
170197

171198
protected resetInputTranscripts(): void {
172199
this.inputTranscriptReplacements.clear();
200+
this.completedResponseToolItems = [];
201+
}
202+
203+
private emitCompletedToolCall(item: XaiRealtimeEvent["item"], event: XaiRealtimeEvent): void {
204+
if (item?.type === "function_call" && (!item.status || item.status === "completed")) {
205+
// Completed items and resumed replay are authoritative; added items can
206+
// still be in progress and must not dispatch incomplete arguments.
207+
this.emitToolCallOnce({
208+
itemId: item.id ?? event.item_id,
209+
callId: item.call_id,
210+
name: item.name,
211+
rawArgs: item.arguments,
212+
});
213+
}
173214
}
174215

175216
private appendAssistantTranscriptDelta(delta: string): void {

0 commit comments

Comments
 (0)