Skip to content

fix(openai): GPT-Live relay calls answer the callee before the opening line - #165147

Open
jayzhou2309 wants to merge 5 commits into
openclaw:mainfrom
jayzhou2309:fix/gpt-live-opening-before-caller-audio
Open

jayzhou2309 wants to merge 5 commits into
openclaw:mainfrom
jayzhou2309:fix/gpt-live-opening-before-caller-audio

Conversation

@jayzhou2309

@jayzhou2309 jayzhou2309 commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Related: #164979

What Problem This Solves

On GPT-Live calls through the Gateway relay (the WebRTC transport used with ChatGPT sign-in), caller audio captured while the call connects reaches GPT-Live before the session has started. On an inbound phone call, where voice-call sends the greeting once the session is ready, the caller's first words reach the model before the greeting, so the assistant can answer them before it greets. If GPT-Live never reports that the session started, the call stays up with no greeting while the caller's audio goes into a session that never started.

User Impact

On GPT-Live relay calls over WebRTC, caller audio now reaches GPT-Live only after the session has started and after any greeting sent when the session is ready. Audio captured while the call connects is held (newest 5 s), not dropped. On inbound phone calls the greeting now goes out before the caller's first words. On outbound phone calls the opening line has been in the session instructions since #165715, and the callee's first words now arrive after the session starts instead of before. If the session never starts, connect now fails at its 30 s deadline, as the direct transport already does, and voice-call ends the call with an error instead of keeping a silent call open. The direct transport and other realtime providers are unchanged.

Why This Change Was Made

A greeting sent on ready goes out as speakable session context from onReady, which runs once the sideband reports session.started. On WebRTC, OpenAIQuicksilverGatewayBridge.connectWebRtc handed the pre-ready caller audio to the media peer as soon as the peer existed, and sendAudio forwarded every later frame straight to the peer. Both happened before session.started, so the model heard the caller first.

The bridge now keeps WebRTC caller audio in its existing bounded buffer (newest 5 s) until the session starts. Because the audio is held until then, WebRTC connect also waits for session.started inside the connect deadline, as the direct transport already does. A session that never starts fails connect() with a TimeoutError and releases the held audio, instead of resolving and holding the caller's audio until the 30-minute session TTL. When connect completes, the bridge calls onReady first, so any greeting context goes out, then hands the buffer to the peer. This is direction (b) from the issue. It does not change where voice-call puts the opening line (#165715 moved outbound openings into the session instructions), add a listen-first mode (#164980), or touch greeting playback protection (#159144).

Evidence

  • Red first, ordering. Commit 920b5f6 adds sends the greeting context before releasing caller audio to the model to extensions/openai/realtime-quicksilver-gateway-bridge.test.ts. It records the order of sideband sends and peer audio. Since f93c78c the session starts while the WebRTC answer is still being applied, and caller audio arrives in that window. With the bridge file from upstream/main c24097e it fails, because audio:0102 and audio:0304 reach the peer before session.context.append. On this head it passes with the order session.context.append, then the held audio, then live audio.
  • Red first, missed start. Commit 3223ec6 adds fails the connection and drops held caller audio when the session never starts. On 3223ec6 it fails (1 failed, 14 passed), because connect() resolves although the session never started. Commit f93c78c makes WebRTC connect wait for session.started, and the test passes. connect() rejects with TimeoutError, onReady never fires, the peer is closed, and the bridge neither holds nor sends caller audio.
  • A mutant that gates sendAudio on ready instead of connected fails the ordering test (1 failed, 14 passed). The test covers the window where session.started has arrived but connect has not finished.
  • Five existing tests resolved a WebRTC connect without session.started, and they now start the session during connect, the way the provider does. Three are in realtime-quicksilver-gateway-bridge.test.ts, one is the webrtc case of realtime-quicksilver-gateway-audio.test.ts, and one is the retained-audio test in realtime-quicksilver-media.runtime.test.ts. Each still checks what it checked before.
  • Head f93c78c passes all 39 non-live extensions/openai/realtime-*.test.ts files (450 tests). It also passes voice-call realtime-handler and realtime-handler.lifecycle, src/talk/session-runtime, src/gateway/talk/relay/index, and Discord realtime-speaker-sessions (5 files, 220 tests). tsgo -p tsconfig.extensions.json, tsgo -p test/tsconfig/tsconfig.extensions.test.json, oxfmt --check, oxlint on the four changed files, and git diff --check are clean.
  • Earlier heads. A second model reviewed the original diff for lost or reordered audio, a reentrant close from onReady, abort before start, and the direct transport, and found no correctness issue. node scripts/check-changed.mjs --base upstream/main passed on 472f4550db4, with its extension-test typecheck step rerun alone after a local time limit. It was not rerun on this head.

Real behavior proof

This run used head f93c78c. It ran again with only extensions/openai/realtime-quicksilver-gateway-bridge.ts replaced by the copy from upstream/main fac490e. Main has no other product change on these paths since this PR's base. Each call enters through the voice-call phone-call controller, as a Twilio media stream does, and that controller decides when to send the greeting.

Real in this run:

  • voice-call's RealtimeCallHandler, with a real CallManager and SQLite call store. The stream URL comes from buildTwiMLPayload and the stream connects through handleWebSocketUpgrade. The provider is resolved the way runtime.ts does it. The controller's own greeting policy decides the greeting: on ready for inbound calls, and in the session instructions for outbound calls.
  • The OpenAI realtime voice provider plugin and its OpenAIQuicksilverGatewayBridge, with model gpt-live-1-codex and ChatGPT auth resolution, so the bridge uses WebRTC.
  • The bridge's default peer, the worker-thread facade in realtime-quicksilver-peer.runtime.ts. Opus, DTLS and SRTP run in the audio worker. Each timeline logs the peer class and its worker thread id.
  • HTTP, WebSocket and WebRTC traffic, all on loopback.

