@lunora/react 1.0.0-alpha.23 → 1.0.0-alpha.25

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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { LunoraClient, OptimisticUpdate, User, ConnectionStatus, ReturnOf, ArgsOf, FunctionReference, MutatorHandle, Preloaded } from '@lunora/client';
2
+ import { LunoraClient, OptimisticUpdate, User, FunctionReference, ConnectionStatus, ReturnOf, ArgsOf, MutatorHandle, Preloaded } from '@lunora/client';
3
3
  export { type ArgsOf, type FunctionReference, type LunoraClient, type LunoraErrorCode, type MutatorHandle, type MutatorTransaction, type OptimisticLocalStore, type OptimisticUpdate, type Preloaded, type ReturnOf, type User, getErrorCode, getRetryAfterMs, isConflictError, isForbiddenError, isRateLimitedError, isUnauthorizedError } from '@lunora/client';
4
4
  import { QueryClient } from '@tanstack/react-query';
5
5
  export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-D4okOpO8.mjs";
@@ -214,6 +214,395 @@ interface UseAuthResult {
214
214
  user: User | null;
215
215
  }
216
216
  /**
217
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
218
+ * `@lunora/agent`'s `AgentThreadStatus` — re-declared here (rather than imported)
219
+ * so this React entry never pulls in the server-only `@lunora/agent` module
220
+ * graph (the kit stays React + DOM only). Keep in sync with
221
+ * `packages/agent/src/types.ts`.
222
+ */
223
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
224
+ /**
225
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
226
+ * subset of the persisted thread row — every field beyond `status` is optional so
227
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
228
+ * `agent_threads` table in `packages/agent/src/component.ts`.
229
+ */
230
+ interface AgentThreadRecord {
231
+ createdAt?: number;
232
+ /** The failure message when `status === "error"`. */
233
+ error?: string;
234
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
235
+ instanceId?: string;
236
+ messageCount?: number;
237
+ /** The verified thread owner, when the run was started with one. */
238
+ owner?: string;
239
+ status: AgentThreadStatus;
240
+ title?: string;
241
+ updatedAt?: number;
242
+ }
243
+ /**
244
+ * The `agents.agentThread` reference the hook subscribes to for live thread state
245
+ * (status + the in-flight `instanceId`). A structural subset of the generated
246
+ * `api.agents` surface, so the whole generated `api` object is assignable.
247
+ */
248
+ interface UseAgentApi {
249
+ agents: {
250
+ agentThread: FunctionReference<"query", {
251
+ key: string;
252
+ }, Record<string, unknown> | undefined>;
253
+ };
254
+ }
255
+ interface UseAgentOptions {
256
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
257
+ api: UseAgentApi;
258
+ /**
259
+ * Optional app mutation over the agent's cancel path
260
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
261
+ * When omitted (or no run is in flight) {@link UseAgentResult.cancel} is a
262
+ * no-op.
263
+ */
264
+ cancel?: FunctionReference<"mutation">;
265
+ /**
266
+ * The app mutation that starts (or continues) a run — a thin wrapper over
267
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
268
+ * {@link UseAgentOptions.runArgs} and the per-call args.
269
+ */
270
+ run: FunctionReference<"mutation">;
271
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
272
+ runArgs?: Record<string, unknown>;
273
+ /** The thread to observe and drive. */
274
+ threadKey: string;
275
+ }
276
+ interface UseAgentResult {
277
+ /**
278
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
279
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
280
+ */
281
+ cancel: () => Promise<void>;
282
+ /** `true` while a `run` invocation is in flight. */
283
+ pending: boolean;
284
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
285
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
286
+ /** The live thread status, or `undefined` before the thread exists. */
287
+ status: AgentThreadStatus | undefined;
288
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
289
+ thread: AgentThreadRecord | undefined;
290
+ }
291
+ /**
292
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
293
+ * chat message surface. Composes `useSubscription(api.agents.agentThread)` for
294
+ * live state and `useMutation` for the run/cancel writes. For the full
295
+ * conversation surface (durable history + streaming + approvals) use
296
+ * `useAgentChat`.
297
+ *
298
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
299
+ * `ctx.agents.&lt;name>.run` / `.cancel`, so the hook hard-codes no function names
300
+ * beyond the `agents:*` surface.
301
+ */
302
+ declare const useAgent: (options: UseAgentOptions) => UseAgentResult;
303
+ /**
304
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
305
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
306
+ * re-declared here (rather than imported) so this React entry never pulls in the
307
+ * server-only `@lunora/agent` module graph. Keep in sync with the `agent_messages`
308
+ * table in `packages/agent/src/component.ts`.
309
+ */
310
+ interface AgentChatMessage {
311
+ content: string;
312
+ createdAt?: number;
313
+ /**
314
+ * `true` for a client-side optimistic user message not yet acknowledged by
315
+ * the server. Cleared once the durable history carries the matching user turn.
316
+ */
317
+ optimistic?: boolean;
318
+ role: "assistant" | "system" | "tool" | "user";
319
+ seq: number;
320
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
321
+ status?: "approved" | "awaiting_approval" | "rejected";
322
+ toolCallId?: string;
323
+ toolCalls?: ReadonlyArray<{
324
+ id: string;
325
+ input: unknown;
326
+ name: string;
327
+ }>;
328
+ toolName?: string;
329
+ }
330
+ /**
331
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
332
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
333
+ * {@link UseAgentChatResult.streamingText} live and are never replayed; the
334
+ * persisted assistant message stays the single source of truth.
335
+ */
336
+ interface AgentTokenDelta {
337
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
338
+ kind?: "token";
339
+ /** The incremental text chunk the model just produced. */
340
+ text: string;
341
+ /** The thread this delta belongs to. */
342
+ threadKey: string;
343
+ /** The zero-based index of the turn producing the delta. */
344
+ turn: number;
345
+ }
346
+ /**
347
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
348
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
349
+ * surfaced by `useAgentToolEvents`, ignored by {@link UseAgentChatResult.streamingText}.
350
+ */
351
+ interface AgentProgressEvent {
352
+ /** The arbitrary, JSON-serializable payload the tool reported. */
353
+ data: unknown;
354
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
355
+ kind: "progress";
356
+ /** The thread this event belongs to. */
357
+ threadKey: string;
358
+ /** The tool call this progress belongs to. */
359
+ toolCallId: string;
360
+ }
361
+ /**
362
+ * A single event on the agent's live-only channel — a streamed token delta or a
363
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
364
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
365
+ * it unset).
366
+ */
367
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
368
+ /** The `agents:agentMessages` reference — live durable thread history. */
369
+ type AgentMessagesReference$1 = FunctionReference<"query", {
370
+ key: string;
371
+ limit?: number;
372
+ }, ReadonlyArray<Record<string, unknown>>>;
373
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
374
+ type AgentApprovalReference = FunctionReference<"mutation", {
375
+ decision: "approve" | "reject";
376
+ instanceId: string;
377
+ note?: string;
378
+ threadKey: string;
379
+ toolCallId: string;
380
+ }, {
381
+ resolved: boolean;
382
+ }>;
383
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
384
+ type AgentThreadReference = FunctionReference<"query", {
385
+ key: string;
386
+ }, Record<string, unknown> | undefined>;
387
+ /**
388
+ * An app stream reference that tees the agent's in-flight live events, keyed by
389
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
390
+ * sink — tool progress events; this hook consumes only the token arm.
391
+ */
392
+ type AgentTokenStreamReference = FunctionReference<"stream", {
393
+ key: string;
394
+ }, AgentLiveEvent>;
395
+ /**
396
+ * The `agents.*` reference surface the chat hook reads. A structural subset of
397
+ * the generated `api.agents`, so the whole generated `api` object is assignable.
398
+ */
399
+ interface UseAgentChatApi {
400
+ agents: {
401
+ agentMessages: AgentMessagesReference$1;
402
+ agentResolveApproval: AgentApprovalReference;
403
+ agentThread: AgentThreadReference;
404
+ };
405
+ }
406
+ interface UseAgentChatOptions {
407
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
408
+ api: UseAgentChatApi;
409
+ /**
410
+ * Optional app mutation over the agent's cancel path
411
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
412
+ * When omitted (or no run is in flight) {@link UseAgentChatResult.cancel} is a
413
+ * no-op.
414
+ */
415
+ cancel?: FunctionReference<"mutation">;
416
+ /** History depth forwarded to `agents:agentMessages`. */
417
+ limit?: number;
418
+ /**
419
+ * The app mutation that starts (or continues) a run — a thin wrapper over
420
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
421
+ * {@link UseAgentChatOptions.sendArgs} and the per-call args.
422
+ */
423
+ send: FunctionReference<"mutation">;
424
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
425
+ sendArgs?: Record<string, unknown>;
426
+ /**
427
+ * Optional live token-delta stream — an app stream function that tees the
428
+ * agent's in-flight deltas. When omitted {@link UseAgentChatResult.streamingText}
429
+ * stays empty and the UI updates message-by-message from durable history.
430
+ */
431
+ stream?: AgentTokenStreamReference;
432
+ /** The thread to observe and continue. */
433
+ threadKey: string;
434
+ }
435
+ interface UseAgentChatResult {
436
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
437
+ approve: (toolCallId: string, note?: string) => Promise<void>;
438
+ /**
439
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
440
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
441
+ */
442
+ cancel: () => Promise<void>;
443
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
444
+ messages: ReadonlyArray<AgentChatMessage>;
445
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
446
+ reject: (toolCallId: string, note?: string) => Promise<void>;
447
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
448
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
449
+ /** The live thread status, or `undefined` before the thread exists. */
450
+ status: AgentThreadStatus | undefined;
451
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
452
+ streamingText: string;
453
+ }
454
+ /**
455
+ * A first-class agent chat surface: live durable history + in-flight token
456
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey`.
457
+ *
458
+ * It composes the existing primitives rather than adding transport:
459
+ * `useSubscription(api.agents.agentMessages)` for durable history,
460
+ * `useSubscription(api.agents.agentThread)` for live status + the in-flight
461
+ * `instanceId`, {@link useStream} over an app token stream for in-flight deltas,
462
+ * and `useMutation` for the writes (`api.agents.agentResolveApproval` for
463
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*`
464
+ * surface is hard-coded — `send`/`cancel`/`stream` stay generic references.
465
+ *
466
+ * A `send` optimistically appends the user turn so it renders immediately; the
467
+ * optimistic row clears once the durable history carries the acknowledged turn.
468
+ * `streamingText` is live-only: it holds the current turn's streamed text and
469
+ * empties as soon as that turn's assistant message lands in `messages` (the
470
+ * persisted message is the source of truth), consistent with the loop's
471
+ * replay-safe, live-only delta design.
472
+ */
473
+ declare const useAgentChat: (options: UseAgentChatOptions) => UseAgentChatResult;
474
+ /**
475
+ * The `agents.agentState` reference the hook subscribes to for the thread's live
476
+ * synced state. A structural subset of the generated `api.agents` surface (like
477
+ * `UseAgentApi` for `agentThread`), so the whole generated `api` object is
478
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type
479
+ * is mirrored by the hook's generic `T`, since codegen pins the reference return
480
+ * as an optional record (it never evaluates agent config).
481
+ */
482
+ interface UseAgentStateApi {
483
+ agents: {
484
+ agentState: FunctionReference<"query", {
485
+ key: string;
486
+ }, Record<string, unknown> | undefined>;
487
+ };
488
+ }
489
+ interface UseAgentStateOptions {
490
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
491
+ api: UseAgentStateApi;
492
+ /** The thread whose synced state to observe. */
493
+ threadKey: string;
494
+ }
495
+ interface UseAgentStateResult<T> {
496
+ /** The subscription error, if the live channel reported one. */
497
+ error: Error | undefined;
498
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
499
+ state: T | undefined;
500
+ }
501
+ /**
502
+ * Subscribe to an agent thread's synced state — the `setState`-style value a
503
+ * tool writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`.
504
+ * A thin wrapper over `useSubscription(api.agents.agentState, { key })`: the
505
+ * server pushes a fresh frame whenever the state changes (the dedicated query's
506
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
507
+ * `state` updates only on a real `setState`.
508
+ *
509
+ * Generic over the app's state shape (`useAgentState` with a `SupportState` type
510
+ * argument, itself a record) — the reference is typed as an optional record
511
+ * because codegen cannot see the per-agent state type; the generic casts to `T`.
512
+ * The `extends` bound (not a bare unbounded type parameter) is required: this
513
+ * `.ts` file is parsed JSX-aware by the bundler, where an unbounded type-param
514
+ * arrow is ambiguous with a JSX element.
515
+ */
516
+ declare const useAgentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: UseAgentStateOptions) => UseAgentStateResult<T>;
517
+ /** The `agents:agentMessages` reference — live durable thread history. */
518
+ type AgentMessagesReference = FunctionReference<"query", {
519
+ key: string;
520
+ limit?: number;
521
+ }, ReadonlyArray<Record<string, unknown>>>;
522
+ /**
523
+ * An app stream reference that tees the agent's in-flight live events, keyed by
524
+ * thread. Carries token deltas and tool progress events; this hook consumes only
525
+ * the progress arm (`kind === "progress"`).
526
+ */
527
+ type AgentLiveStreamReference = FunctionReference<"stream", {
528
+ key: string;
529
+ }, AgentLiveEvent>;
530
+ /**
531
+ * The `agents.*` reference surface the tool-events hook reads. A structural
532
+ * subset of the generated `api.agents`, so the whole generated `api` object is
533
+ * assignable.
534
+ */
535
+ interface UseAgentToolEventsApi {
536
+ agents: {
537
+ agentMessages: AgentMessagesReference;
538
+ };
539
+ }
540
+ interface UseAgentToolEventsOptions {
541
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
542
+ api: UseAgentToolEventsApi;
543
+ /** History depth forwarded to `agents:agentMessages`. */
544
+ limit?: number;
545
+ /**
546
+ * Optional live event stream — the same app stream function `useAgentChat`
547
+ * uses. When supplied, ephemeral `ctx.reportProgress(...)` events for the
548
+ * thread are surfaced as `{ type: "progress" }` entries; when omitted only the
549
+ * durable lifecycle (call / result / awaiting-approval) is returned.
550
+ */
551
+ stream?: AgentLiveStreamReference;
552
+ /** The thread whose tool activity to observe. */
553
+ threadKey: string;
554
+ }
555
+ /**
556
+ * A single tool-lifecycle event for a thread. The durable arms
557
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
558
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
559
+ * stream and has no `seq`. Discriminate on `type`.
560
+ */
561
+ type AgentToolEvent = {
562
+ data: unknown;
563
+ toolCallId: string;
564
+ type: "progress";
565
+ } | {
566
+ input: unknown;
567
+ seq: number;
568
+ toolCallId: string;
569
+ toolName: string;
570
+ type: "call";
571
+ } | {
572
+ output: string;
573
+ seq: number;
574
+ status?: "approved" | "rejected";
575
+ toolCallId?: string;
576
+ toolName?: string;
577
+ type: "result";
578
+ } | {
579
+ seq: number;
580
+ toolCallId?: string;
581
+ toolName?: string;
582
+ type: "awaiting-approval";
583
+ };
584
+ interface UseAgentToolEventsResult {
585
+ /**
586
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
587
+ * followed by any in-flight ephemeral progress events. Rebuilt each render
588
+ * from the live subscription + stream — treat as derived, not identity-stable.
589
+ */
590
+ events: ReadonlyArray<AgentToolEvent>;
591
+ }
592
+ /**
593
+ * A focused view of a thread's tool activity: tool calls, their results,
594
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
595
+ * without the full chat message surface. Composes the existing primitives:
596
+ * `useSubscription(api.agents.agentMessages)` for the durable lifecycle and
597
+ * {@link useStream} over the optional app event stream for ephemeral progress.
598
+ *
599
+ * Progress events are live-only (the durable path never emits them): they ride
600
+ * the same sink as token deltas and are surfaced here, correlated to their tool
601
+ * call by `toolCallId`. For the conversational surface (messages + streaming
602
+ * text + approvals) use `useAgentChat`; this hook is the tool-observability slice.
603
+ */
604
+ declare const useAgentToolEvents: (options: UseAgentToolEventsOptions) => UseAgentToolEventsResult;
605
+ /**
217
606
  * Token + identity plumbing. The token lives on the shared `LunoraClient`;
218
607
  * `setToken(jwt)` after a sign-in makes subsequent RPC calls carry the
219
608
  * `Authorization` header. `user` is resolved from better-auth's `get-session`
@@ -553,4 +942,151 @@ declare const useStream: <F extends FunctionReference<"stream">>(function_: F, a
553
942
  * the server pushes over the WS.
554
943
  */
