@effect-uai/google 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +11 -2
  2. package/dist/Gemini.d.mts +1 -1
  3. package/dist/GeminiEmbedding.d.mts +1 -1
  4. package/dist/GeminiImageGenerator.d.mts +1 -1
  5. package/dist/GeminiLiveSession.d.mts +17 -0
  6. package/dist/GeminiLiveSession.d.mts.map +1 -0
  7. package/dist/GeminiLiveSession.mjs +26 -0
  8. package/dist/GeminiLiveSession.mjs.map +1 -0
  9. package/dist/GeminiSynthesizer.d.mts +1 -1
  10. package/dist/GeminiSynthesizer.test.mjs +1 -1
  11. package/dist/GoogleDeepResearch.d.mts +1 -1
  12. package/dist/GoogleDeepResearch.test.mjs +1 -1
  13. package/dist/LyriaGenerator.d.mts +1 -1
  14. package/dist/LyriaGenerator.test.mjs +1 -1
  15. package/dist/codec.d.mts +5 -2
  16. package/dist/codec.d.mts.map +1 -1
  17. package/dist/codec.mjs +4 -1
  18. package/dist/codec.mjs.map +1 -1
  19. package/dist/geminiSpeechCodec.test.mjs +1 -1
  20. package/dist/geminiTools.test.mjs +1 -1
  21. package/dist/index.d.mts +3 -2
  22. package/dist/index.mjs +2 -1
  23. package/dist/models-BVSKJwCx.d.mts +87 -0
  24. package/dist/models-BVSKJwCx.d.mts.map +1 -0
  25. package/dist/models.d.mts +2 -75
  26. package/dist/realtimeSession-7HSIjWh4.d.mts +62 -0
  27. package/dist/realtimeSession-7HSIjWh4.d.mts.map +1 -0
  28. package/dist/realtimeSession.d.mts +2 -0
  29. package/dist/realtimeSession.mjs +406 -0
  30. package/dist/realtimeSession.mjs.map +1 -0
  31. package/dist/realtimeSession.test.d.mts +1 -0
  32. package/dist/realtimeSession.test.mjs +505 -0
  33. package/dist/realtimeSession.test.mjs.map +1 -0
  34. package/dist/{test.DNmyFkvJ-N3QqMRwZ.mjs → test.DNmyFkvJ-BPz3G1HS.mjs} +531 -22
  35. package/dist/test.DNmyFkvJ-BPz3G1HS.mjs.map +1 -0
  36. package/package.json +6 -2
  37. package/src/GeminiLiveSession.ts +45 -0
  38. package/src/codec.ts +3 -2
  39. package/src/index.ts +1 -0
  40. package/src/models.ts +19 -0
  41. package/src/realtimeSession.test.ts +415 -0
  42. package/src/realtimeSession.ts +807 -0
  43. package/dist/models.d.mts.map +0 -1
  44. package/dist/test.DNmyFkvJ-N3QqMRwZ.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"realtimeSession.mjs","names":[],"sources":["../src/realtimeSession.ts"],"sourcesContent":["/**\n * Gemini Live speech-to-speech over `BidiGenerateContent`.\n *\n * Auth is a query parameter, so this needs no `ws` package and no headers:\n * the platform `WebSocket` reaches it from Node, Bun, Deno and the browser.\n *\n * Two shapes differ from OpenAI Realtime and drive most of this file. There\n * are no response ids on the wire, so a turn id is minted here and every event\n * of that turn carries it; and there is no truncate op, so a\n * `PlaybackPosition` has nothing to send.\n */\nimport {\n Cause,\n Duration,\n Effect,\n Encoding,\n Match,\n Pull,\n Queue,\n Redacted,\n Ref,\n Result,\n Schema,\n type Scope,\n Stream,\n} from \"effect\"\nimport * as Socket from \"effect/unstable/socket/Socket\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport type { AudioFormat } from \"@effect-uai/core/Audio\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport type { HistoryItem, Usage } from \"@effect-uai/core/Items\"\nimport {\n type CommonSessionRequest,\n RealtimeEvent,\n type RealtimeInput,\n} from \"@effect-uai/core/Realtime\"\nimport type { RealtimeSessionHandle } from \"@effect-uai/core/RealtimeSession\"\nimport * as WebSocketSession from \"@effect-uai/core/WebSocketSession\"\nimport { parsedResponse, toolDescriptorsToTools } from \"./codec.js\"\nimport type { GeminiLiveModel } from \"./models.js\"\n\nconst PROVIDER = \"gemini-live\"\n\nconst DEFAULT_BASE_URL = \"wss://generativelanguage.googleapis.com\"\nconst RPC = \"ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent\"\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n /** Build the socket yourself, for a proxy or an in-memory transport. */\n readonly webSocket?: Socket.WebSocketConstructor[\"Service\"]\n}\n\n/**\n * Gemini-typed session request. Everything past `CommonSessionRequest` is\n * provider-shaped. The configuration is immutable for the connection: changing\n * any of it means opening a new session.\n */\nexport type GeminiLiveRequest = Omit<CommonSessionRequest, \"model\"> & {\n readonly model: GeminiLiveModel\n /** Replaces the plain `turnDetection` switch when you need the knobs. */\n readonly vad?: {\n readonly startSensitivity?: \"high\" | \"low\"\n readonly endSensitivity?: \"high\" | \"low\"\n readonly prefixPaddingMs?: number\n readonly silenceDurationMs?: number\n }\n /** `\"none\"` turns barge-in off. Defaults to interrupting. */\n readonly activityHandling?: \"interrupt\" | \"none\"\n /**\n * When a tool result reaches the model, for the models that keep generating\n * while a tool runs. Defaults to `\"when-idle\"`: the server's own default is\n * to interrupt, which cuts off whatever the model was saying while it\n * waited, including the \"let me look that up\" it just spoke. `\"interrupt\"`\n * is right when the result cannot wait, `\"silent\"` when it is context the\n * model should have rather than something to announce.\n */\n readonly toolScheduling?: \"when-idle\" | \"interrupt\" | \"silent\"\n readonly turnCoverage?: \"activity\" | \"all\" | \"audioActivityAndAllVideo\"\n /** 3.1 only. Higher levels delay the first audio. */\n readonly thinkingLevel?: \"minimal\" | \"low\" | \"medium\" | \"high\"\n readonly mediaResolution?: \"low\" | \"medium\" | \"high\"\n readonly languageCode?: string\n readonly temperature?: number\n readonly maxOutputTokens?: number\n /** What turns an otherwise time-boxed session into an unbounded one. */\n readonly contextCompression?: {\n readonly triggerTokens?: number\n readonly targetTokens?: number\n }\n /** Grounding. Cannot be combined with `tools`; the pair is a 400. */\n readonly googleSearch?: boolean\n /** 2.5 only. */\n readonly proactiveAudio?: boolean\n /** 2.5 only. */\n readonly affectiveDialog?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// AudioFormat -> wire\n// ---------------------------------------------------------------------------\n\n/** Output is 24 kHz whatever the input rate, and cannot be configured. */\nconst OUTPUT_RATE = 24000\n\nconst unsupportedFormat = (format: AudioFormat, field: string, expected: string) =>\n new AiError.Unsupported({\n provider: PROVIDER,\n capability: field,\n reason: `Gemini Live accepts ${expected}. Got ${JSON.stringify(format)}.`,\n })\n\n/** Any rate is accepted on input; 16 kHz is what the model works in. */\nconst inputRate = (format: AudioFormat): Effect.Effect<number, AiError.AiError> =>\n Match.value(format).pipe(\n Match.when({ container: \"raw\", encoding: \"pcm_s16le\", channels: 1 }, (f) =>\n Effect.succeed(f.sampleRate),\n ),\n Match.orElse((f) =>\n Effect.fail(unsupportedFormat(f, \"inputFormat\", \"mono pcm_s16le at any rate\")),\n ),\n )\n\nconst checkOutputFormat = (format: AudioFormat): Effect.Effect<void, AiError.AiError> =>\n Match.value(format).pipe(\n Match.when(\n { container: \"raw\", encoding: \"pcm_s16le\", sampleRate: OUTPUT_RATE, channels: 1 },\n () => Effect.void,\n ),\n Match.orElse((f) =>\n Effect.fail(unsupportedFormat(f, \"outputFormat\", `mono pcm_s16le at ${OUTPUT_RATE}`)),\n ),\n )\n\n// ---------------------------------------------------------------------------\n// Client frames\n// ---------------------------------------------------------------------------\n\nconst SENSITIVITY = { high: \"HIGH\", low: \"LOW\" } as const\n\nconst TURN_COVERAGE = {\n activity: \"TURN_INCLUDES_ONLY_ACTIVITY\",\n all: \"TURN_INCLUDES_ALL_INPUT\",\n audioActivityAndAllVideo: \"TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO\",\n} as const\n\nconst realtimeInputConfig = (request: GeminiLiveRequest) => ({\n automaticActivityDetection: {\n ...(request.turnDetection === \"manual\" && { disabled: true }),\n ...(request.vad?.startSensitivity !== undefined && {\n startOfSpeechSensitivity: `START_SENSITIVITY_${SENSITIVITY[request.vad.startSensitivity]}`,\n }),\n ...(request.vad?.endSensitivity !== undefined && {\n endOfSpeechSensitivity: `END_SENSITIVITY_${SENSITIVITY[request.vad.endSensitivity]}`,\n }),\n ...(request.vad?.prefixPaddingMs !== undefined && {\n prefixPaddingMs: request.vad.prefixPaddingMs,\n }),\n ...(request.vad?.silenceDurationMs !== undefined && {\n silenceDurationMs: request.vad.silenceDurationMs,\n }),\n },\n ...(request.activityHandling !== undefined && {\n activityHandling:\n request.activityHandling === \"none\" ? \"NO_INTERRUPTION\" : \"START_OF_ACTIVITY_INTERRUPTS\",\n }),\n ...(request.turnCoverage !== undefined && { turnCoverage: TURN_COVERAGE[request.turnCoverage] }),\n})\n\nconst generationConfig = (request: GeminiLiveRequest) => ({\n responseModalities: [\"AUDIO\"],\n ...(request.voiceId !== undefined && {\n speechConfig: {\n voiceConfig: { prebuiltVoiceConfig: { voiceName: request.voiceId } },\n ...(request.languageCode !== undefined && { languageCode: request.languageCode }),\n },\n }),\n ...(request.temperature !== undefined && { temperature: request.temperature }),\n ...(request.maxOutputTokens !== undefined && { maxOutputTokens: request.maxOutputTokens }),\n ...(request.mediaResolution !== undefined && {\n mediaResolution: `MEDIA_RESOLUTION_${request.mediaResolution.toUpperCase()}`,\n }),\n ...(request.thinkingLevel !== undefined && {\n thinkingConfig: { thinkingLevel: request.thinkingLevel.toUpperCase() },\n }),\n ...(request.affectiveDialog === true && { enableAffectiveDialog: true }),\n})\n\nconst toolsOf = (request: GeminiLiveRequest) =>\n request.googleSearch === true\n ? [{ googleSearch: {} }]\n : toolDescriptorsToTools(request.tools ?? [])\n\nconst setupFrame = (request: GeminiLiveRequest): string => {\n const tools = toolsOf(request)\n return JSON.stringify({\n setup: {\n model: `models/${request.model}`,\n generationConfig: generationConfig(request),\n ...(request.instructions !== undefined && {\n systemInstruction: { parts: [{ text: request.instructions }] },\n }),\n ...(tools.length > 0 && { tools }),\n realtimeInputConfig: realtimeInputConfig(request),\n ...(request.transcribeInput !== false && { inputAudioTranscription: {} }),\n // The only way to text on a native-audio model.\n outputAudioTranscription: {},\n // Always on, so a handle exists before the ten-minute socket ends.\n sessionResumption: request.resume === undefined ? {} : { handle: request.resume },\n ...(request.contextCompression !== undefined && {\n contextWindowCompression: {\n slidingWindow: {\n ...(request.contextCompression.targetTokens !== undefined && {\n targetTokens: request.contextCompression.targetTokens,\n }),\n },\n ...(request.contextCompression.triggerTokens !== undefined && {\n triggerTokens: request.contextCompression.triggerTokens,\n }),\n },\n }),\n ...(request.proactiveAudio === true && { proactivity: { proactiveAudio: true } }),\n // Seeded history arrives as `clientContent` right after the handshake.\n ...((request.history?.length ?? 0) > 0 && {\n historyConfig: { initialHistoryInClientContent: true },\n }),\n },\n })\n}\n\nconst messageText = (item: HistoryItem): string =>\n item.type !== \"message\"\n ? \"\"\n : item.content\n .map((block) =>\n block.type === \"input_text\" || block.type === \"output_text\" ? block.text : \"\",\n )\n .join(\"\")\n\n/**\n * Text-only seed, which is all `history` promises across providers. Anything\n * with no text of its own, a tool call or its output, has no place in the seed\n * and is reported once per kind rather than vanishing.\n */\nconst historyFrame = (\n history: ReadonlyArray<HistoryItem>,\n): Effect.Effect<string, AiError.AiError> =>\n Effect.gen(function* () {\n const kinds = new Set(history.filter((i) => messageText(i).length === 0).map((i) => i.type))\n yield* Effect.forEach(\n kinds,\n (kind) =>\n Capabilities.warnDropped({\n provider: PROVIDER,\n capability: \"history\",\n field: \"history\",\n value: kind,\n reason: `Gemini Live seeds a session with text turns only, so \\`${kind}\\` items are left out.`,\n }),\n { discard: true },\n )\n return JSON.stringify({\n clientContent: {\n turns: history\n .filter((item) => messageText(item).length > 0)\n .map((item) => ({\n role: item.type === \"message\" && item.role === \"assistant\" ? \"model\" : \"user\",\n parts: [{ text: messageText(item) }],\n })),\n turnComplete: true,\n },\n })\n })\n\n// ---------------------------------------------------------------------------\n// Server frames\n//\n// Gemini has no discriminator field: one message carries exactly one of these\n// keys, and `serverContent` can carry several of its own at once.\n// ---------------------------------------------------------------------------\n\nconst Part = Schema.Struct({\n text: Schema.optional(Schema.String),\n thought: Schema.optional(Schema.Boolean),\n inlineData: Schema.optional(\n Schema.Struct({\n mimeType: Schema.optional(Schema.String),\n data: Schema.optional(Schema.String),\n }),\n ),\n})\n\nconst Transcription = Schema.Struct({ text: Schema.optional(Schema.String) })\n\nconst ServerContent = Schema.Struct({\n modelTurn: Schema.optional(Schema.Struct({ parts: Schema.optional(Schema.Array(Part)) })),\n turnComplete: Schema.optional(Schema.Boolean),\n generationComplete: Schema.optional(Schema.Boolean),\n interrupted: Schema.optional(Schema.Boolean),\n inputTranscription: Schema.optional(Transcription),\n interimInputTranscription: Schema.optional(Transcription),\n outputTranscription: Schema.optional(Transcription),\n})\n\nconst UsageMetadata = Schema.Struct({\n promptTokenCount: Schema.optional(Schema.Number),\n responseTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n})\n\nconst FunctionCall = Schema.Struct({\n id: Schema.optional(Schema.String),\n name: Schema.String,\n args: Schema.optional(Schema.Unknown),\n})\n\nconst ServerMessage = Schema.Struct({\n setupComplete: Schema.optional(Schema.Unknown),\n serverContent: Schema.optional(ServerContent),\n toolCall: Schema.optional(\n Schema.Struct({ functionCalls: Schema.optional(Schema.Array(FunctionCall)) }),\n ),\n toolCallCancellation: Schema.optional(\n Schema.Struct({ ids: Schema.optional(Schema.Array(Schema.String)) }),\n ),\n goAway: Schema.optional(Schema.Struct({ timeLeft: Schema.optional(Schema.String) })),\n sessionResumptionUpdate: Schema.optional(\n Schema.Struct({\n newHandle: Schema.optional(Schema.String),\n resumable: Schema.optional(Schema.Boolean),\n }),\n ),\n usageMetadata: Schema.optional(UsageMetadata),\n})\n\ntype ServerMessage = typeof ServerMessage.Type\n\n// ---------------------------------------------------------------------------\n// Session state\n// ---------------------------------------------------------------------------\n\ntype SessionState = {\n /** The turn now generating, if any. Minted here: the wire has no id. */\n readonly responseId: string | undefined\n readonly turns: number\n /** Call id to tool name, since `functionResponse` must repeat the name. */\n readonly callNames: Readonly<Record<string, string>>\n /** Latest `usageMetadata`, reported with the turn it lands in. */\n readonly usage: Usage | undefined\n /** The server has announced the close, so the next one is the lifetime cap. */\n readonly goingAway: boolean\n}\n\nconst initialState: SessionState = {\n responseId: undefined,\n turns: 0,\n callNames: {},\n usage: undefined,\n goingAway: false,\n}\n\n/**\n * The id every event of the current turn carries, minting one and announcing\n * the turn if this is its first event.\n */\nconst startTurn = (\n state: Ref.Ref<SessionState>,\n): Effect.Effect<readonly [string, ReadonlyArray<RealtimeEvent>]> =>\n Ref.modify(state, (s) => {\n const responseId = s.responseId ?? `turn_${s.turns + 1}`\n return s.responseId !== undefined\n ? [[responseId, []], s]\n : [\n [responseId, [RealtimeEvent.ResponseStarted({ responseId })]],\n { ...s, responseId, turns: s.turns + 1 },\n ]\n })\n\nconst usageOf = (metadata: typeof UsageMetadata.Type): Usage => ({\n ...(metadata.promptTokenCount !== undefined && { input_tokens: metadata.promptTokenCount }),\n ...(metadata.responseTokenCount !== undefined && { output_tokens: metadata.responseTokenCount }),\n ...(metadata.totalTokenCount !== undefined && { total_tokens: metadata.totalTokenCount }),\n})\n\nconst decodeAudio = (b64: string): Effect.Effect<Uint8Array, AiError.AiError> =>\n Result.match(Encoding.decodeBase64(b64), {\n onSuccess: Effect.succeed,\n onFailure: (cause) =>\n Effect.fail(\n new AiError.GenerationFailed({\n provider: PROVIDER,\n raw: { message: \"audio part base64 decode failed\", cause },\n }),\n ),\n })\n\n/** `timeLeft` is a proto duration, so `\"60s\"` rather than a number. */\nconst parseTimeLeft = (timeLeft: string | undefined): Duration.Duration | undefined => {\n if (timeLeft === undefined) return undefined\n const seconds = Number.parseFloat(timeLeft.replace(/s$/, \"\"))\n return Number.isFinite(seconds) ? Duration.seconds(seconds) : undefined\n}\n\n/** Thought parts are the model reasoning, not something to speak or show. */\nconst partToEvents = (\n responseId: string,\n part: typeof Part.Type,\n): Effect.Effect<ReadonlyArray<RealtimeEvent>, AiError.AiError> =>\n Match.value(part).pipe(\n Match.when({ thought: true }, () => Effect.succeed([])),\n Match.when({ inlineData: { data: Match.string } }, (p) =>\n Effect.map(decodeAudio(p.inlineData.data), (bytes) => [\n RealtimeEvent.AudioDelta({ responseId, bytes }),\n ]),\n ),\n Match.when({ text: Match.string }, (p) =>\n Effect.succeed([RealtimeEvent.OutputTranscriptDelta({ responseId, text: p.text })]),\n ),\n Match.orElse(() => Effect.succeed([])),\n )\n\nconst inputTranscripts = (content: typeof ServerContent.Type): ReadonlyArray<RealtimeEvent> => [\n ...(content.interimInputTranscription?.text === undefined\n ? []\n : [\n RealtimeEvent.InputTranscript({\n text: content.interimInputTranscription.text,\n final: false,\n }),\n ]),\n ...(content.inputTranscription?.text === undefined\n ? []\n : [RealtimeEvent.InputTranscript({ text: content.inputTranscription.text, final: true })]),\n]\n\n/**\n * One `serverContent` to its events. Several fields can arrive together, and\n * 3.1 packs several parts into one message, so this answers with a batch.\n */\nconst contentToEvents = (\n state: Ref.Ref<SessionState>,\n content: typeof ServerContent.Type,\n): Effect.Effect<ReadonlyArray<RealtimeEvent>, AiError.AiError> =>\n Effect.gen(function* () {\n // The user's own words belong to no turn, so they need none started.\n const input = inputTranscripts(content)\n const parts = content.modelTurn?.parts ?? []\n const spokenText = content.outputTranscription?.text\n const generating = parts.length > 0 || spokenText !== undefined\n const ending = content.interrupted === true || content.turnComplete === true\n if (!generating && !ending) return input\n\n const [responseId, started] = generating\n ? yield* startTurn(state)\n : [(yield* Ref.get(state)).responseId, [] as ReadonlyArray<RealtimeEvent>]\n // A terminal flag for a turn that already ended is nothing to report.\n if (responseId === undefined) return input\n\n const spoken = yield* Effect.forEach(parts, (part) => partToEvents(responseId, part))\n const transcript =\n spokenText === undefined\n ? []\n : [RealtimeEvent.OutputTranscriptDelta({ responseId, text: spokenText })]\n const body = [...input, ...started, ...spoken.flat(), ...transcript]\n if (!ending) return body\n\n const usage = (yield* Ref.get(state)).usage\n yield* Ref.update(state, (s) => ({ ...s, responseId: undefined, usage: undefined }))\n return [\n ...body,\n // Playback must stop before the turn is reported as over.\n ...(content.interrupted === true ? [RealtimeEvent.Interrupted({ responseId })] : []),\n RealtimeEvent.ResponseDone({\n responseId,\n reason: content.interrupted === true ? \"interrupted\" : \"complete\",\n ...(usage !== undefined && { usage }),\n }),\n ]\n })\n\nconst toolCallEvents = (\n state: Ref.Ref<SessionState>,\n calls: ReadonlyArray<typeof FunctionCall.Type>,\n): Effect.Effect<ReadonlyArray<RealtimeEvent>> =>\n Effect.gen(function* () {\n const [responseId, started] = yield* startTurn(state)\n yield* Ref.update(state, (s) => ({\n ...s,\n callNames: calls.reduce(\n (names, call) => ({ ...names, [call.id ?? call.name]: call.name }),\n s.callNames,\n ),\n }))\n return [\n ...started,\n ...calls.map((call) =>\n RealtimeEvent.ToolCall({\n responseId,\n call: {\n type: \"function_call\" as const,\n call_id: call.id ?? call.name,\n name: call.name,\n arguments: JSON.stringify(call.args ?? {}),\n providerData: undefined,\n },\n }),\n ),\n ]\n })\n\nconst toEvents = (\n state: Ref.Ref<SessionState>,\n frame: ServerMessage,\n): Effect.Effect<ReadonlyArray<RealtimeEvent>, AiError.AiError> =>\n Effect.gen(function* () {\n if (frame.usageMetadata !== undefined) {\n const usage = usageOf(frame.usageMetadata)\n yield* Ref.update(state, (s) => ({ ...s, usage }))\n }\n if (frame.serverContent !== undefined) return yield* contentToEvents(state, frame.serverContent)\n if (frame.toolCall !== undefined) {\n return yield* toolCallEvents(state, frame.toolCall.functionCalls ?? [])\n }\n const callIds = frame.toolCallCancellation?.ids ?? []\n if (callIds.length > 0) return [RealtimeEvent.ToolCallCancelled({ callIds })]\n if (frame.goAway !== undefined) {\n const timeLeft = parseTimeLeft(frame.goAway.timeLeft)\n yield* Ref.update(state, (s) => ({ ...s, goingAway: true }))\n return [RealtimeEvent.SessionEnding({ ...(timeLeft !== undefined && { timeLeft }) })]\n }\n // An unresumable update carries an empty handle; it must not replace one.\n const handle = frame.sessionResumptionUpdate?.newHandle\n return frame.sessionResumptionUpdate?.resumable === true &&\n handle !== undefined &&\n handle !== \"\"\n ? [RealtimeEvent.ResumptionHandle({ handle })]\n : []\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 automatic activity detection; boundaries are the server's.\",\n })\n\nconst videoPart = (\n frame: Extract<RealtimeInput, { readonly _tag: \"VideoFrame\" }>[\"frame\"],\n): Effect.Effect<{ readonly data: string; readonly mimeType: string }, AiError.AiError> =>\n Match.value(frame).pipe(\n Match.tag(\"base64\", (s) => Effect.succeed({ data: s.base64, mimeType: s.mimeType })),\n Match.tag(\"bytes\", (s) =>\n Effect.succeed({ data: Encoding.encodeBase64(s.bytes), mimeType: s.mimeType }),\n ),\n Match.tag(\"url\", () =>\n Effect.fail(\n new AiError.Unsupported({\n provider: PROVIDER,\n capability: \"videoInput\",\n reason: \"A live video frame must carry its bytes; a URL would need the Files API.\",\n }),\n ),\n ),\n Match.exhaustive,\n )\n\n/** Wire spelling of `toolScheduling`. */\ntype ToolScheduling = \"WHEN_IDLE\" | \"INTERRUPT\" | \"SILENT\"\n\nconst schedulingOf = (request: GeminiLiveRequest): ToolScheduling =>\n Match.value(request.toolScheduling ?? \"when-idle\").pipe(\n Match.when(\"when-idle\", () => \"WHEN_IDLE\" as const),\n Match.when(\"interrupt\", () => \"INTERRUPT\" as const),\n Match.when(\"silent\", () => \"SILENT\" as const),\n Match.exhaustive,\n )\n\nconst handleInput = (\n send: (frame: string) => Effect.Effect<void, AiError.AiError>,\n state: Ref.Ref<SessionState>,\n options: {\n readonly manual: boolean\n readonly rate: number\n readonly scheduling: ToolScheduling\n },\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 realtimeInput: {\n audio: {\n data: Encoding.encodeBase64(i.bytes),\n mimeType: `audio/pcm;rate=${options.rate}`,\n },\n },\n }),\n ),\n ),\n Match.tag(\"Text\", (i) =>\n i.role === \"system\"\n ? Effect.fail(\n new AiError.Unsupported({\n provider: PROVIDER,\n capability: \"systemTurn\",\n reason: \"Gemini Live fixes the system instruction at setup for the connection.\",\n }),\n )\n : send(JSON.stringify({ realtimeInput: { text: i.text } })),\n ),\n Match.tag(\"ToolResult\", (i) =>\n Effect.gen(function* () {\n const name = (yield* Ref.get(state)).callNames[i.output.call_id]\n if (name === undefined) {\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 // Answering resumes generation on its own; there is no turn to ask\n // for. `scheduling` says when, and matters on a model that kept\n // generating while the tool ran.\n yield* send(\n JSON.stringify({\n toolResponse: {\n functionResponses: [\n {\n id: i.output.call_id,\n name,\n response: parsedResponse(i.output.output),\n scheduling: options.scheduling,\n },\n ],\n },\n }),\n )\n }),\n ),\n Match.tag(\"Interrupt\", () =>\n Effect.fail(\n new AiError.Unsupported({\n provider: PROVIDER,\n capability: \"interrupt\",\n reason:\n 'Gemini Live has no cancel op: the server interrupts when it hears speech. Pass activityHandling: \"none\" to turn that off.',\n }),\n ),\n ),\n Match.tag(\"VideoFrame\", (i) =>\n Effect.flatMap(videoPart(i.frame), (video) =>\n send(JSON.stringify({ realtimeInput: { video } })),\n ),\n ),\n Match.tag(\"ActivityStart\", () =>\n options.manual\n ? send(JSON.stringify({ realtimeInput: { activityStart: {} } }))\n : droppedActivity(\"ActivityStart\"),\n ),\n Match.tag(\"ActivityEnd\", () =>\n options.manual\n ? send(JSON.stringify({ realtimeInput: { activityEnd: {} } }))\n : droppedActivity(\"ActivityEnd\"),\n ),\n // Interruption already drops what was never generated, but audio the\n // server did send stays in history whether or not it was heard.\n Match.tag(\"PlaybackPosition\", () =>\n Capabilities.warnDropped({\n provider: PROVIDER,\n capability: \"truncate\",\n field: \"PlaybackPosition\",\n reason: \"Gemini Live has no truncate op, so the unheard tail stays in context.\",\n }),\n ),\n Match.exhaustive,\n )\n\n// ---------------------------------------------------------------------------\n// Connection\n// ---------------------------------------------------------------------------\n\nexport const buildWsUrl = (cfg: Config): string => {\n const url = new URL(cfg.baseUrl ?? DEFAULT_BASE_URL)\n url.protocol = url.protocol === \"http:\" ? \"ws:\" : \"wss:\"\n url.pathname = `${url.pathname.replace(/\\/$/, \"\")}/${RPC}`\n url.searchParams.set(\"key\", Redacted.value(cfg.apiKey))\n return url.toString()\n}\n\nconst withSocket =\n (cfg: Config) =>\n <A, E, R>(\n effect: Effect.Effect<A, E, R | Socket.WebSocketConstructor>,\n ): Effect.Effect<A, E, Exclude<R, Socket.WebSocketConstructor>> =>\n cfg.webSocket === undefined\n ? Effect.provide(effect, Socket.layerWebSocketConstructorGlobal)\n : Effect.provideService(effect, Socket.WebSocketConstructor, cfg.webSocket)\n\n/** Drop frames until `setupComplete`; a close before it is a failed handshake. */\nconst awaitSetupComplete = (\n session: WebSocketSession.WebSocketSession<ServerMessage>,\n): Effect.Effect<void, AiError.AiError> =>\n Queue.take(session.frames).pipe(\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 frame.setupComplete === undefined ? awaitSetupComplete(session) : Effect.void,\n ),\n )\n\nexport const openSession =\n (cfg: Config) =>\n (\n request: GeminiLiveRequest,\n ): Effect.Effect<RealtimeSessionHandle, AiError.AiError, Scope.Scope> =>\n Effect.gen(function* () {\n if (request.googleSearch === true && (request.tools?.length ?? 0) > 0) {\n return yield* Effect.fail(\n new AiError.InvalidRequest({\n provider: PROVIDER,\n raw: \"Gemini rejects googleSearch alongside function declarations; pick one per session.\",\n }),\n )\n }\n const rate = yield* inputRate(request.inputFormat)\n const scheduling = schedulingOf(request)\n yield* checkOutputFormat(request.outputFormat)\n\n const session = yield* WebSocketSession.open({\n url: buildWsUrl(cfg),\n provider: PROVIDER,\n schema: ServerMessage,\n openTimeout: Duration.seconds(30),\n }).pipe(withSocket(cfg))\n\n // The client speaks first here, and nothing else may be sent until the\n // server has accepted the configuration.\n yield* session.send(setupFrame(request))\n yield* awaitSetupComplete(session)\n\n const history = request.history ?? []\n if (history.length > 0) {\n const seed = yield* historyFrame(history)\n yield* session.send(seed)\n }\n\n const state = yield* Ref.make(initialState)\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(state, frame)),\n Stream.runForEach((events) => Queue.offerAll(out, events)),\n )\n\n // A close never synthesizes a `ResponseDone`; a turn 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 { goingAway, 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 turn\" }),\n )\n }\n // `goAway` was the server announcing this close, so the session hit\n // its cap. Reconnecting works; retrying this session does not.\n if (goingAway) {\n return yield* Queue.fail(\n out,\n new AiError.SessionExpired({\n provider: PROVIDER,\n raw: cause ?? \"the socket closed after the server announced it was going away\",\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\n const manual = request.turnDetection === \"manual\"\n return {\n send: (input) => handleInput(session.send, state, { manual, rate, scheduling }, input),\n events: Stream.fromQueue(out),\n }\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyCA,MAAM,WAAW;AAEjB,MAAM,mBAAmB;AACzB,MAAM,MAAM;;AA2DZ,MAAM,cAAc;AAEpB,MAAM,qBAAqB,QAAqB,OAAe,aAC7D,IAAI,QAAQ,YAAY;CACt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AK,CAAC,GAClD,OAAO,YAAY,WAAW,MAAM,SAAS,KAAK,MAAM,CAAC,CAC3D;CAIA,MAAM,UAAU,UACd,OAAO,IAAI,aAAa;EACtB,MAAM,EAAE,WAAW,eAAe,OAAO,IAAI,IAAI,KAAK;EACtD,IAAI,eAAe,KAAA,GACjB,OAAO,OAAO,MAAM,KAClB,KACA,IAAI,QAAQ,eAAe,EAAE,KAAK,SAAS,6BAA6B,CAAC,CAC3E;EAIF,IAAI,WACF,OAAO,OAAO,MAAM,KAClB,KACA,IAAI,QAAQ,eAAe;GACzB,UAAU;GACV,KAAK,SAAS;EAChB,CAAC,CACH;EAEF,OAAO,OAAO,UAAU,KAAA,KAAa,MAAM,SAAS,KAAK,IACrD,MAAM,UAAU,KAAK,KAAK,IAC1B,MAAM,IAAI,GAAG;CACnB,CAAC;CAEH,OAAO,KAAK,KACV,OAAO,iBAAiB;EAAE,WAAW;EAAQ,iBAAiB,OAAO,KAAA,CAAS;CAAE,CAAC,GACjF,OAAO,UACT;CAEA,MAAM,SAAS,QAAQ,kBAAkB;CACzC,OAAO;EACL,OAAO,UAAU,YAAY,QAAQ,MAAM,OAAO;GAAE;GAAQ;GAAM;EAAW,GAAG,KAAK;EACrF,QAAQ,OAAO,UAAU,GAAG;CAC9B;AACF,CAAC"}
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,505 @@
1
+ import { openSession } from "./realtimeSession.mjs";
2
+ import { a as beforeEach, i as beforeAll, n as globalExpect, o as describe, r as afterAll, s as it$1, t as TestRunner } from "./test.DNmyFkvJ-BPz3G1HS.mjs";
3
+ import { Duration, Effect, Encoding, Fiber, Logger, Redacted, Ref, Stream } from "effect";
4
+ import { RealtimeInput } from "@effect-uai/core/Realtime";
5
+ import * as Cause$1 from "effect/Cause";
6
+ import * as Duration$1 from "effect/Duration";
7
+ import * as Effect$1 from "effect/Effect";
8
+ import * as Exit from "effect/Exit";
9
+ import { flow, pipe as pipe$1 } from "effect/Function";
10
+ import * as Layer$1 from "effect/Layer";
11
+ import { isObject } from "effect/Predicate";
12
+ import * as Rec from "effect/Record";
13
+ import * as Schedule from "effect/Schedule";
14
+ import * as Schema$1 from "effect/Schema";
15
+ import * as Scope$1 from "effect/Scope";
16
+ import * as fc from "effect/testing/FastCheck";
17
+ import * as TestClock from "effect/testing/TestClock";
18
+ import * as TestConsole from "effect/testing/TestConsole";
19
+ import * as FakeWebSocket from "@effect-uai/core/testing/FakeWebSocket";
20
+ //#region ../../../node_modules/.pnpm/@effect+vitest@4.0.0-rc.111_effect@4.0.0-rc.111_vitest@4.1.11_@types+node@26.2.0_vite@7_0a4161190c2476edad4e3173ad651095/node_modules/@effect/vitest/dist/internal/internal.js
21
+ /**
22
+ * @since 4.0.0
23
+ */
24
+ const getCurrentSuite = TestRunner.getCurrentSuite;
25
+ const runPromise = /*#__PURE__*/ Effect$1.fnUntraced(function* (effect, _ctx) {
26
+ const exit = yield* Effect$1.exit(effect);
27
+ if (Exit.isFailure(exit)) {
28
+ const errors = Cause$1.prettyErrors(exit.cause);
29
+ for (let i = 0; i < errors.length; i++) yield* Effect$1.logError(errors[i]);
30
+ }
31
+ return yield* exit;
32
+ }, (effect, _, ctx) => Effect$1.runPromise(effect, { signal: ctx?.signal }));
33
+ /** @internal */
34
+ const runTest = (ctx) => (effect) => runPromise(effect, ctx);
35
+ const TestEnv = /*#__PURE__*/ Layer$1.mergeAll(TestConsole.layer, /*#__PURE__*/ TestClock.layer());
36
+ /** @internal */
37
+ const testOptions = (timeout) => typeof timeout === "number" ? { timeout } : timeout ?? {};
38
+ const hookTimeout = (timeout) => timeout === void 0 ? void 0 : Duration$1.toMillis(Duration$1.fromInputUnsafe(timeout));
39
+ const makeItProxy = (it, overrides) => new Proxy(it, {
40
+ apply(target, thisArg, argArray) {
41
+ return Reflect.apply(target, thisArg, argArray);
42
+ },
43
+ get(target, property, receiver) {
44
+ if (Object.hasOwn(overrides, property)) return Reflect.get(overrides, property);
45
+ return Reflect.get(target, property, receiver);
46
+ }
47
+ });
48
+ const collectTasks = (tasks, acc = []) => {
49
+ for (let i = 0; i < tasks.length; i++) {
50
+ const task = tasks[i];
51
+ if (task.type === "test" && task.mode !== "skip" && task.mode !== "todo") acc.push(task);
52
+ else if (task.tasks !== void 0) collectTasks(task.tasks, acc);
53
+ }
54
+ return acc;
55
+ };
56
+ /** @internal */
57
+ const makeTester = (mapEffect, it = it$1) => {
58
+ const run = (ctx, args, self) => pipe$1(Effect$1.suspend(() => self(...args)), mapEffect, runTest(ctx));
59
+ const f = (name, self, timeout) => it(name, testOptions(timeout), (ctx) => run(ctx, [ctx], self));
60
+ const skip = (name, self, timeout) => it.skip(name, testOptions(timeout), (ctx) => run(ctx, [ctx], self));
61
+ const skipIf = (condition) => (name, self, timeout) => it.skipIf(condition)(name, testOptions(timeout), (ctx) => run(ctx, [ctx], self));
62
+ const runIf = (condition) => (name, self, timeout) => it.runIf(condition)(name, testOptions(timeout), (ctx) => run(ctx, [ctx], self));
63
+ const only = (name, self, timeout) => it.only(name, testOptions(timeout), (ctx) => run(ctx, [ctx], self));
64
+ const each = (cases) => (name, self, timeout) => it.for(cases)(name, testOptions(timeout), (args, ctx) => run(ctx, [args], self));
65
+ const fails = (name, self, timeout) => it$1.fails(name, testOptions(timeout), (ctx) => run(ctx, [ctx], self));
66
+ const prop = (name, arbitraries, self, timeout) => {
67
+ if (Array.isArray(arbitraries)) {
68
+ const arbs = arbitraries.map((arbitrary) => {
69
+ if (Schema$1.isSchema(arbitrary)) return Schema$1.toArbitrary(arbitrary)(fc);
70
+ return arbitrary;
71
+ });
72
+ return it(name, testOptions(timeout), (ctx) => fc.assert(fc.asyncProperty(...arbs, (...as) => run(ctx, [as, ctx], self)), isObject(timeout) ? timeout?.fastCheck : {}));
73
+ }
74
+ const arbs = fc.record(Object.keys(arbitraries).reduce(function(result, key) {
75
+ const arb = arbitraries[key];
76
+ Rec.assignProperty(result, key, Schema$1.isSchema(arb) ? Schema$1.toArbitrary(arb)(fc) : arb);
77
+ return result;
78
+ }, {}));
79
+ return it(name, testOptions(timeout), (ctx) => fc.assert(fc.asyncProperty(arbs, (...as) => run(ctx, [as[0], ctx], self)), isObject(timeout) ? timeout?.fastCheck : {}));
80
+ };
81
+ return Object.assign(f, {
82
+ skip,
83
+ skipIf,
84
+ runIf,
85
+ only,
86
+ each,
87
+ fails,
88
+ prop
89
+ });
90
+ };
91
+ /** @internal */
92
+ const prop = (name, arbitraries, self, timeout) => {
93
+ if (Array.isArray(arbitraries)) {
94
+ const arbs = arbitraries.map((arbitrary) => {
95
+ if (Schema$1.isSchema(arbitrary)) throw new Error("Schemas are not supported yet");
96
+ return arbitrary;
97
+ });
98
+ return it$1(name, testOptions(timeout), (ctx) => fc.assert(fc.property(...arbs, (...as) => self(as, ctx)), isObject(timeout) ? timeout?.fastCheck : {}));
99
+ }
100
+ const arbs = fc.record(Object.keys(arbitraries).reduce(function(result, key) {
101
+ const arb = arbitraries[key];
102
+ if (Schema$1.isSchema(arb)) throw new Error("Schemas are not supported yet");
103
+ Rec.assignProperty(result, key, arb);
104
+ return result;
105
+ }, {}));
106
+ return it$1(name, testOptions(timeout), (ctx) => fc.assert(fc.property(arbs, (as) => self(as, ctx)), isObject(timeout) ? timeout?.fastCheck : {}));
107
+ };
108
+ /** @internal */
109
+ const layer = (layer_, options) => (...args) => {
110
+ const excludeTestServices = options?.excludeTestServices ?? false;
111
+ const withTestEnv = excludeTestServices ? layer_ : Layer$1.provideMerge(layer_, TestEnv);
112
+ const memoMap = options?.memoMap ?? Effect$1.runSync(Layer$1.makeMemoMap);
113
+ const scope = Effect$1.runSync(Scope$1.make());
114
+ const contextEffect = Layer$1.buildWithMemoMap(withTestEnv, memoMap, scope).pipe(Effect$1.orDie, Effect$1.cached, Effect$1.runSync);
115
+ let closed = false;
116
+ const closeScope = (ctx) => {
117
+ if (closed) return Promise.resolve();
118
+ closed = true;
119
+ return runPromise(Scope$1.close(scope, Exit.void), ctx);
120
+ };
121
+ const makeIt = (it) => makeItProxy(it, {
122
+ effect: makeTester((effect) => Effect$1.flatMap(contextEffect, (context) => effect.pipe(Effect$1.scoped, Effect$1.provide(context))), it),
123
+ prop,
124
+ flakyTest,
125
+ layer(nestedLayer, options) {
126
+ return layer(Layer$1.provideMerge(nestedLayer, withTestEnv), {
127
+ ...options,
128
+ memoMap: Layer$1.forkMemoMapUnsafe(memoMap),
129
+ excludeTestServices
130
+ });
131
+ }
132
+ });
133
+ if (args.length === 1) {
134
+ const currentSuite = getCurrentSuite();
135
+ const previousTasks = new Set(currentSuite.tasks);
136
+ args[0](makeIt(it$1));
137
+ const blockTasks = collectTasks(currentSuite.tasks.filter((task) => !previousTasks.has(task)));
138
+ if (blockTasks.length === 0) {
139
+ afterAll(() => closeScope(), hookTimeout(options?.timeout));
140
+ return;
141
+ }
142
+ const blockTaskSet = new Set(blockTasks);
143
+ let remaining = blockTasks.length;
144
+ beforeEach((ctx) => {
145
+ if (!blockTaskSet.has(ctx.task)) return;
146
+ ctx.onTestFinished(() => {
147
+ remaining--;
148
+ if (remaining === 0) return closeScope(ctx);
149
+ });
150
+ return runPromise(Effect$1.asVoid(contextEffect), ctx);
151
+ }, hookTimeout(options?.timeout));
152
+ afterAll(() => closeScope(), hookTimeout(options?.timeout));
153
+ return;
154
+ }
155
+ return describe(args[0], () => {
156
+ beforeAll(() => runPromise(Effect$1.asVoid(contextEffect)), hookTimeout(options?.timeout));
157
+ afterAll(() => closeScope(), hookTimeout(options?.timeout));
158
+ return args[1](makeIt(it$1));
159
+ });
160
+ };
161
+ /** @internal */
162
+ const flakyTest = (self, timeout = Duration$1.seconds(30)) => pipe$1(self, Effect$1.scoped, Effect$1.sandbox, Effect$1.retry(pipe$1(Schedule.recurs(10), Schedule.while((_) => Effect$1.succeed(Duration$1.isLessThanOrEqualTo(Duration$1.fromInputUnsafe(_.elapsed), Duration$1.fromInputUnsafe(timeout)))))), Effect$1.orDie);
163
+ /** @internal */
164
+ const makeMethods = (it) => makeItProxy(it, {
165
+ effect: makeTester(flow(Effect$1.scoped, Effect$1.provide(TestEnv)), it),
166
+ live: makeTester(Effect$1.scoped, it),
167
+ flakyTest,
168
+ layer,
169
+ prop
170
+ });
171
+ /** @internal */
172
+ const { effect, live } = /*#__PURE__*/ makeMethods(it$1);
173
+ //#endregion
174
+ //#region ../../../node_modules/.pnpm/@effect+vitest@4.0.0-rc.111_effect@4.0.0-rc.111_vitest@4.1.11_@types+node@26.2.0_vite@7_0a4161190c2476edad4e3173ad651095/node_modules/@effect/vitest/dist/index.js
175
+ /**
176
+ * @since 4.0.0
177
+ */
178
+ /**
179
+ * @since 4.0.0
180
+ */
181
+ const it = /*#__PURE__*/ makeMethods(it$1);
182
+ //#endregion
183
+ //#region src/realtimeSession.test.ts
184
+ const request = {
185
+ model: "gemini-3.1-flash-live-preview",
186
+ instructions: "be terse",
187
+ voiceId: "Kore",
188
+ inputFormat: {
189
+ container: "raw",
190
+ encoding: "pcm_s16le",
191
+ sampleRate: 16e3,
192
+ channels: 1
193
+ },
194
+ outputFormat: {
195
+ container: "raw",
196
+ encoding: "pcm_s16le",
197
+ sampleRate: 24e3,
198
+ channels: 1
199
+ }
200
+ };
201
+ const cfg = { apiKey: Redacted.make("test-key") };
202
+ /** The client speaks first here, so the handshake answers `setup`. */
203
+ const gemini = FakeWebSocket.make({ reply: (frame) => Effect.succeed(Object.hasOwn(frame, "setup") ? [{ setupComplete: {} }] : []) });
204
+ /** Let the socket's own turn and the adapter's fibers run. */
205
+ const tick = Effect.sleep("5 millis");
206
+ /**
207
+ * Events are recorded as they arrive rather than collected at the end, so a
208
+ * run that ends in a failure still says what the caller saw before it.
209
+ */
210
+ const transcript = (server, script, options) => Effect.gen(function* () {
211
+ const handle = yield* openSession({
212
+ ...cfg,
213
+ webSocket: server.connect
214
+ })(options?.request ?? request);
215
+ const seen = yield* Ref.make([]);
216
+ const collector = yield* Effect.forkChild(Effect.exit(Stream.runForEach(handle.events, (e) => Ref.update(seen, (xs) => [...xs, e]))));
217
+ yield* script(handle);
218
+ yield* tick;
219
+ yield* server.close(options?.closeCode ?? 1e3);
220
+ return {
221
+ exit: yield* Fiber.join(collector),
222
+ events: yield* Ref.get(seen)
223
+ };
224
+ });
225
+ const tags = (events) => events.map((e) => e._tag);
226
+ const audioPart = (bytes) => ({ inlineData: {
227
+ mimeType: "audio/pcm;rate=24000",
228
+ data: Encoding.encodeBase64(new Uint8Array(bytes))
229
+ } });
230
+ describe("Gemini live session turns", () => {
231
+ it.live("mints one turn id for a whole answer, and reports its usage at the end", () => Effect.gen(function* () {
232
+ const server = yield* gemini;
233
+ const { events } = yield* transcript(server, () => Effect.gen(function* () {
234
+ yield* server.push({ serverContent: {
235
+ modelTurn: { parts: [audioPart([
236
+ 1,
237
+ 2,
238
+ 3
239
+ ]), {
240
+ thought: true,
241
+ text: "planning"
242
+ }] },
243
+ outputTranscription: { text: "hi" }
244
+ } });
245
+ yield* server.push({
246
+ serverContent: { modelTurn: { parts: [audioPart([4, 5])] } },
247
+ usageMetadata: {
248
+ promptTokenCount: 10,
249
+ responseTokenCount: 20,
250
+ totalTokenCount: 30
251
+ }
252
+ });
253
+ yield* server.push({ serverContent: { turnComplete: true } });
254
+ }));
255
+ globalExpect(tags(events)).toEqual([
256
+ "ResponseStarted",
257
+ "AudioDelta",
258
+ "OutputTranscriptDelta",
259
+ "AudioDelta",
260
+ "ResponseDone"
261
+ ]);
262
+ globalExpect(new Set(events.map((e) => "responseId" in e ? e.responseId : ""))).toEqual(/* @__PURE__ */ new Set(["turn_1"]));
263
+ const done = events[4];
264
+ globalExpect(done?._tag === "ResponseDone" && done.reason).toBe("complete");
265
+ globalExpect(done?._tag === "ResponseDone" && done.usage?.total_tokens).toBe(30);
266
+ }).pipe(Effect.scoped));
267
+ it.live("ends an interrupted turn once, and numbers the next one after it", () => Effect.gen(function* () {
268
+ const server = yield* gemini;
269
+ const { events } = yield* transcript(server, () => Effect.gen(function* () {
270
+ yield* server.push({ serverContent: { modelTurn: { parts: [audioPart([1])] } } });
271
+ yield* server.push({ serverContent: { interrupted: true } });
272
+ yield* server.push({ serverContent: { turnComplete: true } });
273
+ yield* server.push({ serverContent: { modelTurn: { parts: [audioPart([2])] } } });
274
+ yield* server.push({ serverContent: { turnComplete: true } });
275
+ }));
276
+ globalExpect(tags(events)).toEqual([
277
+ "ResponseStarted",
278
+ "AudioDelta",
279
+ "Interrupted",
280
+ "ResponseDone",
281
+ "ResponseStarted",
282
+ "AudioDelta",
283
+ "ResponseDone"
284
+ ]);
285
+ const interrupted = events[3];
286
+ globalExpect(interrupted?._tag === "ResponseDone" && interrupted.reason).toBe("interrupted");
287
+ const next = events[4];
288
+ globalExpect(next?._tag === "ResponseStarted" && next.responseId).toBe("turn_2");
289
+ }).pipe(Effect.scoped));
290
+ it.live("marks the user's words interim until the utterance is transcribed", () => Effect.gen(function* () {
291
+ const server = yield* gemini;
292
+ const { events } = yield* transcript(server, () => Effect.gen(function* () {
293
+ yield* server.push({ serverContent: { interimInputTranscription: { text: "weather" } } });
294
+ yield* server.push({ serverContent: { inputTranscription: { text: "weather in Lisbon" } } });
295
+ }));
296
+ globalExpect(events).toEqual([{
297
+ _tag: "InputTranscript",
298
+ text: "weather",
299
+ final: false
300
+ }, {
301
+ _tag: "InputTranscript",
302
+ text: "weather in Lisbon",
303
+ final: true
304
+ }]);
305
+ }).pipe(Effect.scoped));
306
+ it.live("ends the stream as an incomplete turn when a turn is still running", () => Effect.gen(function* () {
307
+ const server = yield* gemini;
308
+ const { exit } = yield* transcript(server, () => server.push({ serverContent: { modelTurn: { parts: [audioPart([1])] } } }));
309
+ globalExpect(exit._tag).toBe("Failure");
310
+ globalExpect(JSON.stringify(exit)).toContain("IncompleteTurn");
311
+ }).pipe(Effect.scoped));
312
+ it.live("fails when the socket closes before the configuration is accepted", () => Effect.gen(function* () {
313
+ const mute = yield* FakeWebSocket.make();
314
+ const opened = yield* Effect.forkChild(Effect.exit(openSession({
315
+ ...cfg,
316
+ webSocket: mute.connect
317
+ })(request)));
318
+ yield* tick;
319
+ yield* mute.close(1e3);
320
+ const exit = yield* Fiber.join(opened);
321
+ globalExpect(exit._tag).toBe("Failure");
322
+ globalExpect(JSON.stringify(exit)).toContain("Unavailable");
323
+ }).pipe(Effect.scoped));
324
+ });
325
+ describe("Gemini live session tools", () => {
326
+ it.live("answers a call with the name the server gave it", () => Effect.gen(function* () {
327
+ const server = yield* gemini;
328
+ const { events } = yield* transcript(server, (handle) => Effect.gen(function* () {
329
+ yield* server.push({ toolCall: { functionCalls: [{
330
+ id: "fc_1",
331
+ name: "get_weather",
332
+ args: { city: "Lisbon" }
333
+ }] } });
334
+ yield* tick;
335
+ yield* handle.send(RealtimeInput.ToolResult({ output: {
336
+ type: "function_call_output",
337
+ call_id: "fc_1",
338
+ output: "{\"celsius\":32}",
339
+ providerData: void 0
340
+ } }));
341
+ yield* server.push({ serverContent: { turnComplete: true } });
342
+ }));
343
+ const call = events.find((e) => e._tag === "ToolCall");
344
+ globalExpect(call?._tag === "ToolCall" && call.call.arguments).toBe("{\"city\":\"Lisbon\"}");
345
+ globalExpect(call?._tag === "ToolCall" && call.responseId).toBe("turn_1");
346
+ const response = (yield* server.sent).find((f) => f.toolResponse !== void 0);
347
+ globalExpect(response.toolResponse.functionResponses).toEqual([{
348
+ id: "fc_1",
349
+ name: "get_weather",
350
+ response: { celsius: 32 },
351
+ scheduling: "WHEN_IDLE"
352
+ }]);
353
+ }).pipe(Effect.scoped));
354
+ it.live("reports a result at once when the caller asks it to interrupt", () => Effect.gen(function* () {
355
+ const server = yield* gemini;
356
+ yield* transcript(server, (handle) => Effect.gen(function* () {
357
+ yield* server.push({ toolCall: { functionCalls: [{
358
+ id: "fc_1",
359
+ name: "get_weather",
360
+ args: {}
361
+ }] } });
362
+ yield* tick;
363
+ yield* handle.send(RealtimeInput.ToolResult({ output: {
364
+ type: "function_call_output",
365
+ call_id: "fc_1",
366
+ output: "{}",
367
+ providerData: void 0
368
+ } }));
369
+ }), { request: {
370
+ ...request,
371
+ toolScheduling: "interrupt"
372
+ } });
373
+ const response = (yield* server.sent).find((f) => f.toolResponse !== void 0);
374
+ globalExpect(response.toolResponse.functionResponses[0].scheduling).toBe("INTERRUPT");
375
+ }).pipe(Effect.scoped));
376
+ it.live("rejects a result for a call this session never made", () => Effect.gen(function* () {
377
+ const server = yield* gemini;
378
+ const handle = yield* openSession({
379
+ ...cfg,
380
+ webSocket: server.connect
381
+ })(request);
382
+ const failure = yield* Effect.exit(handle.send(RealtimeInput.ToolResult({ output: {
383
+ type: "function_call_output",
384
+ call_id: "fc_unknown",
385
+ output: "{}",
386
+ providerData: void 0
387
+ } })));
388
+ globalExpect(failure._tag).toBe("Failure");
389
+ globalExpect(JSON.stringify(failure)).toContain("InvalidRequest");
390
+ globalExpect((yield* server.sent).some((f) => f.toolResponse !== void 0)).toBe(false);
391
+ }).pipe(Effect.scoped));
392
+ });
393
+ describe("Gemini live session lifetime", () => {
394
+ it.live("keeps only a resumable handle, and reads the closing warning as a duration", () => Effect.gen(function* () {
395
+ const server = yield* gemini;
396
+ const { events, exit } = yield* transcript(server, () => Effect.gen(function* () {
397
+ yield* server.push({ sessionResumptionUpdate: {
398
+ newHandle: "",
399
+ resumable: false
400
+ } });
401
+ yield* server.push({ sessionResumptionUpdate: {
402
+ newHandle: "h1",
403
+ resumable: true
404
+ } });
405
+ yield* server.push({ goAway: { timeLeft: "60s" } });
406
+ }));
407
+ globalExpect(tags(events)).toEqual(["ResumptionHandle", "SessionEnding"]);
408
+ const handle = events[0];
409
+ globalExpect(handle?._tag === "ResumptionHandle" && handle.handle).toBe("h1");
410
+ const ending = events[1];
411
+ globalExpect(ending?._tag === "SessionEnding" && ending.timeLeft).toEqual(Duration.seconds(60));
412
+ globalExpect(JSON.stringify(exit)).toContain("SessionExpired");
413
+ }).pipe(Effect.scoped));
414
+ it.live("ends cleanly when the close was not announced", () => Effect.gen(function* () {
415
+ const server = yield* gemini;
416
+ const { exit } = yield* transcript(server, () => server.push({ serverContent: { turnComplete: true } }));
417
+ globalExpect(exit._tag).toBe("Success");
418
+ }).pipe(Effect.scoped));
419
+ });
420
+ /** The `CapabilityWarning` payloads a run produced, in order. */
421
+ const warningCollector = () => {
422
+ const seen = [];
423
+ const logger = Logger.make((options) => {
424
+ const [label, warning] = options.message;
425
+ if (label === "Capability dropped") seen.push(warning);
426
+ });
427
+ return {
428
+ seen,
429
+ layer: Logger.layer([logger])
430
+ };
431
+ };
432
+ const userText = (text) => ({
433
+ type: "message",
434
+ role: "user",
435
+ content: [{
436
+ type: "input_text",
437
+ text,
438
+ providerData: void 0
439
+ }],
440
+ providerData: void 0
441
+ });
442
+ const call = (id) => ({
443
+ type: "function_call",
444
+ call_id: id,
445
+ name: "get_time",
446
+ arguments: "{}",
447
+ providerData: void 0
448
+ });
449
+ describe("Gemini live session history", () => {
450
+ it.live("names each kind of item the text-only seed cannot carry, once", () => Effect.gen(function* () {
451
+ const server = yield* gemini;
452
+ const warnings = warningCollector();
453
+ yield* openSession({
454
+ ...cfg,
455
+ webSocket: server.connect
456
+ })({
457
+ ...request,
458
+ history: [
459
+ userText("what time is it"),
460
+ call("fc_1"),
461
+ call("fc_2"),
462
+ {
463
+ type: "function_call_output",
464
+ call_id: "fc_1",
465
+ output: "{\"now\":\"12:00\"}",
466
+ providerData: void 0
467
+ }
468
+ ]
469
+ }).pipe(Effect.provide(warnings.layer));
470
+ yield* tick;
471
+ globalExpect(warnings.seen.map((w) => w.value)).toEqual(["function_call", "function_call_output"]);
472
+ globalExpect(warnings.seen.every((w) => w.field === "history")).toBe(true);
473
+ const seed = (yield* server.sent).find((f) => f.clientContent !== void 0);
474
+ globalExpect(seed.clientContent.turns).toEqual([{
475
+ role: "user",
476
+ parts: [{ text: "what time is it" }]
477
+ }]);
478
+ }).pipe(Effect.scoped));
479
+ });
480
+ describe("Gemini live session video", () => {
481
+ it.live("sends frame bytes inline, and refuses a frame it would have to fetch", () => Effect.gen(function* () {
482
+ const server = yield* gemini;
483
+ yield* transcript(server, (handle) => Effect.gen(function* () {
484
+ yield* handle.send(RealtimeInput.VideoFrame({ frame: {
485
+ _tag: "bytes",
486
+ bytes: new Uint8Array([1, 2]),
487
+ mimeType: "image/jpeg"
488
+ } }));
489
+ const exit = yield* Effect.exit(handle.send(RealtimeInput.VideoFrame({ frame: {
490
+ _tag: "url",
491
+ url: "https://example.com/frame.jpg"
492
+ } })));
493
+ globalExpect(JSON.stringify(exit)).toContain("Unsupported");
494
+ }));
495
+ const sent = yield* server.sent;
496
+ globalExpect(sent.filter((f) => f.realtimeInput?.video !== void 0)).toEqual([{ realtimeInput: { video: {
497
+ data: Encoding.encodeBase64(new Uint8Array([1, 2])),
498
+ mimeType: "image/jpeg"
499
+ } } }]);
500
+ }).pipe(Effect.scoped));
501
+ });
502
+ //#endregion
503
+ export {};
504
+
505
+ //# sourceMappingURL=realtimeSession.test.mjs.map