Faked:

  • GPT-Live. A local HTTP endpoint answers the call-creation request with the SDP answer of a werift peer (ICE-lite on 127.0.0.1, on its own worker thread) that records every RTP packet. A local WebSocket server plays the sideband. It records what the bridge sends and emits session.started 600 ms after the WebRTC connection comes up, or never. The bridge reaches both through its fetchImpl and webSocketFactory options, which rewrite only the host.
  • The carrier. A WebSocket client sends Twilio's media-stream messages (connected, start, then media every 20 ms, then stop). The caller speaks a 440 Hz tone for the first second, then sends silence. FakeProvider stands in for Twilio's REST API.
  • The ChatGPT credential store, which returns a synthetic token.

A speech packet is an RTP payload of 10 bytes or more. The peer's silence frames are 3 bytes, and no other payload sizes appeared. Times are in ms from the carrier's start message.

Call Bridge Runs Caller-speech RTP before session.started Before the greeting context What happened
Inbound, greeting on ready main 3 31 of 41-49, each run 31, each run First speech at 358-1105 ms, greeting at 959-1707 ms
Inbound, greeting on ready this PR 3 0 of 41-50 0 Greeting at 1086-2068 ms, first speech 13-16 ms after it
Outbound, with an opening line main 3 31 of 49, each run No greeting context sent Opening line in the call-creation instructions
Outbound, with an opening line this PR 3 0 of 49 No greeting context sent Opening line in the call-creation instructions
Session never starts main 1 49 of 49 No greeting context sent connect() resolved at 232 ms. The call was still open at 40 s.
Session never starts this PR 1 0 No greeting context sent connect() rejected with TimeoutError at 30.1 s. voice-call ended the call with error and closed the stream with 1011 Failed to connect.

On outbound calls the callee's speech claims the opening, so the controller's 3 s fallback greeting never fires, in either build. The difference there is only when the callee's first words reach GPT-Live: before the session starts on main, and 18-22 ms after session.started on this branch.

Inbound, first run on each build (some lines omitted):

this PR
  213  carrier            start
  235  carrier            caller speech starts
  900  controller         createBridge -> OpenAIQuicksilverGatewayBridge
 1290  bridge             peer is the worker facade (audio worker thread 5)
 1290  bridge-net         fetch https://chatgpt.com/backend-api/codex/realtime/calls?intent=quicksilver&architecture=avas
 1302  carrier            caller speech ends (39 frames)
 1322  bridge-net         websocket wss://api.openai.com/v1/live/rtc_proof165147
 1466  gpt-live-peer      connection connected
 2066  gpt-live-sideband  send session.started
 2068  bridge             connect() resolved
 2068  gpt-live-sideband  recv session.context.append [inbound greeting]
 2081  gpt-live-peer      first of 41 caller-speech RTP packets (from the RTP log)

main fac490e5876
  157  carrier            start
  179  carrier            caller speech starts
  694  controller         createBridge -> OpenAIQuicksilverGatewayBridge
  959  bridge             peer is the worker facade (audio worker thread 5)
  976  bridge             connect() resolved
 1104  gpt-live-peer      connection connected
 1105  gpt-live-peer      first of 41 caller-speech RTP packets (from the RTP log)
 1174  carrier            caller speech ends (39 frames)
 1705  gpt-live-sideband  send session.started
 1707  gpt-live-sideband  recv session.context.append [inbound greeting]

Session never starts, this PR (some lines omitted):

  132  bridge             connect()
  224  bridge             peer is the worker facade (audio worker thread 23)
  365  gpt-live-peer      connection connected
30133  bridge             connect() rejected: TimeoutError: OpenAI GPT-Live gateway relay failed
30133  controller         error: [voice-call] Failed to connect realtime bridge: TimeoutError: OpenAI GPT-Live gateway relay failed
30141  gpt-live-sideband  recv session.close
30155  controller         log: [voice-call] Realtime call ended callId=<call-id> providerCallId=CA0000000000000000000000000000proof reason=error
30158  carrier            stream closed by Gateway 1011 Failed to connect

What this does not show:

  • No real GPT-Live session ran, and no OpenAI credentials were available. The run shows what the relay puts on the wire and in what order. It does not show how GPT-Live orders sideband context against WebRTC audio, or what the model says.
  • No real carrier call ran. The off-script openings reported on physical Twilio calls in [voice-call] GPT-Live outbound calls: the callee's "hello" reaches the model before the opening line (double or invented greetings) — #85846 fixed for OpenAI Realtime only #164979 are not shown fixed, so this PR now links the issue as related instead of closing it.
  • The Gateway process and its webhook HTTP server were not started. The bridge has no setting that points it at another GPT-Live endpoint, so a running Gateway would need in-process patching to reach a local fake. The harness calls the controller methods that the webhook server calls instead.
  • The 600 ms between the WebRTC connection and session.started is a choice, not a measured GPT-Live latency.
Harness (temporary test file, not committed)

Copy it to extensions/logbook/zz-proof-165147.test.ts, a database-worker test root, so the real CallManager gets the main-thread SQLite broker. Then run PROOF_LABEL=after PROOF_OUT=after.jsonl node scripts/run-vitest.mjs run extensions/logbook/zz-proof-165147.test.ts. For the main run, check out extensions/openai/realtime-quicksilver-gateway-bridge.ts from upstream/main first. Each output line is one call, with a summary and its timeline.

