Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(voice): follow a Live update by its metadata instead of retelling it
LeoXingaa320054e098
diff --git a/apps/voice-runtime/src/live-session.ts b/apps/voice-runtime/src/live-session.tsindex 0b2eedbd..bb77a962 100644--- a/apps/voice-runtime/src/live-session.ts+++ b/apps/voice-runtime/src/live-session.ts@@ -38,7 +38,14 @@ export type LiveEvent =}/** The model began a reply to the user (not an update). */| { type: "response_started" }- | { type: "response_finished"; canceled: boolean }+ /** The provider started a response for the update tell() named. */+ | { type: "update_accepted"; id: string }+ | {+ type: "response_finished";+ canceled: boolean;+ /** The update the response said, when it said one. */+ updateId?: string;+ }/** detail is the provider's own reason, bounded, for the log. */| { type: "provider_error"; code: string; detail: string };@@ -60,7 +67,14 @@ export interface LiveSession {* of the call; with allowTools it may first call tools, and the response* after their results is still the update. Its words arrive as update text.*/- tell(cue: string, allowTools?: boolean): void;+ tell(cue: string, allowTools: boolean, id: string): void;+ /**+ * Asks again for the update `id` without telling its cue again, when its+ * response ended without a word.+ */+ repeatUpdate(id: string, allowTools: boolean): void;+ /** Ends a session that stopped answering, as a transient loss. */+ abandon(code: string): void;/** Adds application context without generating speech. */note(text: string): void;/**diff --git a/apps/voice-runtime/src/live-tasks.ts b/apps/voice-runtime/src/live-tasks.tsindex bb5c3c54..7c315c2e 100644--- a/apps/voice-runtime/src/live-tasks.ts+++ b/apps/voice-runtime/src/live-tasks.ts@@ -11,8 +11,6 @@ export interface TaskUpdate {kind: "report" | "failed" | "approval" | "alert" | "browser";/** What to tell, full text: the reports or the failure. */replies: string[];- /** Times it was told without the provider starting it. */- attempts?: number;}interface Tracked {diff --git a/apps/voice-runtime/src/live-worker.test.ts b/apps/voice-runtime/src/live-worker.test.tsindex c545fd88..cd08c707 100644--- a/apps/voice-runtime/src/live-worker.test.ts+++ b/apps/voice-runtime/src/live-worker.test.ts@@ -142,6 +142,10 @@ class FakeSession {respond = vi.fn();truncate = vi.fn();tell = vi.fn();+ repeatUpdate = vi.fn();+ abandon = vi.fn((code: string) =>+ this.fail(new LiveSessionError(code, true)),+ );note = vi.fn();sendToolResults = vi.fn();setSpeed = vi.fn((speed: number) => speed <= 1.5);@@ -1116,10 +1120,12 @@ describe("LiveVoiceWorker", () => {await test.shutdown();});- it("reconnects once on a transient loss and fails the session after that", async () => {+ it("reconnects on a transient loss three times and fails the session after that", async () => {const test = await harness();- test.session().fail(new LiveSessionError("live_socket_closed", true));- await vi.waitFor(() => expect(test.sessions).toHaveLength(2));+ for (const count of [2, 3, 4]) {+ test.session().fail(new LiveSessionError("live_socket_closed", true));+ await vi.waitFor(() => expect(test.sessions).toHaveLength(count));+ }test.session().fail(new LiveSessionError("live_socket_closed", true));await vi.waitFor(() =>expect(test.ofType("session_failure")).toEqual([@@ -1406,17 +1412,66 @@ describe("LiveVoiceWorker background work", () => {await test.shutdown();});- it("tells an update again when the provider never started it, then gives it up", async () => {+ it("replaces a session that never took up an update and tells it there", async () => {const test = await harness();test.setAlerts([{ alert_id: "a1", text: "Lisa @you" }]);- await vi.waitFor(- () => expect(test.session().tell).toHaveBeenCalledTimes(3),- {- timeout: 3_000,- },+ await vi.waitFor(() => expect(test.session().tell).toHaveBeenCalledOnce());+ const first = test.session();+ // The cue is never taken up: telling it again on the same connection+ // would only queue behind it.+ await vi.waitFor(() =>+ expect(first.abandon).toHaveBeenCalledWith("live_update_stalled"),+ );+ expect(first.tell).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(test.sessions).toHaveLength(2));+ await vi.waitFor(() => expect(test.session().tell).toHaveBeenCalledOnce());+ await test.shutdown();+ });++ it("asks again for an update whose response said nothing, then gives it up", async () => {+ const test = await harness();+ test.setAlerts([{ alert_id: "a1", text: "Lisa @you" }]);+ await vi.waitFor(() => expect(test.session().tell).toHaveBeenCalledOnce());+ const id = test.session().tell.mock.calls[0]![2] as string;+ for (const repeats of [1, 2]) {+ test+ .session()+ .emit(+ { type: "update_accepted", id },+ { type: "response_finished", canceled: false, updateId: id },+ );+ await vi.waitFor(() =>+ expect(test.session().repeatUpdate).toHaveBeenCalledTimes(repeats),+ );+ }+ expect(test.session().repeatUpdate).toHaveBeenCalledWith(id, false);+ test+ .session()+ .emit(+ { type: "update_accepted", id },+ { type: "response_finished", canceled: false, updateId: id },+ );+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(test.session().repeatUpdate).toHaveBeenCalledTimes(2);+ expect(test.session().tell).toHaveBeenCalledOnce();+ expect(test.session().abandon).not.toHaveBeenCalled();+ await test.shutdown();+ });++ it("cancels an update's response that started but says nothing", async () => {+ const test = await harness();+ test.setAlerts([{ alert_id: "a1", text: "Lisa @you" }]);+ await vi.waitFor(() => expect(test.session().tell).toHaveBeenCalledOnce());+ const id = test.session().tell.mock.calls[0]![2] as string;+ test.session().emit({ type: "update_accepted", id });+ await vi.waitFor(() => expect(test.session().cancel).toHaveBeenCalled());+ test+ .session()+ .emit({ type: "response_finished", canceled: true, updateId: id });+ await vi.waitFor(() =>+ expect(test.session().repeatUpdate).toHaveBeenCalledOnce(),);- await new Promise((resolve) => setTimeout(resolve, 500));- expect(test.session().tell).toHaveBeenCalledTimes(3);+ expect(test.session().abandon).not.toHaveBeenCalled();await test.shutdown();});diff --git a/apps/voice-runtime/src/live-worker.ts b/apps/voice-runtime/src/live-worker.tsindex 4fb6af2c..f6f6aad7 100644--- a/apps/voice-runtime/src/live-worker.ts+++ b/apps/voice-runtime/src/live-worker.ts@@ -60,9 +60,15 @@ const maximumPendingToolCalls = 16;const maximumPendingNotes = 256;const maximumPendingNoteChars = 512 * 1024;const maximumPendingUpdates = 64;+/**+ * How long each step of an update may take: the provider taking up its cue,+ * then the response saying its first word, then a cancel coming back.+ */const updateStartTimeoutMs = 15_000;-/** An update is tried this many times before it is given up. */+/** An update is asked for this many times before it is given up. */const maxUpdateAttempts = 3;+/** A lost provider session is replaced at most this many times in a call. */+const maxReconnects = 3;const inputFirstFrameTimeoutMs = 10_000;const retryMs = 300;/**@@ -186,6 +192,12 @@ interface Speech {speechId: string;updates: TaskUpdate[];turnId: string;+ allowTools: boolean;+ attempts: number;+ /** The provider started a response for it. */+ accepted: boolean;+ /** A response that said nothing is being canceled. */+ canceling: boolean;}interface Reply {@@ -432,7 +444,7 @@ export class LiveVoiceWorker {private startedAt = Date.now();private timed = new Set<string>();private markSessionReady!: () => void;- private reconnected = false;+ private reconnects = 0;private failed = false;private stopped = false;private muted = false;@@ -703,21 +715,21 @@ export class LiveVoiceWorker {} catch (error) {if (this.stopped) return;if (- this.reconnected ||+ this.reconnects >= maxReconnects ||!(error instanceof LiveSessionError) ||!error.transient) {await this.fail(error);return;}- this.reconnected = true;+ this.reconnects += 1;log().warn({voiceSessionId: this.voiceSessionId,failureCode: error.code,detail: error.detail,},- "Voice live provider session lost; reconnecting once",+ "Voice live provider session lost; reconnecting",);// In-flight replies belong to the lost provider session.this.interrupt(true);@@ -871,15 +883,23 @@ export class LiveVoiceWorker {);return;}+ case "update_accepted": {+ const speech = this.pendingSpeech;+ if (speech?.speechId !== event.id || speech.accepted) return;+ speech.accepted = true;+ this.awaitUpdate(speech);+ return;+ }case "response_finished":if (this.pendingSpeech) {+ const speech = this.pendingSpeech;if (event.canceled && this.pendingSpeechInterrupted) {- const speech = this.pendingSpeech;this.clearPendingSpeech();this.queuedUpdates.unshift(...speech.updates);this.flushNotes();this.flushUpdates();- }+ } else if (event.updateId === speech.speechId)+ this.repeatUpdate(speech);return;}if (this.reply) this.finishReply(event.canceled);@@ -1883,6 +1903,10 @@ export class LiveVoiceWorker {speechId: `update_${randomUUID()}`,updates,turnId: this.latestTurn?.id ?? "lt_update",+ allowTools: updates.some((update) => update.kind === "report"),+ attempts: 1,+ accepted: false,+ canceling: false,};this.say(speech, at);}@@ -1890,25 +1914,7 @@ export class LiveVoiceWorker {private say(speech: Speech, at: UpdateEntry) {this.pendingSpeech = speech;this.pendingSpeechInterrupted = false;- this.speechStartTimer = setTimeout(() => {- // An update the provider never started is tried again later; only- // one that keeps failing is given up, never the whole live session.- const retry = speech.updates.filter(- (update) =>- (update.attempts = (update.attempts ?? 0) + 1) < maxUpdateAttempts,- );- log().warn(- {- voiceSessionId: this.voiceSessionId,- interrupted: this.pendingSpeechInterrupted,- dropped: speech.updates.length - retry.length,- },- "Voice live update never started",- );- this.clearPendingSpeech();- this.queuedUpdates.unshift(...retry);- this.flushUpdates();- }, this.options.updateStartTimeoutMs ?? updateStartTimeoutMs);+ this.awaitUpdate(speech);log().info({voiceSessionId: this.voiceSessionId,@@ -1923,10 +1929,62 @@ export class LiveVoiceWorker {at,this.latestTurn?.heard ?? this.latestTurn?.text,),- speech.updates.some((update) => update.kind === "report"),+ speech.allowTools,+ speech.speechId,);}+ /**+ * Watches the update's next step. A cue the provider never took up means+ * the connection stalled: telling it again there would only queue behind+ * the first and cut it off when both arrive, so the session is replaced.+ * A response that started but says nothing is canceled and asked for again.+ */+ private awaitUpdate(speech: Speech) {+ clearTimeout(this.speechStartTimer);+ this.speechStartTimer = setTimeout(() => {+ if (this.pendingSpeech !== speech) return;+ const stage = speech.canceling+ ? "cancel"+ : speech.accepted+ ? "silent"+ : "unacknowledged";+ log().warn(+ { voiceSessionId: this.voiceSessionId, stage },+ "Voice live update stalled",+ );+ if (stage === "silent") {+ speech.canceling = true;+ this.awaitUpdate(speech);+ this.session?.cancel();+ } else this.session?.abandon("live_update_stalled");+ }, this.options.updateStartTimeoutMs ?? updateStartTimeoutMs);+ }++ /**+ * Asks again for an update whose response ended without a word; its cue+ * is already in the conversation, so it is not told twice.+ */+ private repeatUpdate(speech: Speech) {+ speech.attempts += 1;+ if (speech.attempts > maxUpdateAttempts) {+ log().warn(+ {+ voiceSessionId: this.voiceSessionId,+ updates: speech.updates.map((update) => update.kind),+ },+ "Voice live update given up",+ );+ this.clearPendingSpeech();+ this.flushUpdates();+ return;+ }+ speech.accepted = false;+ speech.canceling = false;+ this.awaitUpdate(speech);+ this.session?.repeatUpdate(speech.speechId, speech.allowTools);+ }+private clearPendingSpeech() {clearTimeout(this.speechStartTimer);this.pendingSpeech = undefined;diff --git a/apps/voice-runtime/src/xai-live.test.ts b/apps/voice-runtime/src/xai-live.test.tsindex fe78d172..bcc588d0 100644--- a/apps/voice-runtime/src/xai-live.test.ts+++ b/apps/voice-runtime/src/xai-live.test.ts@@ -91,6 +91,9 @@ const open = (history,});+/** The metadata an update's response.create carries, as xAI echoes it. */+const told = (id: string, tools = "auto") => ({ update_id: id, tools });+async function collect(session: XaiLiveSession, count: number) {const events: LiveEvent[] = [];for await (const event of session.events()) {@@ -558,19 +561,26 @@ describe("XaiLiveSession", () => {it("never runs a call an update without tools wrote as words", async () => {const provider = await fakeProvider();const session = await open(provider.url);- session.tell("A result arrived.");- const events = collect(session, 2);+ session.tell("A result arrived.", false, "u1");+ const events = collect(session, 3);provider.emit(- { type: "response.created", response: { id: "r1" } },+ {+ type: "response.created",+ response: { id: "r1", metadata: told("u1", "none") },+ },{type: "response.output_audio_transcript.delta",delta: "By the way<tool_call>lookup</tool_call>",},- { type: "response.done", response: { status: "completed" } },+ {+ type: "response.done",+ response: { status: "completed", metadata: told("u1", "none") },+ },);expect(await events).toEqual([+ { type: "update_accepted", id: "u1" },{ type: "text_delta", text: "By the way", update: true },- { type: "response_finished", canceled: false },+ { type: "response_finished", canceled: false, updateId: "u1" },]);await session.close();});@@ -578,10 +588,13 @@ describe("XaiLiveSession", () => {it("answers an update's tool round as the same update", async () => {const provider = await fakeProvider();const session = await open(provider.url);- session.tell("A report arrived.", true);- const first = collect(session, 2);+ session.tell("A report arrived.", true, "u1");+ const first = collect(session, 3);provider.emit(- { type: "response.created", response: { id: "r1" } },+ {+ type: "response.created",+ response: { id: "r1", metadata: told("u1") },+ },{type: "response.function_call_arguments.done",call_id: "c1",@@ -591,23 +604,31 @@ describe("XaiLiveSession", () => {{ type: "response.done", response: { status: "completed" } },);expect(await first).toEqual([+ { type: "update_accepted", id: "u1" },{type: "function_calls",update: true,calls: [{ callId: "c1", name: "lookup", arguments: "{}" }],},- { type: "response_finished", canceled: false },+ { type: "response_finished", canceled: false, updateId: "u1" },]);session.sendToolResults([{ callId: "c1", output: "ok" }]);await waitForSent(provider.sent, 5);- expect(provider.sent.at(-1)).toEqual({ type: "response.create" });- const second = collect(session, 1);+ // The response after the results speaks for the update, not a turn.+ expect(provider.sent.at(-1)).toEqual({+ type: "response.create",+ response: { tool_choice: "auto", metadata: told("u1") },+ });+ const second = collect(session, 2);provider.emit(- { type: "response.created", response: { id: "r2" } },+ {+ type: "response.created",+ response: { id: "r2", metadata: told("u1") },+ },{ type: "response.output_audio_transcript.delta", delta: "All checked." },);- // The response after the results speaks for the update, not a turn.expect(await second).toEqual([+ { type: "update_accepted", id: "u1" },{ type: "text_delta", text: "All checked.", update: true },]);await session.close();@@ -703,6 +724,42 @@ describe("XaiLiveSession", () => {await session.close();});+ it("holds an update told while a reply is under way until it ends", async () => {+ const provider = await fakeProvider();+ const session = await open(provider.url);+ const started = collect(session, 1);+ provider.emit({ type: "response.created", response: { id: "r1" } });+ expect(await started).toEqual([{ type: "response_started" }]);+ // A new item with a response request would cancel the reply under way.+ session.tell("A result arrived.", false, "u1");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(provider.sent).toHaveLength(1);+ provider.emit({+ type: "response.done",+ response: { id: "r1", status: "completed" },+ });+ await waitForSent(provider.sent, 3);+ expect(provider.sent.slice(1).map((event) => event.type)).toEqual([+ "conversation.item.create",+ "response.create",+ ]);+ await session.close();+ });++ it("asks again for an update without telling its cue twice", async () => {+ const provider = await fakeProvider();+ const session = await open(provider.url);+ session.repeatUpdate("u1", true);+ await waitForSent(provider.sent, 2);+ expect(provider.sent.slice(1)).toEqual([+ {+ type: "response.create",+ response: { tool_choice: "auto", metadata: told("u1") },+ },+ ]);+ await session.close();+ });+it("asks for a reply when server VAD ended a turn without one", async () => {const provider = await fakeProvider();const session = await open(provider.url);@@ -715,7 +772,7 @@ describe("XaiLiveSession", () => {it("tells an update in the model's own words, from a system note and without tools", async () => {const provider = await fakeProvider();const session = await open(provider.url);- session.tell("A result arrived.");+ session.tell("A result arrived.", false, "u1");await waitForSent(provider.sent, 3);expect(provider.sent.slice(1, 3)).toEqual([{@@ -726,16 +783,23 @@ describe("XaiLiveSession", () => {content: [{ type: "input_text", text: "[system] A result arrived." }],},},- { type: "response.create", response: { tool_choice: "none" } },+ {+ type: "response.create",+ response: { tool_choice: "none", metadata: told("u1", "none") },+ },]);- const events = collect(session, 2);+ const events = collect(session, 3);provider.emit(- { type: "response.created", response: { id: "r1" } },+ {+ type: "response.created",+ response: { id: "r1", metadata: told("u1", "none") },+ },// Words can precede the audio; they still belong to the update.{ type: "response.output_audio_transcript.delta", delta: "By the way" },{ type: "response.output_audio.delta", delta: pcmBase64(5) },);expect(await events).toEqual([+ { type: "update_accepted", id: "u1" },{ type: "text_delta", text: "By the way", update: true },{ type: "audio_started", update: true },]);@@ -774,21 +838,28 @@ describe("XaiLiveSession", () => {{ type: "response_finished", canceled: false },]);// A report arrives: its answer is asked for, so it is never canceled.- session.tell("A task finished.");+ session.tell("A task finished.", true, "u1");await waitForSent(provider.sent, 3);- const told = collect(session, 2);+ const said = collect(session, 3);provider.emit(- { type: "response.created", response: { id: "r2" } },+ {+ type: "response.created",+ response: { id: "r2", metadata: told("u1") },+ },{type: "response.output_audio_transcript.delta",response_id: "r2",delta: "Done.",},- { type: "response.done", response: { id: "r2", status: "completed" } },+ {+ type: "response.done",+ response: { id: "r2", status: "completed", metadata: told("u1") },+ },);- expect(await told).toEqual([+ expect(await said).toEqual([+ { type: "update_accepted", id: "u1" },{ type: "text_delta", text: "Done.", update: true },- { type: "response_finished", canceled: false },+ { type: "response_finished", canceled: false, updateId: "u1" },]);// The user's next words get an answer of their own, not one taken for// the report.diff --git a/apps/voice-runtime/src/xai-live.ts b/apps/voice-runtime/src/xai-live.tsindex 6c217698..57275c39 100644--- a/apps/voice-runtime/src/xai-live.ts+++ b/apps/voice-runtime/src/xai-live.ts@@ -193,10 +193,18 @@ export function textCall(return { name: tool.name, arguments: JSON.stringify(args) };}+/** A response asked for an update: tell()'s, or one after its tool results. */+interface UpdateRequest {+ id: string;+ tools: boolean;+}+interface Response {id: string;/** An update composed with tell(). */update: boolean;+ /** The update it says, from its metadata. */+ updateId?: string;/** Whether it may call tools; an update said with tell() may not. */tools: boolean;audioStarted: boolean;@@ -230,15 +238,12 @@ export class XaiLiveSession implements LiveSession {private muted = false;private audioCarry = Buffer.alloc(0);private response?: Response;- /**- * Responses the server creates for tell() calls, and for the results of- * their tool calls, oldest first: whether each may call tools.- */- private readonly pendingUpdates: boolean[] = [];- /** Calls an update made; the response to their results is the update too. */- private readonly updateCalls = new Set<string>();- /** The round whose results are coming back holds an update's calls. */- private updateRound = false;+ /** Calls an update made, by call ID: the update the next response says. */+ private readonly updateCalls = new Map<string, string>();+ /** The update whose calls' results are coming back. */+ private updateRound?: string;+ /** A tell() that waits for the response under way to end. */+ private waitingTell?: { cue: string; update: UpdateRequest };/** The session's tools by worker name, for calls written as words. */private tools = new Map<string, LiveTool>();/** Calls the model wrote as words, by call ID: their worker tool names. */@@ -250,6 +255,8 @@ export class XaiLiveSession implements LiveSession {/** Calls handed to the worker whose outputs have not come back yet. */private readonly pendingCalls = new Set<string>();private responseWanted = false;+ /** The update the wanted response says, if any. */+ private wantedUpdate?: UpdateRequest;/** Input items whose transcript the worker already received as final. */private readonly completedInputs = new Set<string>();private readonly inputTexts = new Map<string, string>();@@ -482,9 +489,28 @@ export class XaiLiveSession implements LiveSession {/*** The cue joins the conversation right before the reply as a marked user* item: as response instructions or a system item, Grok answered the- * latest user turn again instead. It is never saved or shown.+ * latest user turn again instead. It is never saved or shown. A new item+ * with a response request cancels the response under way, so a cue told+ * meanwhile waits for it to end.*/- tell(cue: string, allowTools = false) {+ tell(cue: string, allowTools: boolean, id: string) {+ const update = { id, tools: allowTools };+ if (this.response) this.waitingTell = { cue, update };+ else this.sendTell(cue, update);+ }++ /** Asks again for an update whose cue the model already has. */+ repeatUpdate(id: string, allowTools: boolean) {+ this.requestResponse({ id, tools: allowTools });+ }++ /** Gives the session up as lost, so the worker connects a new one. */+ abandon(code: string) {+ this.fail(code, true);+ this.socket.terminate();+ }++ private sendTell(cue: string, update: UpdateRequest) {this.send({type: "conversation.item.create",item: {@@ -493,11 +519,7 @@ export class XaiLiveSession implements LiveSession {content: [{ type: "input_text", text: `[system] ${cue}` }],},});- this.pendingUpdates.push(allowTools);- this.send({- type: "response.create",- response: { tool_choice: allowTools ? "auto" : "none" },- });+ this.createResponse(update);}/** Takes effect at the next response; the one playing keeps its speed. */@@ -536,7 +558,11 @@ export class XaiLiveSession implements LiveSession {) {for (const result of results) {this.pendingCalls.delete(result.callId);- if (this.updateCalls.delete(result.callId)) this.updateRound = true;+ const update = this.updateCalls.get(result.callId);+ if (update !== undefined) {+ this.updateCalls.delete(result.callId);+ this.updateRound = update;+ }// A call written as words has no call item to answer; its result is// context, with a reminder of how to call.const written = this.textCalls.get(result.callId);@@ -560,10 +586,11 @@ export class XaiLiveSession implements LiveSession {// answered by the update, which goes on in its own words.if (results.length === 0 || this.pendingCalls.size > 0) return;const update = this.updateRound;- this.updateRound = false;+ this.updateRound = undefined;if (!reply) return;- if (update) this.pendingUpdates.push(true);- this.requestResponse();+ this.requestResponse(+ update === undefined ? undefined : { id: update, tools: true },+ );}async *events(): AsyncIterable<LiveEvent> {@@ -587,9 +614,27 @@ export class XaiLiveSession implements LiveSession {this.end();}- private requestResponse() {- if (this.response) this.responseWanted = true;- else this.send({ type: "response.create" });+ private requestResponse(update?: UpdateRequest) {+ if (this.response) {+ this.responseWanted = true;+ this.wantedUpdate = update;+ } else this.createResponse(update);+ }++ /**+ * An update's response carries its ID as metadata, which xAI echoes on+ * response.created and response.done, also when it is canceled.+ */+ private createResponse(update?: UpdateRequest) {+ if (!update) return this.send({ type: "response.create" });+ const tools = update.tools ? "auto" : "none";+ this.send({+ type: "response.create",+ response: {+ tool_choice: tools,+ metadata: { update_id: update.id, tools },+ },+ });}#sendAudio(pcm: Buffer) {@@ -634,13 +679,22 @@ export class XaiLiveSession implements LiveSession {}case "response.created": {const response = event.response as Record<string, unknown> | undefined;- const update = this.pendingUpdates.length > 0;- const tools = update ? this.pendingUpdates.shift()! : true;+ const metadata = response?.metadata as+ | Record<string, unknown>+ | null+ | undefined;+ const updateId =+ typeof metadata?.update_id === "string"+ ? metadata.update_id+ : undefined;+ const update = updateId !== undefined;+ const tools = !update || metadata?.tools !== "none";// A server-started reply supersedes calls nobody answers any more.if (!update) this.pendingCalls.clear();this.response = {id: typeof response?.id === "string" ? response.id : "",update,+ updateId,tools,audioStarted: false,canceled: false,@@ -652,7 +706,9 @@ export class XaiLiveSession implements LiveSession {};this.retrying = false;this.audioCarry = Buffer.alloc(0);- if (!update) this.push({ type: "response_started" });+ if (updateId !== undefined)+ this.push({ type: "update_accepted", id: updateId });+ else this.push({ type: "response_started" });return;}case "response.output_item.added": {@@ -716,10 +772,22 @@ export class XaiLiveSession implements LiveSession {this.runTextCall(response, response.markup);else this.release(response);}- this.push({ type: "response_finished", canceled });+ this.push({+ type: "response_finished",+ canceled,+ ...(response?.updateId === undefined+ ? {}+ : { updateId: response.updateId }),+ });if (this.responseWanted && this.pendingCalls.size === 0) {+ const update = this.wantedUpdate;this.responseWanted = false;- this.send({ type: "response.create" });+ this.wantedUpdate = undefined;+ this.createResponse(update);+ } else if (this.waitingTell) {+ const { cue, update } = this.waitingTell;+ this.waitingTell = undefined;+ this.sendTell(cue, update);}return;}@@ -837,8 +905,11 @@ export class XaiLiveSession implements LiveSession {"Your last reply wrote a tool call as words instead of calling the tool, so nothing ran and none of it was said. Call the tool now as a function call, without words first; never write a call in words or angle brackets.",);this.retrying = true;- if (response.update) this.pendingUpdates.push(true);- this.requestResponse();+ this.requestResponse(+ response.updateId === undefined+ ? undefined+ : { id: response.updateId, tools: true },+ );return;}const callId = `text_call_${randomUUID()}`;@@ -850,7 +921,8 @@ export class XaiLiveSession implements LiveSession {private handOver(response: Response, call: LiveFunctionCall) {response.called = true;this.pendingCalls.add(call.callId);- if (response.update) this.updateCalls.add(call.callId);+ if (response.updateId !== undefined)+ this.updateCalls.set(call.callId, response.updateId);this.push({type: "function_calls",calls: [call],