555
944
  declare const useSubscription: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => UseSubscriptionResult<ReturnOf<F>>;
556
- export { AuthLoading, type AuthState, Authenticated, CheckoutButton, type CheckoutButtonProps, CustomerPortalButton, type CustomerPortalButtonProps, type FlagContext, type FlagValue, type HeartbeatReference, type ListPresentReference, LunoraProvider, type LunoraProviderProps, type MutationHook, type MutatorHook, type PageItemOf, type PaginatedArgs, type RedirectTarget, type RedirectTrigger, type Subscription, Unauthenticated, type UseAuthResult, type UseCheckoutResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationCallOptions, type UsePaginatedQueryOptions, type UsePaginatedQueryResult, type UsePresenceOptions, type UsePresenceResult, type UseQueryOptions, type UseRateLimitOptions, type UseRateLimitResult, type UseStreamOptions, type UseStreamResult, type UseStreamStatus, type UseSubscriptionResult, hydratePreloaded, useAuth, useAuthState, useCheckout, useConnectionStatus, useFlag, useFlags, useInfiniteQuery, useLunora, useMutation, useMutator, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription };
945
+ /**
946
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
947
+ * capture and speaker playback implementations injected into the hook via its
948
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
949
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
950
+ * hook's transport + React-state logic and remains mockable in a non-browser
951
+ * test env.
952
+ */
953
+ /**
954
+ * The negotiated audio format the voice DO streams back. Mirrors
955
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
956
+ * imported) so this React package never pulls in the server-only `@lunora/agent`
957
+ * module graph.
958
+ */
959
+ type VoiceAudioFormat = "mp3" | "wav";
960
+ /** Captures microphone audio and reports level / turn boundaries back to the hook. */
961
+ interface VoiceMicrophone {
962
+ /** Mute/unmute the mic without tearing down the capture graph. */
963
+ setMuted: (muted: boolean) => void;
964
+ /** Stop capture and release the media stream + audio graph. */
965
+ stop: () => void;
966
+ }
967
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
968
+ interface VoiceSpeaker {
969
+ /** Queue a decoded audio chunk for gap-minimized playback. */
970
+ enqueue: (audio: Uint8Array) => void;
971
+ /** Drop everything queued and stop the current chunk (barge-in). */
972
+ interrupt: () => void;
973
+ /** Release the playback audio context. */
974
+ stop: () => void;
975
+ }
976
+ /** Config passed to a {@link CreateMicrophone} factory. */
977
+ interface MicrophoneConfig {
978
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
979
+ interruptChunks: number;
980
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
981
+ interruptThreshold: number;
982
+ /** `true` while `status === "speaking"` — gates barge-in detection. */
983
+ isSpeaking: () => boolean;
984
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
985
+ onAudio: (pcm: Uint8Array) => void;
986
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
987
+ onInterrupt: () => void;
988
+ /** The current input RMS (0–1), for a level meter. */
989
+ onLevel: (rms: number) => void;
990
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
991
+ onSilence: () => void;
992
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
993
+ silenceDurationMs: number;
994
+ /** RMS below which audio counts as silence. */
995
+ silenceThreshold: number;
996
+ }
997
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
998
+ type CreateSpeaker = (config: {
999
+ audioFormat: VoiceAudioFormat;
1000
+ }) => VoiceSpeaker;
1001
+ /**
1002
+ * The default browser microphone: `getUserMedia` → a Web Audio `ScriptProcessor`
1003
+ * that tees 16 kHz PCM frames, tracks input RMS, auto-commits an utterance after
1004
+ * a silence gap, and flags a barge-in while the agent is speaking.
1005
+ */
1006
+ /**
1007
+ * The `agents.&lt;name>Voice` reference codegen emits for a voice-enabled agent — a
1008
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1009
+ * generated member, so passing `api.agents.&lt;name>Voice` type-checks.
1010
+ */
1011
+ type VoiceReference = FunctionReference<"stream", {
1012
+ threadKey: string;
1013
+ }, Record<string, unknown>>;
1014
+ /** The lifecycle of a voice call, mirrored to the UI. */
1015
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1016
+ /** A minimal structural subset of the DOM `WebSocket` the hook drives. */
1017
+ interface VoiceSocket {
1018
+ binaryType: string;
1019
+ close: () => void;
1020
+ onclose: ((event: unknown) => void) | null;
1021
+ onerror: ((event: unknown) => void) | null;
1022
+ onmessage: ((event: {
1023
+ data: unknown;
1024
+ }) => void) | null;
1025
+ onopen: ((event: unknown) => void) | null;
1026
+ readonly readyState: number;
1027
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1028
+ }
1029
+ type CreateSocket = (url: string) => VoiceSocket;
1030
+ interface UseVoiceAgentOptions {
1031
+ /**
1032
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1033
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1034
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1035
+ */
1036
+ createMicrophone?: CreateMicrophone;
1037
+ /** Advanced/test seam: open the transport. Defaults to `new WebSocket(url)`. */
1038
+ createSocket?: CreateSocket;
1039
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1040
+ createSpeaker?: CreateSpeaker;
1041
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1042
+ interruptChunks?: number;
1043
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1044
+ interruptThreshold?: number;
1045
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1046
+ silenceDurationMs?: number;
1047
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1048
+ silenceThreshold?: number;
1049
+ /** The thread to converse on — shared with the agent's text turns. */
1050
+ threadKey: string;
1051
+ /** The generated `api.agents.&lt;name>Voice` reference — identifies the voice DO endpoint. */
1052
+ voice: VoiceReference;
1053
+ }
1054
+ interface UseVoiceAgentResult {
1055
+ /** The current input RMS (0–1) — drive a mic level meter. */
1056
+ audioLevel: number;
1057
+ /** `true` once the WS `ready` handshake completed. */
1058
+ connected: boolean;
1059
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1060
+ endCall: () => void;
1061
+ /** The last transport/pipeline error, or `undefined`. */
1062
+ error: Error | undefined;
1063
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1064
+ interimTranscript: string;
1065
+ /** `true` while the mic is muted. */
1066
+ isMuted: boolean;
1067
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1068
+ sendText: (text: string) => void;
1069
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1070
+ startCall: () => Promise<void>;
1071
+ /** The current call lifecycle. */
1072
+ status: VoiceStatus;
1073
+ /** Mute/unmute the microphone. Returns the new muted state. */
1074
+ toggleMute: () => boolean;
1075
+ /** The last finalized user utterance (STT result). */
1076
+ transcript: string;
1077
+ }
1078
+ /**
1079
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1080
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1081
+ * streams the agent's synthesized speech back through the browser's audio output,
1082
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1083
+ * `audioLevel`) to React state. Pass the generated `api.agents.&lt;name>Voice`
1084
+ * reference (never a string), matching `useAgentChat`'s reference-passing style.
1085
+ *
1086
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1087
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1088
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1089
+ * `createSocket`) so the hook is drivable outside a browser.
1090
+ */
1091
+ declare const useVoiceAgent: (options: UseVoiceAgentOptions) => UseVoiceAgentResult;
1092
+ export { type AgentChatMessage, type AgentLiveEvent, type AgentProgressEvent, type AgentThreadRecord, type AgentThreadStatus, type AgentTokenDelta, type AgentToolEvent, AuthLoading, type AuthState, Authenticated, CheckoutButton, type CheckoutButtonProps, CustomerPortalButton, type CustomerPortalButtonProps, type FlagContext, type FlagValue, type HeartbeatReference, type ListPresentReference, LunoraProvider, type LunoraProviderProps, type MutationHook, type MutatorHook, type PageItemOf, type PaginatedArgs, type RedirectTarget, type RedirectTrigger, type Subscription, Unauthenticated, type UseAgentApi, type UseAgentChatApi, type UseAgentChatOptions, type UseAgentChatResult, type UseAgentOptions, type UseAgentResult, type UseAgentStateApi, type UseAgentStateOptions, type UseAgentStateResult, type UseAgentToolEventsApi, type UseAgentToolEventsOptions, type UseAgentToolEventsResult, type UseAuthResult, type UseCheckoutResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationCallOptions, type UsePaginatedQueryOptions, type UsePaginatedQueryResult, type UsePresenceOptions, type UsePresenceResult, type UseQueryOptions, type UseRateLimitOptions, type UseRateLimitResult, type UseStreamOptions, type UseStreamResult, type UseStreamStatus, type UseSubscriptionResult, type UseVoiceAgentOptions, type UseVoiceAgentResult, type VoiceAudioFormat, type VoiceReference, type VoiceStatus, hydratePreloaded, useAgent, useAgentChat, useAgentState, useAgentToolEvents, useAuth, useAuthState, useCheckout, useConnectionStatus, useFlag, useFlags, useInfiniteQuery, useLunora, useMutation, useMutator, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription, useVoiceAgent };