// Proof harness for openclaw/openclaw#165147. Temporary: run-proof.sh copies it to
// extensions/logbook/ (a database-worker test root, so the real CallManager gets the
// main-thread SQLite broker), runs it, and deletes it. It is never committed.
//
// Real: the voice-call phone-call controller (RealtimeCallHandler with a real
// CallManager), the OpenAI realtime voice provider plugin and its GPT-Live gateway
// relay bridge, the bridge's default WebRTC peer (the worker-thread facade, with
// werift, Opus, DTLS and SRTP running in the audio worker), real HTTP, WebSocket
// and WebRTC traffic on loopback.
// Faked: the GPT-Live service (a local call-creation endpoint, sideband WebSocket
// server and werift answering peer), the carrier (a local WebSocket client speaking
// Twilio's media-stream messages; FakeProvider stands in for Twilio's REST API), and
// the ChatGPT credential store (returns a synthetic token).
import { once } from "node:events";
import { appendFileSync, writeFileSync } from "node:fs";
import http from "node:http";
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
import { Worker } from "node:worker_threads";
import { WebSocket, WebSocketServer } from "openclaw/plugin-sdk/websocket-runtime";
import { expect, it } from "vitest";
import { normalizeVoiceCallConfig } from "../voice-call/src/config.js";
import { CallManager } from "../voice-call/src/manager.js";
import {
  createTestStorePath,
  FakeProvider,
  installVoiceCallStateRuntimeForTests,
} from "../voice-call/src/manager.test-harness.js";
import { resolveConfiguredRealtimeVoiceProviderAsync } from "../voice-call/src/realtime-voice.runtime.js";
import { RealtimeCallHandler } from "../voice-call/src/webhook/realtime-handler.js";
import { StreamDisconnectGrace } from "../voice-call/src/webhook/stream-disconnect-grace.js";
import { openAIRealtimeHost } from "../openai/realtime-host.js";
import { OpenAIQuicksilverAudioPeer as WorkerFacadePeer } from "../openai/realtime-quicksilver-peer.runtime.js";
import { buildOpenAIRealtimeVoiceProvider } from "../openai/realtime-voice-provider-factory.js";

const LABEL = process.env.PROOF_LABEL ?? "unlabeled";
const OUT = process.env.PROOF_OUT ?? "/dev/stdout";
const REPEATS = Number(process.env.PROOF_REPEATS ?? "3");
const SCENARIOS = (process.env.PROOF_SCENARIOS ?? "inbound,outbound,never-started").split(",");

const MODEL = "gpt-live-1-codex";
const SESSION_STARTED_DELAY_MS = 600; // after the provider peer's DTLS connection is up
const CALLER_SPEECH_MS = 1_000; // the caller talks from the first media frame
const SPEECH_PAYLOAD_MIN_BYTES = 10; // Opus speech frames; the peer's silence frames are 3 bytes
const INBOUND_GREETING = "Thanks for calling. How can I help you today?";
const OPENING_LINE =
  "Hi, this is an AI assistant calling to book a table for two tonight. Do you have availability?";
const SYNTHETIC_ACCOUNT = "acct_synthetic_proof";

function jwtSegment(value: unknown): string {
  return Buffer.from(JSON.stringify(value)).toString("base64url");
}
// Unsigned, synthetic. Only the ChatGPT account claim is read by the auth resolver.
const SYNTHETIC_CHATGPT_TOKEN = `${jwtSegment({ alg: "none" })}.${jwtSegment({
  "https://api.openai.com/auth": { chatgpt_account_id: SYNTHETIC_ACCOUNT },
})}.synthetic`;

type Entry = { t: number; src: string; event: string };

function linearToMulaw(input: number): number {
  let sample = input;
  const sign = sample < 0 ? 0x80 : 0;
  if (sign) {
    sample = -sample;
  }
  sample = Math.min(sample, 32_635) + 0x84;
  let exponent = 7;
  for (let mask = 0x4000; (sample & mask) === 0 && exponent > 0; mask >>= 1) {
    exponent -= 1;
  }
  const mantissa = (sample >> (exponent + 3)) & 0x0f;
  return ~(sign | (exponent << 4) | mantissa) & 0xff;
}

const SPEECH_FRAME = Buffer.from(
  Array.from({ length: 160 }, (_, i) =>
    linearToMulaw(Math.round(10_000 * Math.sin((2 * Math.PI * 440 * i) / 8_000))),
  ),
);
const SILENCE_FRAME = Buffer.alloc(160, 0xff);

// The GPT-Live side of the WebRTC call, on its own event loop so its RTP clock
// is not delayed by the Gateway thread. ICE-lite on loopback, as in
// realtime-quicksilver-peer-worker.test.ts.
const providerPeerSource = `const { parentPort, workerData } = require('node:worker_threads');
(async () => {
  const { RTCPeerConnection, useOPUS } = await import(workerData.weriftUrl);
  const now = () => performance.timeOrigin + performance.now();
  const peer = new RTCPeerConnection({
    codecs: { audio: [useOPUS({ payloadType: 111 })], video: [] },
    iceLite: true,
    iceUseIpv4: false,
    iceUseIpv6: false,
    iceAdditionalHostAddresses: ['127.0.0.1'],
  });
  peer.addTransceiver('audio', { direction: 'sendrecv' });
  peer.connectionStateChange.subscribe(state => parentPort.postMessage({ type: 'state', state, at: now() }));
  peer.onTrack.subscribe(track => track.onReceiveRtp.subscribe(packet =>
    parentPort.postMessage({ type: 'rtp', bytes: packet.payload.length, at: now() })));
  parentPort.on('message', async message => {
    if (message.type === 'offer') {
      await peer.setRemoteDescription({ type: 'offer', sdp: message.sdp });
      await peer.setLocalDescription(await peer.createAnswer());
      parentPort.postMessage({ type: 'answer', sdp: peer.localDescription.sdp });
    } else if (message.type === 'close') {
      await peer.close().catch(() => {});
      parentPort.postMessage({ type: 'closed' });
    }
  });
  parentPort.postMessage({ type: 'ready' });
})().catch(error => parentPort.postMessage({ type: 'error', message: String((error && error.stack) || error) }));`;

async function listen(server: http.Server): Promise<number> {
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  const address = server.address();
  if (!address || typeof address === "string") {
    throw new Error("no port");
  }
  return address.port;
}

