{"version":3,"file":"realtimeSession.mjs","names":["WSWebSocket"],"sources":["../src/realtimeSession.ts"],"sourcesContent":["/**\n * OpenAI Realtime speech-to-speech over `wss://api.openai.com/v1/realtime`.\n *\n * The WS upgrade needs an `Authorization: Bearer` header, which the browser\n * `WebSocket` API cannot set, so this module uses the `ws` peer dep. No\n * `OpenAI-Beta` header: that dialect was shut down 2026-05-12.\n */\nimport {\n  Cause,\n  Clock,\n  DateTime,\n  Duration,\n  Effect,\n  Match,\n  Option,\n  Pull,\n  Queue,\n  Redacted,\n  Ref,\n  Result,\n  Schema,\n  type Scope,\n  Stream,\n} from \"effect\"\nimport { Base64 } from \"effect/encoding\"\nimport * as Socket from \"effect/socket/Socket\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport type { AudioFormat } from \"@effect-uai/core/Audio\"\nimport {\n  type CommonSessionRequest,\n  RealtimeEvent,\n  type RealtimeInput,\n} from \"@effect-uai/core/Realtime\"\nimport type { ToolCallOutput } from \"@effect-uai/core/Items\"\nimport type { RealtimeSessionHandle } from \"@effect-uai/core/RealtimeSession\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport * as ToolOutput from \"@effect-uai/core/ToolOutput\"\nimport * as WebSocketSession from \"@effect-uai/core/WebSocketSession\"\nimport { WebSocket as WSWebSocket } from \"ws\"\nimport type { OpenAIRealtimeModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\n\nconst PROVIDER = \"openai\"\n\n// A realtime tool output is one string: text and JSON joined; media fails.\nconst toolOutputString = (output: ToolCallOutput): Effect.Effect<string, AiError.Unsupported> =>\n  Option.match(ToolOutput.text(output.output), {\n    onSome: Effect.succeed,\n    onNone: () =>\n      Effect.fail(\n        new AiError.Unsupported({\n          provider: PROVIDER,\n          capability: \"tool_output_media\",\n          reason: \"Realtime tool outputs carry text only.\",\n        }),\n      ),\n  })\n\n/** `baseUrl` plus `headers` are what make a compatible gateway reachable. */\nexport type Config = {\n  readonly apiKey: Redacted.Redacted\n  readonly baseUrl?: string\n  readonly region?: OpenAiRegion\n  readonly headers?: Record<string, string>\n  /**\n   * Build the socket yourself, for a proxy or an in-memory transport. The\n   * default attaches the bearer token through the `ws` package.\n   */\n  readonly webSocket?: Socket.WebSocketConstructor[\"Service\"]\n}\n\n/**\n * OpenAI-typed session request. Everything past `CommonSessionRequest` is\n * provider-shaped and has no equivalent on other providers.\n */\nexport type OpenAIRealtimeRequest = Omit<CommonSessionRequest, \"model\" | \"resume\"> & {\n  readonly model: OpenAIRealtimeModel\n  /** Replaces the plain `turnDetection` switch when you need the knobs. */\n  readonly turnDetectionConfig?:\n    | {\n        readonly type: \"server_vad\"\n        readonly threshold?: number\n        readonly prefixPaddingMs?: number\n        readonly silenceDurationMs?: number\n        readonly idleTimeoutMs?: number\n        readonly createResponse?: boolean\n        readonly interruptResponse?: boolean\n      }\n    | {\n        readonly type: \"semantic_vad\"\n        readonly eagerness?: \"low\" | \"medium\" | \"high\" | \"auto\"\n        readonly createResponse?: boolean\n        readonly interruptResponse?: boolean\n      }\n  readonly noiseReduction?: \"near_field\" | \"far_field\"\n  readonly truncation?:\n    | \"auto\"\n    | \"disabled\"\n    | { readonly type: \"retention_ratio\"; readonly retentionRatio: number }\n  readonly reasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\"\n  readonly maxOutputTokens?: number | \"inf\"\n  readonly speed?: number\n  /** `\"text\"` turns the session into a text-only responder. One or the other. */\n  readonly outputModalities?: \"audio\" | \"text\"\n  readonly transcriptionModel?: string\n}\n\n// ---------------------------------------------------------------------------\n// AudioFormat -> `audio.{input,output}.format`\n// ---------------------------------------------------------------------------\n\ntype WireFormat =\n  | { readonly type: \"audio/pcm\"; readonly rate: 24000 }\n  | { readonly type: \"audio/pcmu\" }\n  | { readonly type: \"audio/pcma\" }\n\nconst unsupportedFormat = (format: AudioFormat, field: string) =>\n  new AiError.Unsupported({\n    provider: PROVIDER,\n    capability: field,\n    reason: `OpenAI Realtime accepts pcm_s16le @ 24000, pcm_mulaw @ 8000, or pcm_alaw @ 8000 only. Got ${JSON.stringify(format)}.`,\n  })\n\nconst formatToWire = (\n  field: string,\n): ((format: AudioFormat) => Effect.Effect<WireFormat, AiError.AiError>) =>\n  Match.type<AudioFormat>().pipe(\n    Match.when({ container: \"raw\", encoding: \"pcm_s16le\", sampleRate: 24000 }, () =>\n      Effect.succeed<WireFormat>({ type: \"audio/pcm\", rate: 24000 }),\n    ),\n    Match.when({ container: \"raw\", encoding: \"pcm_mulaw\", sampleRate: 8000 }, () =>\n      Effect.succeed<WireFormat>({ type: \"audio/pcmu\" }),\n    ),\n    Match.when({ container: \"raw\", encoding: \"pcm_alaw\", sampleRate: 8000 }, () =>\n      Effect.succeed<WireFormat>({ type: \"audio/pcma\" }),\n    ),\n    Match.orElse((f) => Effect.fail(unsupportedFormat(f, field))),\n  )\n\n// ---------------------------------------------------------------------------\n// Client frames\n// ---------------------------------------------------------------------------\n\nconst toolToWire = (tool: ToolDescriptor) => ({\n  type: \"function\",\n  name: tool.name,\n  description: tool.description,\n  parameters: tool.inputSchema,\n})\n\nconst turnDetectionToWire = (request: OpenAIRealtimeRequest) =>\n  Match.value(request.turnDetectionConfig).pipe(\n    Match.when({ type: \"server_vad\" }, (c) => ({\n      type: \"server_vad\" as const,\n      ...(c.threshold !== undefined && { threshold: c.threshold }),\n      ...(c.prefixPaddingMs !== undefined && { prefix_padding_ms: c.prefixPaddingMs }),\n      ...(c.silenceDurationMs !== undefined && { silence_duration_ms: c.silenceDurationMs }),\n      ...(c.idleTimeoutMs !== undefined && { idle_timeout_ms: c.idleTimeoutMs }),\n      ...(c.createResponse !== undefined && { create_response: c.createResponse }),\n      ...(c.interruptResponse !== undefined && { interrupt_response: c.interruptResponse }),\n    })),\n    Match.when({ type: \"semantic_vad\" }, (c) => ({\n      type: \"semantic_vad\" as const,\n      ...(c.eagerness !== undefined && { eagerness: c.eagerness }),\n      ...(c.createResponse !== undefined && { create_response: c.createResponse }),\n      ...(c.interruptResponse !== undefined && { interrupt_response: c.interruptResponse }),\n    })),\n    // No explicit config: `manual` means no turn detection at all.\n    Match.orElse(() =>\n      request.turnDetection === \"manual\" ? null : ({ type: \"server_vad\" } as const),\n    ),\n  )\n\nconst truncationToWire = (truncation: OpenAIRealtimeRequest[\"truncation\"]) =>\n  typeof truncation === \"object\"\n    ? { type: \"retention_ratio\", retention_ratio: truncation.retentionRatio }\n    : truncation\n\nconst sessionUpdateFrame = (\n  request: OpenAIRealtimeRequest,\n  formats: { readonly input: WireFormat; readonly output: WireFormat },\n): string =>\n  JSON.stringify({\n    type: \"session.update\",\n    session: {\n      type: \"realtime\",\n      ...(request.instructions !== undefined && { instructions: request.instructions }),\n      ...(request.outputModalities !== undefined && {\n        output_modalities: [request.outputModalities],\n      }),\n      audio: {\n        input: {\n          format: formats.input,\n          turn_detection: turnDetectionToWire(request),\n          ...(request.noiseReduction !== undefined && {\n            noise_reduction: { type: request.noiseReduction },\n          }),\n          ...(request.transcribeInput !== false && {\n            transcription: { model: request.transcriptionModel ?? \"gpt-live-transcribe\" },\n          }),\n        },\n        output: {\n          format: formats.output,\n          ...(request.voiceId !== undefined && { voice: request.voiceId }),\n          ...(request.speed !== undefined && { speed: request.speed }),\n        },\n      },\n      ...(request.tools !== undefined && { tools: request.tools.map(toolToWire) }),\n      ...(request.truncation !== undefined && {\n        truncation: truncationToWire(request.truncation),\n      }),\n      ...(request.reasoningEffort !== undefined && {\n        reasoning: { effort: request.reasoningEffort },\n      }),\n      ...(request.maxOutputTokens !== undefined && { max_output_tokens: request.maxOutputTokens }),\n    },\n  })\n\nconst historyItemFrame = (item: unknown): string =>\n  JSON.stringify({ type: \"conversation.item.create\", item })\n\nconst textItemFrame = (text: string, role: \"user\" | \"system\"): string =>\n  JSON.stringify({\n    type: \"conversation.item.create\",\n    item: { type: \"message\", role, content: [{ type: \"input_text\", text }] },\n  })\n\nconst responseCreateFrame = JSON.stringify({ type: \"response.create\" })\n\n// ---------------------------------------------------------------------------\n// Server frames\n// ---------------------------------------------------------------------------\n\nconst Session = Schema.Struct({\n  id: Schema.optional(Schema.String),\n  expires_at: Schema.optional(Schema.Number),\n})\n\nconst Usage = Schema.Struct({\n  input_tokens: Schema.optional(Schema.Number),\n  output_tokens: Schema.optional(Schema.Number),\n  total_tokens: Schema.optional(Schema.Number),\n})\n\nconst Response = Schema.Struct({\n  id: Schema.String,\n  status: Schema.optional(Schema.String),\n  status_details: Schema.optional(\n    Schema.NullOr(Schema.Struct({ reason: Schema.optional(Schema.NullOr(Schema.String)) })),\n  ),\n  usage: Schema.optional(Schema.NullOr(Usage)),\n})\n\nconst OutputItem = Schema.Struct({\n  id: Schema.optional(Schema.String),\n  type: Schema.optional(Schema.String),\n  call_id: Schema.optional(Schema.String),\n  name: Schema.optional(Schema.String),\n})\n\nconst ServerEvent = Schema.Union([\n  Schema.Struct({ type: Schema.Literal(\"session.created\"), session: Session }),\n  Schema.Struct({ type: Schema.Literal(\"session.updated\") }),\n  Schema.Struct({ type: Schema.Literal(\"response.created\"), response: Response }),\n  Schema.Struct({ type: Schema.Literal(\"response.done\"), response: Response }),\n  Schema.Struct({\n    type: Schema.Literal(\"response.output_item.added\"),\n    response_id: Schema.optional(Schema.String),\n    item: OutputItem,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"response.output_audio.delta\"),\n    response_id: Schema.String,\n    delta: Schema.String,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"response.output_audio_transcript.delta\"),\n    response_id: Schema.String,\n    delta: Schema.String,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"response.output_text.delta\"),\n    response_id: Schema.String,\n    delta: Schema.String,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"response.function_call_arguments.done\"),\n    response_id: Schema.optional(Schema.String),\n    call_id: Schema.String,\n    name: Schema.optional(Schema.String),\n    arguments: Schema.String,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"conversation.item.input_audio_transcription.delta\"),\n    delta: Schema.String,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"conversation.item.input_audio_transcription.completed\"),\n    transcript: Schema.String,\n  }),\n  Schema.Struct({ type: Schema.Literal(\"input_audio_buffer.speech_started\") }),\n  Schema.Struct({ type: Schema.Literal(\"input_audio_buffer.speech_stopped\") }),\n  Schema.Struct({\n    type: Schema.Literal(\"error\"),\n    error: Schema.Struct({\n      type: Schema.optional(Schema.String),\n      code: Schema.optional(Schema.NullOr(Schema.String)),\n      message: Schema.String,\n    }),\n  }),\n])\n\ntype ServerEvent = typeof ServerEvent.Type\n\n// ---------------------------------------------------------------------------\n// Session state\n// ---------------------------------------------------------------------------\n\ntype SessionState = {\n  /** The response currently generating, if any. */\n  readonly responseId: string | undefined\n  /**\n   * The most recent assistant audio item, and the target of a truncate. It\n   * outlives its response: the model generates faster than real time, so a\n   * listener is often still hearing an answer the server has finished.\n   */\n  readonly itemId: string | undefined\n  /** `call_id` to tool name, so a `.done` frame can name its call. */\n  readonly callNames: Readonly<Record<string, string>>\n  /** Calls of the current response that have not been answered. */\n  readonly pendingCalls: ReadonlyArray<string>\n  readonly interrupted: boolean\n  /** A tool result landed mid response; ask for its turn once that one ends. */\n  readonly resumeWhenIdle: boolean\n  /** When the server drops the session. Converted off the wire's Unix seconds. */\n  readonly expiresAt: DateTime.Utc | undefined\n}\n\nconst initialState: SessionState = {\n  responseId: undefined,\n  itemId: undefined,\n  callNames: {},\n  pendingCalls: [],\n  interrupted: false,\n  resumeWhenIdle: false,\n  expiresAt: undefined,\n}\n\n/**\n * Only one response may generate at a time, so a turn asked for while one is\n * running waits for it. Every transition below is a single `Ref.modify`: the\n * pump fiber and the caller's `send` both touch this state concurrently.\n */\ntype Turn = \"create\" | \"defer\"\n\nconst turnFor = (s: SessionState): [Turn, SessionState] =>\n  s.responseId === undefined ? [\"create\", s] : [\"defer\", { ...s, resumeWhenIdle: true }]\n\nconst requestTurn = (state: Ref.Ref<SessionState>): Effect.Effect<Turn> =>\n  Ref.modify(state, turnFor)\n\nconst answerCall = (state: Ref.Ref<SessionState>, callId: string): Effect.Effect<Turn> =>\n  Ref.modify(state, (s) => {\n    const [turn, next] = turnFor(s)\n    return [turn, { ...next, pendingCalls: next.pendingCalls.filter((id) => id !== callId) }]\n  })\n\nconst closeResponse = (\n  state: Ref.Ref<SessionState>,\n): Effect.Effect<{ readonly resume: boolean; readonly pendingCalls: ReadonlyArray<string> }> =>\n  Ref.modify(state, (s) => [\n    { resume: s.resumeWhenIdle, pendingCalls: s.pendingCalls },\n    { ...s, responseId: undefined, pendingCalls: [], interrupted: false, resumeWhenIdle: false },\n  ])\n\n/** The response whose playback must stop, or `undefined` if already reported. */\nconst beginBargeIn = (state: Ref.Ref<SessionState>): Effect.Effect<string | undefined> =>\n  Ref.modify(state, (s): [string | undefined, SessionState] =>\n    s.responseId !== undefined && !s.interrupted\n      ? [s.responseId, { ...s, interrupted: true }]\n      : [undefined, s],\n  )\n\nconst doneReason = (\n  response: typeof Response.Type,\n): \"complete\" | \"interrupted\" | \"cancelled\" | \"error\" =>\n  Match.value(response.status).pipe(\n    Match.when(\"completed\", () => \"complete\" as const),\n    Match.when(\"cancelled\", () =>\n      response.status_details?.reason === \"turn_detected\"\n        ? (\"interrupted\" as const)\n        : (\"cancelled\" as const),\n    ),\n    Match.orElse(() => \"error\" as const),\n  )\n\nconst usageOf = (response: typeof Response.Type) =>\n  response.usage == null ? undefined : { ...response.usage }\n\nconst decodeAudio = (b64: string): Effect.Effect<Uint8Array, AiError.AiError> =>\n  Result.match(Base64.decode(b64), {\n    onSuccess: Effect.succeed,\n    onFailure: (cause) =>\n      Effect.fail(\n        new AiError.GenerationFailed({\n          provider: PROVIDER,\n          raw: { message: \"audio delta base64 decode failed\", cause },\n        }),\n      ),\n  })\n\n/**\n * One server frame to the events it produces, updating the response\n * bookkeeping. Takes `send` because finishing a response is also when a\n * deferred follow-up turn becomes legal to ask for.\n */\nconst toEvents = (\n  send: (frame: string) => Effect.Effect<void, AiError.AiError>,\n  state: Ref.Ref<SessionState>,\n  frame: ServerEvent,\n): Effect.Effect<ReadonlyArray<RealtimeEvent>, AiError.AiError> =>\n  Match.value(frame).pipe(\n    Match.when({ type: \"session.created\" }, (f) =>\n      Ref.update(state, (s) => ({\n        ...s,\n        expiresAt:\n          f.session.expires_at === undefined\n            ? undefined\n            : DateTime.makeUnsafe(f.session.expires_at * 1000),\n      })).pipe(Effect.as([])),\n    ),\n    Match.when({ type: \"session.updated\" }, () => Effect.succeed([])),\n    Match.when({ type: \"response.created\" }, (f) =>\n      Ref.update(state, (s) => ({\n        ...s,\n        responseId: f.response.id,\n        pendingCalls: [],\n        interrupted: false,\n      })).pipe(Effect.as([RealtimeEvent.ResponseStarted({ responseId: f.response.id })])),\n    ),\n    Match.when({ type: \"response.output_item.added\" }, (f) =>\n      Ref.update(state, (s) => ({\n        ...s,\n        // Only an assistant message can be truncated, so only it is tracked.\n        ...(f.item.type === \"message\" && f.item.id !== undefined && { itemId: f.item.id }),\n        ...(f.item.type === \"function_call\" &&\n          f.item.call_id !== undefined && {\n            callNames: { ...s.callNames, [f.item.call_id]: f.item.name ?? \"\" },\n            pendingCalls: [...s.pendingCalls, f.item.call_id],\n          }),\n      })).pipe(Effect.as([])),\n    ),\n    Match.when({ type: \"response.output_audio.delta\" }, (f) =>\n      Effect.map(decodeAudio(f.delta), (bytes) => [\n        RealtimeEvent.AudioDelta({ responseId: f.response_id, bytes }),\n      ]),\n    ),\n    Match.whenOr(\n      { type: \"response.output_audio_transcript.delta\" },\n      { type: \"response.output_text.delta\" },\n      (f) =>\n        Effect.succeed([\n          RealtimeEvent.OutputTranscriptDelta({ responseId: f.response_id, text: f.delta }),\n        ]),\n    ),\n    Match.when({ type: \"response.function_call_arguments.done\" }, (f) =>\n      Effect.gen(function* () {\n        const s = yield* Ref.get(state)\n        const name = f.name ?? s.callNames[f.call_id] ?? \"\"\n        return [\n          RealtimeEvent.ToolCall({\n            responseId: f.response_id ?? s.responseId ?? \"\",\n            call: {\n              type: \"function_call\",\n              call_id: f.call_id,\n              name,\n              arguments: f.arguments,\n              providerData: undefined,\n            },\n          }),\n        ]\n      }),\n    ),\n    Match.when({ type: \"response.done\" }, (f) =>\n      Effect.gen(function* () {\n        const reason = doneReason(f.response)\n        const cancelled = reason === \"interrupted\" || reason === \"cancelled\"\n        const closed = yield* closeResponse(state)\n        // An input answered while this response was running never got its turn.\n        if (closed.resume) yield* send(responseCreateFrame)\n        const usage = usageOf(f.response)\n        return [\n          // Calls of a cancelled response will never be answered.\n          ...(cancelled && closed.pendingCalls.length > 0\n            ? [RealtimeEvent.ToolCallCancelled({ callIds: closed.pendingCalls })]\n            : []),\n          RealtimeEvent.ResponseDone({\n            responseId: f.response.id,\n            reason,\n            ...(usage !== undefined && { usage }),\n          }),\n        ]\n      }),\n    ),\n    Match.when({ type: \"input_audio_buffer.speech_started\" }, () =>\n      // Barge-in: the server cancels the response, but the client owns\n      // playback and has to stop it now rather than at `response.done`.\n      Effect.map(beginBargeIn(state), (responseId) => [\n        RealtimeEvent.SpeechStarted(),\n        ...(responseId === undefined ? [] : [RealtimeEvent.Interrupted({ responseId })]),\n      ]),\n    ),\n    Match.when({ type: \"input_audio_buffer.speech_stopped\" }, () =>\n      Effect.succeed([RealtimeEvent.SpeechStopped()]),\n    ),\n    Match.when({ type: \"conversation.item.input_audio_transcription.delta\" }, (f) =>\n      Effect.succeed([RealtimeEvent.InputTranscript({ text: f.delta, final: false })]),\n    ),\n    Match.when({ type: \"conversation.item.input_audio_transcription.completed\" }, (f) =>\n      Effect.succeed([RealtimeEvent.InputTranscript({ text: f.transcript, final: true })]),\n    ),\n    Match.when({ type: \"error\" }, (f) =>\n      Effect.succeed([\n        RealtimeEvent.Error({\n          ...(f.error.code != null && { code: f.error.code }),\n          message: f.error.message,\n        }),\n      ]),\n    ),\n    Match.exhaustive,\n  )\n\n// ---------------------------------------------------------------------------\n// Input handling\n// ---------------------------------------------------------------------------\n\nconst droppedActivity = (field: string) =>\n  Capabilities.warnDropped({\n    provider: PROVIDER,\n    capability: \"manualTurns\",\n    field,\n    reason: \"The session uses server turn detection; activity boundaries are the server's.\",\n  })\n\nconst handleInput = (\n  send: (frame: string) => Effect.Effect<void, AiError.AiError>,\n  state: Ref.Ref<SessionState>,\n  manual: boolean,\n  input: RealtimeInput,\n): Effect.Effect<void, AiError.AiError> =>\n  Match.value(input).pipe(\n    Match.tag(\"Audio\", (i) =>\n      send(\n        JSON.stringify({\n          type: \"input_audio_buffer.append\",\n          audio: Base64.encode(i.bytes),\n        }),\n      ),\n    ),\n    Match.tag(\"Text\", (i) =>\n      Effect.gen(function* () {\n        yield* send(textItemFrame(i.text, i.role ?? \"user\"))\n        // `response.create` during an active response is a server error, so\n        // the done handler asks for this turn instead.\n        const turn = yield* requestTurn(state)\n        if (turn === \"create\") yield* send(responseCreateFrame)\n      }),\n    ),\n    Match.tag(\"ToolResult\", (i) =>\n      Effect.gen(function* () {\n        const s = yield* Ref.get(state)\n        if (!(i.output.call_id in s.callNames)) {\n          return yield* Effect.fail(\n            new AiError.InvalidRequest({\n              provider: PROVIDER,\n              raw: `no tool call ${i.output.call_id} in this session`,\n            }),\n          )\n        }\n        const output = yield* toolOutputString(i.output)\n        yield* send(\n          JSON.stringify({\n            type: \"conversation.item.create\",\n            item: { type: \"function_call_output\", call_id: i.output.call_id, output },\n          }),\n        )\n        // The adapter resumes generation, so the caller never sends this. A\n        // slow tool often answers after the user has spoken again, so a result\n        // that lands mid response waits for that one to finish.\n        const turn = yield* answerCall(state, i.output.call_id)\n        if (turn === \"create\") yield* send(responseCreateFrame)\n      }),\n    ),\n    Match.tag(\"Interrupt\", () => send(JSON.stringify({ type: \"response.cancel\" }))),\n    Match.tag(\"VideoFrame\", () =>\n      Effect.fail(\n        new AiError.Unsupported({\n          provider: PROVIDER,\n          capability: \"videoInput\",\n          reason: \"OpenAI Realtime takes still images as conversation items, not video frames.\",\n        }),\n      ),\n    ),\n    Match.tag(\"ActivityStart\", () => (manual ? Effect.void : droppedActivity(\"ActivityStart\"))),\n    Match.tag(\"ActivityEnd\", () =>\n      manual\n        ? Effect.andThen(\n            send(JSON.stringify({ type: \"input_audio_buffer.commit\" })),\n            send(responseCreateFrame),\n          )\n        : droppedActivity(\"ActivityEnd\"),\n    ),\n    Match.tag(\"PlaybackPosition\", (i) =>\n      Effect.gen(function* () {\n        const s = yield* Ref.get(state)\n        if (s.itemId === undefined) {\n          return yield* Capabilities.warnDropped({\n            provider: PROVIDER,\n            capability: \"truncate\",\n            field: \"PlaybackPosition\",\n            reason: \"No assistant audio item is in flight to truncate.\",\n          })\n        }\n        yield* send(\n          JSON.stringify({\n            type: \"conversation.item.truncate\",\n            item_id: s.itemId,\n            content_index: 0,\n            audio_end_ms: Math.max(0, Math.round(i.playedMs)),\n          }),\n        )\n      }),\n    ),\n    Match.exhaustive,\n  )\n\n// ---------------------------------------------------------------------------\n// Connection\n// ---------------------------------------------------------------------------\n\n/**\n * `resume` is a Gemini handle. The typed request omits it, so this only ever\n * fires for a caller coming through the generic tag, where it would otherwise\n * be cast away and a session the caller believes it resumed starts blank.\n */\nexport const refuseResume = (\n  request: CommonSessionRequest,\n): Effect.Effect<void, AiError.AiError> =>\n  request.resume === undefined\n    ? Effect.void\n    : Effect.fail(\n        new AiError.Unsupported({\n          provider: PROVIDER,\n          capability: \"resume\",\n          reason: \"OpenAI Realtime has no session resumption. A dropped session starts over.\",\n        }),\n      )\n\n/** A query already on `baseUrl`, such as a gateway's API version, is kept. */\nexport const buildWsUrl = (cfg: Config, model: string): string => {\n  const url = new URL(resolveHost(cfg))\n  url.protocol = url.protocol === \"http:\" ? \"ws:\" : \"wss:\"\n  url.pathname = `${url.pathname.replace(/\\/$/, \"\")}/realtime`\n  url.searchParams.set(\"model\", model)\n  return url.toString()\n}\n\n// Single contained cast: `@types/ws` declares its WebSocket extending Node's\n// EventEmitter while `globalThis.WebSocket` extends EventTarget. The surface\n// Effect's Socket reads is identical at runtime.\nconst authedWsConstructor =\n  (cfg: Config): Socket.WebSocketConstructor[\"Service\"] =>\n  (url) =>\n    new WSWebSocket(url, undefined, {\n      headers: {\n        Authorization: `Bearer ${Redacted.value(cfg.apiKey)}`,\n        ...cfg.headers,\n      },\n    }) as unknown as globalThis.WebSocket\n\n/** Drop frames until the handshake ack arrives, feeding state on the way. */\nconst awaitAck = (\n  session: WebSocketSession.WebSocketSession<ServerEvent>,\n  state: Ref.Ref<SessionState>,\n  tag: \"session.created\" | \"session.updated\",\n): Effect.Effect<void, AiError.AiError> =>\n  Queue.take(session.frames).pipe(\n    // A clean close before the ack is still a failed handshake.\n    Effect.catchCause((cause) =>\n      Pull.isDoneCause(cause)\n        ? Effect.fail(\n            new AiError.Unavailable({\n              provider: PROVIDER,\n              raw: \"the socket closed during the handshake\",\n            }),\n          )\n        : Effect.failCause(cause as Cause.Cause<AiError.AiError>),\n    ),\n    Effect.flatMap((frame) =>\n      Effect.andThen(\n        toEvents(session.send, state, frame),\n        frame.type === tag ? Effect.void : awaitAck(session, state, tag),\n      ),\n    ),\n  )\n\n/** 60 seconds of warning before the server's hard session limit. */\nconst SESSION_ENDING_LEAD = Duration.seconds(60)\n\nconst sessionEndingTimer = (\n  state: Ref.Ref<SessionState>,\n  out: Queue.Queue<RealtimeEvent, AiError.AiError | Cause.Done>,\n): Effect.Effect<void> =>\n  Effect.gen(function* () {\n    const expiresAt = (yield* Ref.get(state)).expiresAt\n    if (expiresAt === undefined) return\n    const now = yield* Clock.currentTimeMillis\n    const leadMs = Duration.toMillis(SESSION_ENDING_LEAD)\n    const waitMs = DateTime.toEpochMillis(expiresAt) - leadMs - now\n    if (waitMs > 0) yield* Effect.sleep(Duration.millis(waitMs))\n    yield* Queue.offer(out, RealtimeEvent.SessionEnding({ timeLeft: SESSION_ENDING_LEAD })).pipe(\n      Effect.ignore,\n    )\n  })\n\nexport const openSession =\n  (cfg: Config) =>\n  (\n    request: OpenAIRealtimeRequest,\n  ): Effect.Effect<RealtimeSessionHandle, AiError.AiError, Scope.Scope> =>\n    Effect.gen(function* () {\n      const formats = {\n        input: yield* formatToWire(\"inputFormat\")(request.inputFormat),\n        output: yield* formatToWire(\"outputFormat\")(request.outputFormat),\n      }\n      const session = yield* WebSocketSession.open({\n        url: buildWsUrl(cfg, request.model),\n        provider: PROVIDER,\n        schema: ServerEvent,\n        openTimeout: Duration.seconds(30),\n      }).pipe(\n        Effect.provideService(\n          Socket.WebSocketConstructor,\n          cfg.webSocket ?? authedWsConstructor(cfg),\n        ),\n      )\n\n      const state = yield* Ref.make(initialState)\n      // `open` resolves only once the server has accepted the configuration.\n      yield* awaitAck(session, state, \"session.created\")\n      yield* session.send(sessionUpdateFrame(request, formats))\n      yield* awaitAck(session, state, \"session.updated\")\n\n      yield* Effect.forEach(request.history ?? [], (item) => session.send(historyItemFrame(item)), {\n        discard: true,\n      })\n\n      const out = yield* Queue.bounded<RealtimeEvent, AiError.AiError | Cause.Done>(128)\n\n      const pump = Stream.fromQueue(session.frames).pipe(\n        Stream.mapEffect((frame) => toEvents(session.send, state, frame)),\n        Stream.runForEach((events) => Queue.offerAll(out, events)),\n      )\n\n      // A close never synthesizes a `ResponseDone`; a response still in flight\n      // ends the stream as an incomplete turn instead.\n      const finish = (cause: Cause.Cause<AiError.AiError> | undefined) =>\n        Effect.gen(function* () {\n          const { expiresAt, responseId } = yield* Ref.get(state)\n          if (responseId !== undefined) {\n            return yield* Queue.fail(\n              out,\n              new AiError.IncompleteTurn({ raw: cause ?? \"the socket closed mid response\" }),\n            )\n          }\n          const now = yield* Clock.currentTimeMillis\n          // The server drops the socket at the expiry it announced at connect.\n          // Reconnecting works; retrying this session does not.\n          if (expiresAt !== undefined && now >= DateTime.toEpochMillis(expiresAt)) {\n            return yield* Queue.fail(\n              out,\n              new AiError.SessionExpired({\n                provider: PROVIDER,\n                raw: cause ?? \"the socket closed at the expiry the server set at connect\",\n              }),\n            )\n          }\n          return yield* cause !== undefined && Cause.hasFails(cause)\n            ? Queue.failCause(out, cause)\n            : Queue.end(out)\n        })\n\n      yield* pump.pipe(\n        Effect.matchCauseEffect({ onFailure: finish, onSuccess: () => finish(undefined) }),\n        Effect.forkScoped,\n      )\n      yield* Effect.forkScoped(sessionEndingTimer(state, out))\n\n      const manual = request.turnDetection === \"manual\"\n      return {\n        send: (input) => handleInput(session.send, state, manual, input),\n        events: Stream.fromQueue(out),\n      }\n    })\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2CA,MAAM,WAAW;AAGjB,MAAM,oBAAoB,WACxB,OAAO,MAAM,WAAW,KAAK,OAAO,MAAM,GAAG;CAC3C,QAAQ,OAAO;CACf,cACE,OAAO,KACL,IAAI,QAAQ,YAAY;EACtB,UAAU;EACV,YAAY;EACZ,QAAQ;CACV,CAAC,CACH;AACJ,CAAC;AA4DH,MAAM,qBAAqB,QAAqB,UAC9C,IAAI,QAAQ,YAAY;CACtB,UAAU;CACV,YAAY;CACZ,QAAQ,6FAA6F,KAAK,UAAU,MAAM,EAAE;AAC9H,CAAC;AAEH,MAAM,gBACJ,UAEA,MAAM,KAAkB,CAAC,CAAC,KACxB,MAAM,KAAK;CAAE,WAAW;CAAO,UAAU;CAAa,YAAY;AAAM,SACtE,OAAO,QAAoB;CAAE,MAAM;CAAa,MAAM;AAAM,CAAC,CAC/D,GACA,MAAM,KAAK;CAAE,WAAW;CAAO,UAAU;CAAa,YAAY;AAAK,SACrE,OAAO,QAAoB,EAAE,MAAM,aAAa,CAAC,CACnD,GACA,MAAM,KAAK;CAAE,WAAW;CAAO,UAAU;CAAY,YAAY;AAAK,SACpE,OAAO,QAAoB,EAAE,MAAM,aAAa,CAAC,CACnD,GACA,MAAM,QAAQ,MAAM,OAAO,KAAK,kBAAkB,GAAG,KAAK,CAAC,CAAC,CAC9D;AAMF,MAAM,cAAc,UAA0B;CAC5C,MAAM;CACN,MAAM,KAAK;CACX,aAAa,KAAK;CAClB,YAAY,KAAK;AACnB;AAEA,MAAM,uBAAuB,YAC3B,MAAM,MAAM,QAA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