function describeArg(arg: unknown): string {
  if (arg instanceof Error) {
    return `${arg.name}: ${arg.message}`;
  }
  return typeof arg === "string" ? arg : JSON.stringify(arg);
}

async function runScenario(
  scenario: "inbound" | "outbound" | "never-started",
  attempt: number,
) {
  const t0 = performance.timeOrigin + performance.now();
  const at = (absolute = performance.timeOrigin + performance.now()) =>
    Math.round(absolute - t0);
  const timeline: Entry[] = [];
  const log = (src: string, event: string, t = at()) => timeline.push({ t, src, event });
  const rtp: Array<{ t: number; bytes: number }> = [];
  const cleanups: Array<() => unknown> = [];

  // Controller and bridge logs, with timestamps.
  const original = { log: console.log, warn: console.warn, error: console.error };
  for (const level of ["log", "warn", "error"] as const) {
    console[level] = (...args: unknown[]) => {
      const line = args.map(describeArg).join(" ");
      if (line.startsWith("[voice-call]")) {
        log("controller", `${level}: ${line}`);
      }
      original[level](...args);
    };
  }
  cleanups.push(() => Object.assign(console, original));

  // --- Fake GPT-Live service -------------------------------------------------
  const peerWorker = new Worker(providerPeerSource, {
    eval: true,
    workerData: {
      weriftUrl: pathToFileURL(createRequire(new URL("../openai/package.json", import.meta.url)).resolve("werift")).href,
    },
  });
  cleanups.push(() => peerWorker.terminate());
  let sideband: WebSocket | undefined;
  let liveBridge: object | undefined;
  let sessionStartedTimer: ReturnType<typeof setTimeout> | undefined;
  cleanups.push(() => clearTimeout(sessionStartedTimer));
  const answers: Array<(sdp: string) => void> = [];
  peerWorker.on("message", (message) => {
    if (message.type === "rtp") {
      rtp.push({ t: at(message.at), bytes: message.bytes });
    } else if (message.type === "state") {
      log("gpt-live-peer", `connection ${message.state}`, at(message.at));
      if (message.state === "connected" && scenario !== "never-started") {
        sessionStartedTimer = setTimeout(() => {
          log("gpt-live-sideband", "send session.started");
          sideband?.send(JSON.stringify({ type: "session.started", session: { id: "sess_proof" } }));
        }, SESSION_STARTED_DELAY_MS);
      }
    } else if (message.type === "answer") {
      answers.shift()?.(message.sdp);
    } else if (message.type === "error") {
      log("gpt-live-peer", `error ${message.message}`);
    }
  });
  await once(peerWorker, "message");

  let callInstructions = "";
  const callServer = http.createServer(async (req, res) => {
    const chunks: Buffer[] = [];
    for await (const chunk of req) {
      chunks.push(chunk as Buffer);
    }
    const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {
      sdp: string;
      session: { instructions?: string; model?: string };
    };
    callInstructions = body.session.instructions ?? "";
    log(
      "gpt-live-http",
      `POST call (bearer=${req.headers.authorization ? "present" : "missing"}, model=${body.session.model})`,
    );
    const answer = new Promise<string>((resolve) => answers.push(resolve));
    peerWorker.postMessage({ type: "offer", sdp: body.sdp });
    const sdp = await answer;
    res.writeHead(201, { "Content-Type": "application/sdp", Location: "/v1/live/rtc_proof165147" });
    res.end(sdp);
    log("gpt-live-http", "201 answer sent");
  });
  const callPort = await listen(callServer);
  cleanups.push(() => callServer.closeAllConnections());
  cleanups.push(() => callServer.close());

  const sidebandHttp = http.createServer();
  const sidebandServer = new WebSocketServer({ server: sidebandHttp });
  sidebandServer.on("connection", (socket, req) => {
    sideband = socket;
    log(
      "gpt-live-sideband",
      `connected ${req.url} (bearer=${req.headers.authorization ? "present" : "missing"})`,
    );
    socket.on("message", (data) => {
      const event = JSON.parse(String(data)) as { type: string; text?: string; item?: unknown };
      const text = JSON.stringify(event).includes(INBOUND_GREETING)
        ? " [inbound greeting]"
        : JSON.stringify(event).includes(OPENING_LINE)
          ? " [opening line]"
          : "";
      log("gpt-live-sideband", `recv ${event.type}${text}`);
    });
    socket.on("close", (code) => log("gpt-live-sideband", `closed ${code}`));
  });
  const sidebandPort = await listen(sidebandHttp);
  cleanups.push(() => sidebandServer.close());
  cleanups.push(() => sidebandHttp.closeAllConnections());
  cleanups.push(() => sidebandHttp.close());

  // Network edge: the bridge's own fetch and WebSocket seams. URLs are rewritten
  // to loopback; requests, headers and bodies go over real HTTP and WebSocket.
  const fetchImpl: typeof fetch = (url, init) => {
    // Observation only: which peer the bridge created (private field, read once).
    const peer = (liveBridge as { peer?: { worker?: { threadId: number } } } | undefined)?.peer;
    log(
      "bridge",
      `peer is ${peer instanceof WorkerFacadePeer ? "the worker facade" : "NOT the worker facade"} (audio worker thread ${peer?.worker?.threadId ?? "none"})`,
    );
    log("bridge-net", `fetch ${String(url)}`);
    return fetch(`http://127.0.0.1:${callPort}${new URL(String(url)).pathname}`, init);
  };
  const webSocketFactory = (url: string, options: object) => {
    log("bridge-net", `websocket ${url}`);
    return new WebSocket(`ws://127.0.0.1:${sidebandPort}${new URL(url).pathname}`, options);
  };

  // --- Real provider plugin, with the credential store stubbed -----------------
  const isChatGptProfile = (opts: { provider?: string; profileTypes?: readonly string[] }) =>
    opts.provider === "openai" && Boolean(opts.profileTypes?.includes("oauth"));
  const host = {
    ...openAIRealtimeHost,
    isProviderAuthProfileConfigured: isChatGptProfile,
    isProviderAuthProfileConfiguredAsync: async (opts: Parameters<typeof isChatGptProfile>[0]) =>
      isChatGptProfile(opts),
    resolveProviderAuthProfileApiKey: async (opts: Parameters<typeof isChatGptProfile>[0]) =>
      isChatGptProfile(opts) ? SYNTHETIC_CHATGPT_TOKEN : undefined,
  } as typeof openAIRealtimeHost;
  const provider = buildOpenAIRealtimeVoiceProvider(host, {
    logger: {
      debug: (message: string) => log("bridge", `debug: ${message}`),
      warn: (message: string) => log("bridge", `warn: ${message}`),
    },
  });
  // Wrapped in place: the provider's internal API lives on a non-enumerable symbol.
  const createBridge = provider.createBridge.bind(provider);
  provider.createBridge = (req) => {
    const bridge = createBridge({ ...req, fetchImpl, webSocketFactory } as typeof req);
    liveBridge = bridge;
    log("controller", `createBridge -> ${bridge.constructor.name}`);
    const connect = bridge.connect.bind(bridge);
    bridge.connect = () => {
      log("bridge", "connect()");
      const pending = connect();
      pending.then(
        () => log("bridge", "connect() resolved"),
        (error: unknown) => log("bridge", `connect() rejected: ${describeArg(error)}`),
      );
      return pending;
    };
    return bridge;
  };

  // --- Real phone-call controller ---------------------------------------------
  installVoiceCallStateRuntimeForTests();
  const storePath = createTestStorePath();
  const config = normalizeVoiceCallConfig({
    provider: "twilio",
    fromNumber: "+15550000000",
    inboundPolicy: "open",
    inboundGreeting: INBOUND_GREETING,
    maxConcurrentCalls: 5,
    realtime: {
      enabled: true,
      provider: "openai",
      providers: { openai: { model: MODEL } },
      instructions: "You are the owner's phone assistant.",
    },
  });
  const carrier = new FakeProvider("twilio");
  const manager = new CallManager(config, storePath);
  await manager.initialize(carrier, "https://gateway.example/voice/webhook");
  cleanups.push(() => manager.stop());
  const lifecycle = new StreamDisconnectGrace(() => {});
  cleanups.push(() => lifecycle.close());
  const coreConfig = {};
  const handler = new RealtimeCallHandler(
    config.realtime,
    manager,
    async (call) => {
      const agentId = call.agentId ?? "main";
      // Same resolution as extensions/voice-call/src/runtime.ts, with this provider listed.
      const resolved = await resolveConfiguredRealtimeVoiceProviderAsync({
        configuredProviderId: config.realtime.provider,
        providerConfigs: config.realtime.providers,
        cfg: coreConfig,
        agentId,
        surface: "gateway-relay",
        useProviderDefaultModel: true,
        providers: [provider],
      });
      return {
        agentId,
        provider: resolved.provider,
        providerConfig: resolved.providerConfig,
        capabilities: resolved.capabilities,
        instructions: config.realtime.instructions,
      };
    },
    config.serve.path,
    lifecycle,
    coreConfig,
    config.voicemail.holdOpeningMaxMs,
  );
  cleanups.push(() => handler.close());
  handler.setPublicUrl("https://gateway.example/voice/webhook");

  let callSid = "CA0000000000000000000000000000proof";
  let direction = "inbound";
  if (scenario === "outbound") {
    const placed = await manager.initiateCall("+15550000001", undefined, {
      message: OPENING_LINE,
      mode: "conversation",
    });
    expect(placed.success).toBe(true);
    callSid = "request-uuid"; // FakeProvider's provider call id
    direction = "outbound-api";
    log("carrier", "outbound call placed (CallManager.initiateCall)");
  }
  const twimlRequest = new http.IncomingMessage(null as never);
  twimlRequest.headers = { host: "gateway.example" };
  const twiml = handler.buildTwiMLPayload(
    twimlRequest,
    new URLSearchParams({
      CallSid: callSid,
      Direction: direction,
      From: "+15550000001",
      To: "+15550000000",
    }),
    callSid,
  );
  const streamUrl = new URL(twiml.body.match(/wss:\/\/[^" ]+/)?.[0] ?? "");
  const upgradeServer = http.createServer();
  upgradeServer.on("upgrade", (req, socket, head) =>
    handler.handleWebSocketUpgrade(req, socket, head),
  );
  const upgradePort = await listen(upgradeServer);
  cleanups.push(() => upgradeServer.closeAllConnections());
  cleanups.push(() => upgradeServer.close());

  // --- Carrier media stream (Twilio message shapes) ----------------------------
  const twilio = new WebSocket(`ws://127.0.0.1:${upgradePort}${streamUrl.pathname}`);
  await once(twilio, "open");
  let twilioClose: { t: number; code: number; reason: string } | undefined;
  let callerHangupAt: number | undefined;
  twilio.on("close", (code, reason) => {
    if (callerHangupAt === undefined) {
      twilioClose = { t: at(), code, reason: String(reason) };
      log("carrier", `stream closed by Gateway ${code} ${String(reason)}`);
    }
  });
  const streamSid = "MZ0000000000000000000000000000proof";
  twilio.send(JSON.stringify({ event: "connected", protocol: "Call", version: "1.0.0" }));
  const start = performance.timeOrigin + performance.now();
  twilio.send(
    JSON.stringify({
      event: "start",
      streamSid,
      start: { streamSid, callSid, tracks: ["inbound"], mediaFormat: { encoding: "audio/x-mulaw", sampleRate: 8000, channels: 1 } },
    }),
  );
  log("carrier", "start");
  let frames = 0;
  let speechFrames = 0;
  const media = setInterval(() => {
    if (twilio.readyState !== WebSocket.OPEN) {
      return;
    }
    const elapsed = performance.timeOrigin + performance.now() - start;
    const speaking = elapsed < CALLER_SPEECH_MS;
    frames += 1;
    if (speaking) {
      speechFrames += 1;
      if (speechFrames === 1) {
        log("carrier", "caller speech starts");
      }
    } else if (speechFrames > 0 && speechFrames === frames - 1) {
      log("carrier", `caller speech ends (${speechFrames} frames)`);
    }
    twilio.send(
      JSON.stringify({
        event: "media",
        streamSid,
        media: {
          track: "inbound",
          chunk: String(frames),
          timestamp: String(frames * 20),
          payload: (speaking ? SPEECH_FRAME : SILENCE_FRAME).toString("base64"),
        },
      }),
    );
  }, 20);
  cleanups.push(() => clearInterval(media));

  const observeMs = scenario === "never-started" ? 40_000 : 6_500;
  const deadline = Date.now() + observeMs;
  while (Date.now() < deadline && !twilioClose) {
    await new Promise((resolve) => setTimeout(resolve, 50));
  }
  if (!twilioClose) {
    callerHangupAt = at();
    log("carrier", `still connected at ${callerHangupAt} ms; caller hangs up`);
    twilio.send(JSON.stringify({ event: "stop", streamSid }));
    twilio.close(1000);
    await new Promise((resolve) => setTimeout(resolve, 500));
  }
  clearInterval(media);
  const hangups = carrier.hangupCalls.map((call) => call.reason ?? "unspecified");
  for (const cleanup of cleanups.toReversed()) {
    try {
      await cleanup();
    } catch {
      // Best-effort teardown of the fixture.
    }
  }

  const sessionStartedAt = timeline.find((e) => e.event === "send session.started")?.t;
  const greeting = timeline.find(
    (e) => e.src === "gpt-live-sideband" && e.event.startsWith("recv session.context.append"),
  );
  const speech = rtp.filter((packet) => packet.bytes >= SPEECH_PAYLOAD_MIN_BYTES);
  const sizes: Record<string, number> = {};
  for (const packet of rtp) {
    const bucket = packet.bytes < SPEECH_PAYLOAD_MIN_BYTES ? `${packet.bytes}B` : ">=10B";
    sizes[bucket] = (sizes[bucket] ?? 0) + 1;
  }
  const connectOutcome = timeline.find((e) => e.event.startsWith("connect() "));
  return {
    label: LABEL,
    scenario,
    attempt,
    summary: {
      callerSpeechFrames: speechFrames,
      openingLineInCallInstructions: callInstructions.includes(OPENING_LINE),
      inboundGreetingInCallInstructions: callInstructions.includes(INBOUND_GREETING),
      connect: connectOutcome ? `${connectOutcome.event} @${connectOutcome.t}ms` : "pending",
      sessionStartedAt: sessionStartedAt ?? null,
      contextAppend: greeting ? `${greeting.event} @${greeting.t}ms` : null,
      rtpPackets: rtp.length,
      rtpSizes: sizes,
      speechRtp: speech.length,
      firstSpeechRtpAt: speech[0]?.t ?? null,
      speechRtpBeforeSessionStarted: speech.filter(
        (p) => sessionStartedAt === undefined || p.t < sessionStartedAt,
      ).length,
      speechRtpBeforeContextAppend: greeting
        ? speech.filter((p) => p.t < greeting.t).length
        : null,
      gatewayClosedStream: twilioClose ?? null,
      callerHungUpAt: callerHangupAt ?? null,
      carrierHangups: hangups,
    },
    timeline,
  };
}

it(`GPT-Live relay proof through the voice-call controller (${LABEL})`, async () => {
  writeFileSync(OUT, "");
  for (const scenario of SCENARIOS as Array<"inbound" | "outbound" | "never-started">) {
    const repeats = scenario === "never-started" ? 1 : REPEATS;
    for (let attempt = 1; attempt <= repeats; attempt += 1) {
      const result = await runScenario(scenario, attempt);
      appendFileSync(OUT, `${JSON.stringify(result)}\n`);
    }
  }
}, 600_000);

Test cost

realtime-quicksilver-gateway-bridge.test.ts now has 15 tests. In a local three-file run, the missed-start case took 109 ms, most of it the real 100 ms connect deadline the test sets, and the reworked ordering case took 76 ms. The new startSession helper polls with vi.waitFor until the sideband socket exists. The retained-audio case in realtime-quicksilver-media.runtime.test.ts took 283 ms. The --maxWorkers=1 wall times were not remeasured on this head.

Not verified: a live call with a real carrier and GPT-Live. See "What this does not show" above.

Rebased 2026-11-30 onto main c24097e (head f93c78c). Main's #190466 (60c2748) defers onReady until the WebRTC answer is accepted, and it conflicted with this PR's change to onSessionStarted. Main's #189029 (c6ad0a9) changed the captured-length check in realtime-quicksilver-gateway-audio.test.ts, and it conflicted with this PR's edit to that test. The resolution keeps both of main's changes and releases held audio right after onReady on each path that calls it. The connect fix then makes WebRTC observe session.started before connect completes, so onReady has one call site again.

AI disclosure: an AI agent (Claude Code) reproduced the ordering defect, traced the root cause, wrote the tests and the fixes, rebased the branch onto main and resolved the conflicts, and wrote and ran the proof harness above on f93c78c and against main's bridge. It ran node scripts/run-vitest.mjs run on each test file named above and on the harness, tsgo for the extension and extension-test configs, oxfmt --check, oxlint, and git diff --check. A second model reviewed the original diff.

🤖 Written and posted by an AI agent (Claude Code) on behalf of @jayzhou2309.

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: passed.

What this changes

This PR holds WebRTC caller audio until session startup and the readiness callback complete, and times out sessions that never start.

Example: An inbound gpt-live-1-codex call captures speech while connecting.

  • Before: The supplied main-branch trace records 31 speech RTP packets before session startup and greeting context.
  • After: The supplied current-head traces record zero early speech packets, with buffered speech following greeting context.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused repair with production transport evidence and no identified blocking defect; overall readiness is capped for partial coverage of the linked issue, and required CI remains outstanding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): Current-head logs and the inspected harness exercise the actual phone-call controller, OpenAI relay, default worker facade, and real loopback transport with delayed or absent session.started. They establish greeting-context-before-speech ordering and timeout cleanup, resolving the prior review's controller, worker, and head gaps under the internal-ordering proof rule; they do not establish GPT-Live's spoken response or resolution of the broader physical-call report.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Caller speech can reach an unstarted relay session before greeting context, and a session that never starts can leave a silent call open.
Reason: The transport defect is concrete and the repair is focused, while the broader linked report's first-spoken-opening expectation remains unproven.

Merge readiness

✅ Ready for maintainer review

Keep this PR: it repairs a current relay startup defect with a focused change. No blocking code defect was found, but the required CI gate remains unsatisfied.

Reviewed head: f93c78c2b18fc132dac0de1360daab13fa29166e

Before merge

None.

Findings

None.

Agent review details

How this fits together

The OpenAI Gateway relay bridges phone, Talk, and Discord audio to GPT-Live, combining WebRTC media with WebSocket session control.

flowchart LR
  A[Phone Talk or Discord] --> B[Gateway relay bridge]
  C[GPT Live sideband] --> B
  B --> D[Readiness callback]
  D --> E[Release buffered audio]
  E --> F[Audio worker]
  F --> G[GPT Live WebRTC peer]
Loading

Technical review

Best possible solution:

Land the focused relay repair after required CI passes and keep the broader phone-call greeting report open.

Do we have a high-confidence way to reproduce the issue?

I did not execute target code; current main visibly releases capture before readiness, and the contributor supplies contrasting current-head and main transport traces.

Is this the best way to solve the issue?

The repair belongs in the shared relay owner and reuses its bounded buffer and deadline without adding configuration or another lifecycle owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4384da1230e1.

Provenance checked

  • Startup microphone capture keeps the original intent (c6b3680: Preserve microphone capture that arrives before asynchronous peer creation, including caller buffers that may be reused.)
  • Early transfer of buffered capture changes intended behavior with a stated reason (2dbdf4f: Consolidate gateway microphone buffering and transfer retained audio when the peer becomes available; this PR explains why transfer must instead follow readiness and greeting context.)
  • Readiness notification keeps the original intent (60c2748: Retain readiness received during answer application and notify consumers once successful startup completes, never after startup failure.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit dc60a94 adds extensions/openai/realtime-quicksilver-gateway-bridge.ts:182 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dc60a9442d5c; files: extensions/openai/realtime-quicksilver-gateway-bridge.ts)
  • Vincent Koc: Raw commit 7ff0e11 adds extensions/openai/realtime-quicksilver-gateway-bridge.ts:251 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7ff0e11c1f95; files: extensions/openai/realtime-quicksilver-gateway-bridge.ts)

PR surface

Source +9, Tests +61. Total +70 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 24 15 +9
Tests 3 74 13 +61
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 98 28 +70

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall readiness starts with the lower of the proof and patch scores. It is capped at 3/6 if the fix is partial, the change offers little benefit, a product decision is still open, or the PR reverses an earlier decision without saying why. ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (6 earlier review cycles)
  • reviewed 2026-10-04T22:09:17.508Z sha 275620724e2c1c1d600aa0d1206a31694b09be7a :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-04T22:42:47.265Z sha 472f4550db4835f3d101d61ffbbd86dbbe29b8a8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-04T22:49:03.241Z sha 472f4550db4835f3d101d61ffbbd86dbbe29b8a8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T19:26:13.869Z sha 415871a57c9639f820f0a4e45cca2bfdf5c340a1 :: blocked before merge. :: none
  • reviewed 2026-10-17T12:00:14.957Z sha 99956a4d6ece19d04f22a2d19189795f132a696e :: blocked before merge. :: none
  • reviewed 2026-11-30T13:14:50.589Z sha f93c78c :: needs real behavior proof before merge. :: none

Reviewed November 30, 2026, 9:29 AM ET / 14:29 UTC (Revision 7).

@jayzhou2309
jayzhou2309 force-pushed the fix/gpt-live-opening-before-caller-audio branch from e56c565 to 472f455 Compare October 4, 2026 22:36
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 4, 2026
@jayzhou2309
jayzhou2309 force-pushed the fix/gpt-live-opening-before-caller-audio branch from 472f455 to 415871a Compare October 11, 2026 19:18
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 11, 2026
@jayzhou2309
jayzhou2309 force-pushed the fix/gpt-live-opening-before-caller-audio branch from 415871a to 99956a4 Compare October 17, 2026 11:42
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Oct 17, 2026
@jayzhou2309
jayzhou2309 force-pushed the fix/gpt-live-opening-before-caller-audio branch 2 times, most recently from 0c6503e to 7e9c1cb Compare October 29, 2026 10:04
The audio pipeline test expected the bridge to hand its retained caller
audio to the WebRTC peer as soon as the peer existed. The bridge now
holds that audio until the Live sideband reports session.started, so
the opening context reaches the model first. Emit session.started in the
test and check the bridge still owns the buffer before it.
The relay now holds WebRTC caller audio until session.started, but the
WebRTC connect resolves without waiting for that event. When the
sideband never reports session.started, connect() resolves and the
caller stays muted until close or the session TTL. Expect connect() to
time out instead and release the held audio.
The relay holds WebRTC caller audio until session.started so the
opening context reaches the model first. WebRTC connect did not wait
for that event, so when it never arrived connect() still resolved and
the caller stayed muted until close or the session TTL.

Wait for session.started inside the connect deadline, as the direct
transport already does. A missing start now rejects connect() with a
TimeoutError and releases the held audio. Both transports now observe
readiness before connect completes, so onReady fires and held audio is
released in one place, and the session.started handler no longer
calls onReady itself.

Tests that resolved a WebRTC connect without session.started now start
the session during connect, the way the provider does.
@jayzhou2309
jayzhou2309 force-pushed the fix/gpt-live-opening-before-caller-audio branch from 7e9c1cb to f93c78c Compare November 30, 2026 13:04
@jayzhou2309

Copy link
Copy Markdown
Contributor Author

Updated: rebased onto main c24097e, new head f93c78c. Two main changes conflicted. #190466 (60c2748) changed onSessionStarted in realtime-quicksilver-gateway-bridge.ts to defer onReady until startup succeeds, and #189029 (c6ad0a9) changed the captured-length check in realtime-quicksilver-gateway-audio.test.ts. The resolution keeps main's deferred onReady and main's assertion. Held caller audio is released right after onReady, on both paths that call it.

Fixed in f93c78c. The missed-start path was real, because WebRTC connect never waited for session.started. It now waits for that event inside the existing 30 s connect deadline, the same way the direct transport does. The wait is at extensions/openai/realtime-quicksilver-gateway-bridge.ts:359, and the direct transport's wait is at :282. If the start never arrives, connect() rejects with a TimeoutError and the bridge releases the held audio with the rest of the session. The consumers already handle a rejected connect(). Talk reports a connect error, voice-call closes the media stream with 1011, and Discord hands the error to its speaker failure handler or to its own caller. None of them needs connect() to resolve before the session starts. A session.started that arrives while the answer is still being applied is kept, as #190466 intended. onReady and the audio release then run once when connect completes, at :236.

  • Red first. 3223ec6 adds fails the connection and drops held caller audio when the session never starts at extensions/openai/realtime-quicksilver-gateway-bridge.test.ts:250. On 3223ec6, which is the rebased PR without the fix, it fails with promise resolved "undefined" instead of rejecting (1 failed, 14 passed). On f93c78c it passes. connect() rejects with TimeoutError after the answer is applied, onReady never fires, the peer is closed, and the bridge neither holds nor sends any caller audio.
  • The ordering test at :221 now starts the session while the answer is still being applied, and caller audio arrives in that window. With main's bridge file both tests fail (2 failed, 13 passed). The ordering test sees audio:0102 and audio:0304 reach the peer before session.context.append. A mutant that gates sendAudio on ready instead of connected also fails it (1 failed, 14 passed).
  • Five existing tests resolved a WebRTC connect without session.started. Three are in the gateway-bridge file, one is the webrtc case of realtime-quicksilver-gateway-audio.test.ts, and one is the retained-audio test in realtime-quicksilver-media.runtime.test.ts. They now start the session during connect, the way the provider does.
  • f93c78c passes all 39 non-live extensions/openai/realtime-*.test.ts files (450 tests). It also passes voice-call realtime-handler and realtime-handler.lifecycle, src/talk/session-runtime, src/gateway/talk/relay/index, and Discord realtime-speaker-sessions (5 files, 220 tests). tsgo for tsconfig.extensions.json and test/tsconfig/tsconfig.extensions.test.json, oxfmt --check, oxlint, and git diff --check are clean.
  • Not verified. No real GPT-Live session or carrier call ran, so the time the provider takes to send session.started in production is not measured. check-changed and the loopback WebRTC proof in the PR body were not rerun on this head.

@clawsweeper re-review

🤖 Written and posted by an AI agent (Claude Code) on behalf of @jayzhou2309.

@clawsweeper

clawsweeper Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Nov 30, 2026
@jayzhou2309

Copy link
Copy Markdown
Contributor Author

Updated: the PR body's "Real behavior proof" section now holds a current-head run through the voice-call phone-call controller and the bridge's worker-thread audio facade, with the same harness run against main's bridge for contrast.

  • Inbound call, where voice-call sends the greeting on ready: on f93c78c, 0 caller-speech RTP packets reached the GPT-Live WebRTC peer before session.started or the greeting's session.context.append, in 3 of 3 runs. The held speech followed the greeting 13-16 ms later. With main fac490e's bridge, 31 packets arrived before both, in 3 of 3 runs.
  • Outbound call with an opening line: the opening is in the call-creation instructions on both builds, and no greeting context is sent. Caller speech before session.started went from 31 packets to 0.
  • Session that never starts: on this head connect() rejects with TimeoutError at 30.1 s, voice-call ends the call with error and closes the stream with 1011 Failed to connect, and no caller speech reaches the provider. On main, connect() resolves at 232 ms, all 49 speech packets go into the unstarted session, and the call is still open at 40 s.
  • Real: RealtimeCallHandler with a real CallManager, the OpenAI provider plugin and OpenAIQuicksilverGatewayBridge on gpt-live-1-codex with ChatGPT auth resolution, and the default worker-facade peer. Each timeline logs the peer's audio worker thread. Faked: GPT-Live (a local call endpoint, sideband server and werift peer), the carrier (Twilio media-stream messages from a local WebSocket client, with FakeProvider for the REST API), and the ChatGPT token.
  • Not shown: a real GPT-Live session, a real carrier call, or a running Gateway process. The physical-call report in [voice-call] GPT-Live outbound calls: the callee's "hello" reaches the model before the opening line (double or invented greetings) — #85846 fixed for OpenAI Realtime only #164979 is not shown fixed, so the body now says Related: #164979 instead of Closes.

@clawsweeper re-review

🤖 Written and posted by an AI agent (Claude Code) on behalf of @jayzhou2309.

@clawsweeper

clawsweeper Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 30, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: openai P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant