@lunora/react 1.0.0-alpha.3 → 1.0.0-alpha.30

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 (46) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/index.d.mts +913 -276
  5. package/dist/index.d.ts +913 -276
  6. package/dist/index.mjs +25 -15
  7. package/dist/packem_shared/{AuthLoading-DtKgZT2Z.mjs → AuthLoading-DezUWNB2.mjs} +1 -1
  8. package/dist/packem_shared/{CheckoutButton-CVSry8U1.mjs → CheckoutButton-DUite8jJ.mjs} +8 -4
  9. package/dist/packem_shared/{LunoraProvider-D38Xp16l.mjs → LunoraProvider-BsuiW4Lk.mjs} +3 -2
  10. package/dist/packem_shared/{cache-CItk3fgN.mjs → cache-JeuDAXfE.mjs} +6 -1
  11. package/dist/packem_shared/hydratePreloaded-2omLtadR.mjs +54 -0
  12. package/dist/packem_shared/{lunoraQueryOptions-CsuWzjg1.mjs → lunoraQueryOptions-CefbPBId.mjs} +1 -1
  13. package/dist/packem_shared/query-key-LGnArBTB.mjs +13 -0
  14. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.mts +38 -0
  15. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.ts +38 -0
  16. package/dist/packem_shared/stable-key-DePnevIy.mjs +38 -0
  17. package/dist/packem_shared/{use-paginated-core-CoOfcc-p.mjs → use-paginated-core-xxvd1YA0.mjs} +37 -19
  18. package/dist/packem_shared/useAgent-BNLlIYHz.mjs +101 -0
  19. package/dist/packem_shared/useAgentChat-0cebQe7-.mjs +304 -0
  20. package/dist/packem_shared/useAgentState-Cqyd3Dfy.mjs +37 -0
  21. package/dist/packem_shared/useAgentToolEvents-gF7U4_KY.mjs +129 -0
  22. package/dist/packem_shared/{useAuth-CNUKtOOp.mjs → useAuth-BSutjJaa.mjs} +1 -1
  23. package/dist/packem_shared/{useAuthState-BiGhtSCs.mjs → useAuthState-CyF35qZR.mjs} +1 -1
  24. package/dist/packem_shared/useClientQuery-DIkNT4QA.mjs +17 -0
  25. package/dist/packem_shared/{useConnectionStatus-DRSY9ldm.mjs → useConnectionStatus-PJ7vyCHy.mjs} +1 -1
  26. package/dist/packem_shared/useFlag-Beyeiq2b.mjs +128 -0
  27. package/dist/packem_shared/useHttpStream-oc4s1pMy.mjs +127 -0
  28. package/dist/packem_shared/{useInfiniteQuery-MH0x4l8h.mjs → useInfiniteQuery-CJNw1XaZ.mjs} +1 -1
  29. package/dist/packem_shared/{useMutation-CrvMXRsk.mjs → useMutation-BeqeIjTr.mjs} +1 -1
  30. package/dist/packem_shared/useMutator-IIrLtDiM.mjs +47 -0
  31. package/dist/packem_shared/{usePaginatedQuery-D3PTDRGS.mjs → usePaginatedQuery-DWzydaVR.mjs} +1 -1
  32. package/dist/packem_shared/{usePresence-D7jLuxj0.mjs → usePresence-Rnx1Fznc.mjs} +13 -6
  33. package/dist/packem_shared/useQuery-CE8_QUgh.mjs +77 -0
  34. package/dist/packem_shared/{useStream-BRY9nemd.mjs → useStream-GYNgc9J5.mjs} +6 -3
  35. package/dist/packem_shared/{useSubscription-CHMCjyQg.mjs → useSubscription-DcDlvVuI.mjs} +3 -3
  36. package/dist/packem_shared/useVoiceAgent-w7fzAMSB.mjs +422 -0
  37. package/dist/packem_shared/wire-key-Bg8BJ8YM.mjs +101 -0
  38. package/dist/server.d.mts +29 -29
  39. package/dist/server.d.ts +29 -29
  40. package/dist/server.mjs +2 -2
  41. package/package.json +6 -5
  42. package/dist/packem_shared/hydratePreloaded-BlFL9FGq.mjs +0 -46
  43. package/dist/packem_shared/query-key-C5rufkEE.mjs +0 -21
  44. package/dist/packem_shared/query-options.d-D4okOpO8.d.mts +0 -38
  45. package/dist/packem_shared/query-options.d-D4okOpO8.d.ts +0 -38
  46. package/dist/packem_shared/useQuery-C5S0W-7K.mjs +0 -41
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { LunoraClient, OptimisticUpdate, User, ConnectionStatus, ReturnOf, ArgsOf, FunctionReference, Preloaded } from '@lunora/client';
3
- export type { ArgsOf, FunctionReference, LunoraClient, OptimisticLocalStore, OptimisticUpdate, Preloaded, ReturnOf, User } from '@lunora/client';
2
+ import { LunoraClient, OptimisticUpdate, User, FunctionReference, ClientQueryRef, ConnectionStatus, ArgsOf, ReturnOf, HttpStreamRef, HttpStreamArgsOf, HttpStreamChunkOf, MutatorHandle, Preloaded } from '@lunora/client';
3
+ export { type ArgsOf, type ClientQueryRef, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamRef, type LunoraClient, type LunoraErrorCode, type MutatorHandle, type MutatorTransaction, type OptimisticLocalStore, type OptimisticUpdate, type Preloaded, type ReturnOf, type User, createClientQuery, getErrorCode, getRetryAfterMs, isConflictError, isForbiddenError, isRateLimitedError, isUnauthorizedError } from '@lunora/client';
4
4
  import { QueryClient } from '@tanstack/react-query';
5
- export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-D4okOpO8.mjs";
5
+ export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-CdgGQ9s4.mjs";
6
6
  import { PaginationStatus } from '@lunora/client/pagination';
7
7
  export type { PaginationResult, PaginationStatus } from '@lunora/client/pagination';
8
8
  import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
@@ -10,73 +10,63 @@ interface AuthGateProps {
10
10
  children: ReactNode;
11
11
  }
12
12
  /** Renders `children` only once a token is set on the client (after hydration). */
13
- declare const Authenticated: ({
14
- children
15
- }: AuthGateProps) => ReactNode;
13
+ declare const Authenticated: ({ children }: AuthGateProps) => ReactNode;
16
14
  /** Renders `children` only when auth has settled and no token is set. */
17
- declare const Unauthenticated: ({
18
- children
19
- }: AuthGateProps) => ReactNode;
15
+ declare const Unauthenticated: ({ children }: AuthGateProps) => ReactNode;
20
16
  /** Renders `children` while auth is still settling (before hydration completes). */
21
- declare const AuthLoading: ({
22
- children
23
- }: AuthGateProps) => ReactNode;
24
- /**
25
- * Resolved auth-gate state. `isLoading` covers the window before the client has
26
- * hydrated — the server render and the first hydration render both report
27
- * loading, so the markup agrees and no signed-out UI flashes in.
28
- */
17
+ declare const AuthLoading: ({ children }: AuthGateProps) => ReactNode;
18
+ /**
19
+ * Resolved auth-gate state. `isLoading` covers the window before the client has
20
+ * hydrated — the server render and the first hydration render both report
21
+ * loading, so the markup agrees and no signed-out UI flashes in.
22
+ */
29
23
  interface AuthState {
30
24
  isAuthenticated: boolean;
31
25
  isLoading: boolean;
32
26
  }
33
27
  /**
34
- * Three-state auth status for gating UI. Reports `isLoading` until the client
35
- * has hydrated, then `isAuthenticated` tracks whether a token is set on the
36
- * shared client.
37
- *
38
- * Lunora auth is token-based and resolves synchronously once the token is
39
- * known, so the loading window is hydration rather than a server round-trip —
40
- * use it (via {@link AuthState}) to render a fallback while it settles.
41
- */
28
+ * Three-state auth status for gating UI. Reports `isLoading` until the client
29
+ * has hydrated, then `isAuthenticated` tracks whether a token is set on the
30
+ * shared client.
31
+ *
32
+ * Lunora auth is token-based and resolves synchronously once the token is
33
+ * known, so the loading window is hydration rather than a server round-trip —
34
+ * use it (via {@link AuthState}) to render a fallback while it settles.
35
+ */
42
36
  declare const useAuthState: () => AuthState;
43
37
  interface LunoraProviderProps {
44
38
  children: ReactNode;
45
39
  client: LunoraClient;
46
40
  /**
47
- * Bring-your-own QueryClient. When omitted, the provider creates one with
48
- * defaults tuned for Lunora's push-driven model: `staleTime: Infinity` (the
49
- * WS subscription is the only invalidation signal), `retry: 0` (failures
50
- * route through the offline queue on the client), and `gcTime: 5min` (keep
51
- * results around for a short return-to-view window).
52
- *
53
- * If a parent `<QueryClientProvider>` is already mounted, the provider
54
- * uses *that* client and does NOT install an inner one (so apps with their
55
- * own setup don't double-wrap).
56
- */
41
+ * Bring-your-own QueryClient. When omitted, the provider creates one with
42
+ * defaults tuned for Lunora's push-driven model: `staleTime: Infinity` (the
43
+ * WS subscription is the only invalidation signal), `retry: 0` (failures
44
+ * route through the offline queue on the client), and `gcTime: 5min` (keep
45
+ * results around for a short return-to-view window).
46
+ *
47
+ * If a parent `<QueryClientProvider>` is already mounted, the provider
48
+ * uses *that* client and does NOT install an inner one (so apps with their
49
+ * own setup don't double-wrap).
50
+ */
57
51
  queryClient?: QueryClient;
58
52
  }
59
53
  /**
60
- * Provides both the {@link LunoraClient} and a TanStack `QueryClient` to the
61
- * tree. The detection logic for a parent QueryClientProvider keeps this safe to
62
- * drop into an app that already runs TanStack Query for its own purposes.
63
- */
64
- declare const LunoraProvider: ({
65
- children,
66
- client,
67
- queryClient
68
- }: LunoraProviderProps) => ReactElement;
54
+ * Provides both the {@link LunoraClient} and a TanStack `QueryClient` to the
55
+ * tree. The detection logic for a parent QueryClientProvider keeps this safe to
56
+ * drop into an app that already runs TanStack Query for its own purposes.
57
+ */
58
+ declare const LunoraProvider: ({ children, client, queryClient }: LunoraProviderProps) => ReactElement;
69
59
  /**
70
- * Read the {@link LunoraClient} from the nearest `<LunoraProvider>`. Kept
71
- * colocated with the provider for back-compat.
72
- */
60
+ * Read the {@link LunoraClient} from the nearest `<LunoraProvider>`. Kept
61
+ * colocated with the provider for back-compat.
62
+ */
73
63
  declare const useLunora: () => LunoraClient;
74
64
  /**
75
- * Client-safe mirror of `@lunora/payment`'s `Subscription`. Re-declared here
76
- * (rather than imported) so this React entry never pulls in the server-only
77
- * `@lunora/payment` module graph — the kit stays React + DOM only. Keep this in
78
- * sync with `packages/payment/src/types.ts`.
79
- */
65
+ * Client-safe mirror of `@lunora/payment`'s `Subscription`. Re-declared here
66
+ * (rather than imported) so this React entry never pulls in the server-only
67
+ * `@lunora/payment` module graph — the kit stays React + DOM only. Keep this in
68
+ * sync with `packages/payment/src/types.ts`.
69
+ */
80
70
  interface Subscription {
81
71
  readonly cancelAtPeriodEnd: boolean;
82
72
  readonly createdAt: number;
@@ -104,24 +94,24 @@ interface UseCheckoutResult {
104
94
  pending: boolean;
105
95
  }
106
96
  /**
107
- * Decoupled redirect-on-resolve primitive shared by `CheckoutButton` and
108
- * `CustomerPortalButton`. The app passes a `trigger` thunk that calls its own
109
- * Lunora action (the one wrapping `LunoraPayment.createCheckout` /
110
- * `createPortalSession`) and resolves `{ url }`; this hook awaits it, flips
111
- * `pending`, surfaces any `error`, and on success navigates via
112
- * `location.assign(url)`.
113
- *
114
- * Mirrors Convex's `CheckoutLink` / `CustomerPortalLink` flow (trigger an action
115
- * that returns a URL, then redirect) while staying agnostic of the app's
116
- * function names.
117
- */
97
+ * Decoupled redirect-on-resolve primitive shared by `CheckoutButton` and
98
+ * `CustomerPortalButton`. The app passes a `trigger` thunk that calls its own
99
+ * Lunora action (the one wrapping `LunoraPayment.createCheckout` /
100
+ * `createPortalSession`) and resolves `{ url }`; this hook awaits it, flips
101
+ * `pending`, surfaces any `error`, and on success navigates via
102
+ * `location.assign(url)`.
103
+ *
104
+ * Mirrors Convex's `CheckoutLink` / `CustomerPortalLink` flow (trigger an action
105
+ * that returns a URL, then redirect) while staying agnostic of the app's
106
+ * function names.
107
+ */
118
108
  declare const useCheckout: (trigger: RedirectTrigger) => UseCheckoutResult;
119
109
  /**
120
- * Presentational props shared by the redirect buttons. Kept to a curated set
121
- * (rather than spreading arbitrary button attributes) so the component stays
122
- * within the repo's `react/jsx-props-no-spreading` rule while covering the
123
- * common styling / accessibility hooks.
124
- */
110
+ * Presentational props shared by the redirect buttons. Kept to a curated set
111
+ * (rather than spreading arbitrary button attributes) so the component stays
112
+ * within the repo's `react/jsx-props-no-spreading` rule while covering the
113
+ * common styling / accessibility hooks.
114
+ */
125
115
  interface RedirectButtonOwnProps {
126
116
  /** Accessible label when the visible `children` are icon-only. */
127
117
  "aria-label"?: string;
@@ -142,33 +132,27 @@ interface CustomerPortalButtonProps extends RedirectButtonOwnProps {
142
132
  onPortal: RedirectTrigger;
143
133
  }
144
134
  /**
145
- * Button that starts a hosted checkout. On click it awaits `onCheckout` (a thunk
146
- * that calls the app's checkout action) and redirects to the returned URL,
147
- * disabling itself while the request is in flight.
148
- */
149
- declare const CheckoutButton: ({
150
- onCheckout,
151
- ...rest
152
- }: CheckoutButtonProps) => ReactNode;
153
- /**
154
- * Button that opens the provider's customer portal. On click it awaits
155
- * `onPortal` (a thunk that calls the app's portal action) and redirects to the
156
- * returned URL, disabling itself while the request is in flight.
157
- */
158
- declare const CustomerPortalButton: ({
159
- onPortal,
160
- ...rest
161
- }: CustomerPortalButtonProps) => ReactNode;
135
+ * Button that starts a hosted checkout. On click it awaits `onCheckout` (a thunk
136
+ * that calls the app's checkout action) and redirects to the returned URL,
137
+ * disabling itself while the request is in flight.
138
+ */
139
+ declare const CheckoutButton: ({ onCheckout, ...rest }: CheckoutButtonProps) => ReactNode;
140
+ /**
141
+ * Button that opens the provider's customer portal. On click it awaits
142
+ * `onPortal` (a thunk that calls the app's portal action) and redirects to the
143
+ * returned URL, disabling itself while the request is in flight.
144
+ */
145
+ declare const CustomerPortalButton: ({ onPortal, ...rest }: CustomerPortalButtonProps) => ReactNode;
162
146
  interface UseQueryOptions {
163
147
  shardKey?: string;
164
148
  }
165
149
  interface UseMutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
166
150
  optimistic?: (current: TCurrent | undefined) => TValue;
167
151
  /**
168
- * Convex-parity multi-query optimistic update forwarded to
169
- * `client.mutation`. Patches many subscribed queries at once via an
170
- * `OptimisticLocalStore`, rolled back atomically on failure.
171
- */
152
+ * Convex-parity multi-query optimistic update forwarded to
153
+ * `client.mutation`. Patches many subscribed queries at once via an
154
+ * `OptimisticLocalStore`, rolled back atomically on failure.
155
+ */
172
156
  optimisticUpdate?: OptimisticUpdate<TArgs>;
173
157
  shardKey?: string;
174
158
  }
@@ -214,25 +198,530 @@ interface UseAuthResult {
214
198
  user: User | null;
215
199
  }
216
200
  /**
217
- * Token + identity plumbing. The token lives on the shared `LunoraClient`;
218
- * `setToken(jwt)` after a sign-in makes subsequent RPC calls carry the
219
- * `Authorization` header. `user` is resolved from better-auth's `get-session`
220
- * endpoint via `client.getCurrentUser()` fetched on mount and refetched
221
- * whenever the token changes (`onAuthTokenChange`), and `null` when signed out.
222
- *
223
- * Multiple `useAuth` instances stay in sync: both `token` and `user` are read
224
- * through `useSyncExternalStore` over the shared client (and a per-client
225
- * identity store), so a `setToken` from one component re-renders every mounted
226
- * hook with the freshly-resolved user.
227
- */
201
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
202
+ * `@lunora/agent`'s `AgentThreadStatus` re-declared here (rather than imported)
203
+ * so this React entry never pulls in the server-only `@lunora/agent` module
204
+ * graph (the kit stays React + DOM only). Keep in sync with
205
+ * `packages/agent/src/types.ts`.
206
+ */
207
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
208
+ /**
209
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
210
+ * subset of the persisted thread row — every field beyond `status` is optional so
211
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
212
+ * `agent_threads` table in `packages/agent/src/component.ts`.
213
+ */
214
+ interface AgentThreadRecord {
215
+ createdAt?: number;
216
+ /** The failure message when `status === "error"`. */
217
+ error?: string;
218
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
219
+ instanceId?: string;
220
+ messageCount?: number;
221
+ /** The verified thread owner, when the run was started with one. */
222
+ owner?: string;
223
+ status: AgentThreadStatus;
224
+ title?: string;
225
+ updatedAt?: number;
226
+ }
227
+ /**
228
+ * The `agents.agentThread` reference the hook subscribes to for live thread state
229
+ * (status + the in-flight `instanceId`). A structural subset of the generated
230
+ * `api.agents` surface, so the whole generated `api` object is assignable.
231
+ */
232
+ interface UseAgentApi {
233
+ agents: {
234
+ agentThread: FunctionReference<"query", {
235
+ key: string;
236
+ }, Record<string, unknown> | undefined>;
237
+ };
238
+ }
239
+ interface UseAgentOptions {
240
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
241
+ api: UseAgentApi;
242
+ /**
243
+ * Optional app mutation over the agent's cancel path
244
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
245
+ * When omitted (or no run is in flight) {@link UseAgentResult.cancel} is a
246
+ * no-op.
247
+ */
248
+ cancel?: FunctionReference<"mutation">;
249
+ /**
250
+ * The app mutation that starts (or continues) a run — a thin wrapper over
251
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
252
+ * {@link UseAgentOptions.runArgs} and the per-call args.
253
+ */
254
+ run: FunctionReference<"mutation">;
255
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
256
+ runArgs?: Record<string, unknown>;
257
+ /** The thread to observe and drive. */
258
+ threadKey: string;
259
+ }
260
+ interface UseAgentResult {
261
+ /**
262
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
263
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
264
+ */
265
+ cancel: () => Promise<void>;
266
+ /** `true` while a `run` invocation is in flight. */
267
+ pending: boolean;
268
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
269
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
270
+ /** The live thread status, or `undefined` before the thread exists. */
271
+ status: AgentThreadStatus | undefined;
272
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
273
+ thread: AgentThreadRecord | undefined;
274
+ }
275
+ /**
276
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
277
+ * chat message surface. Composes `useSubscription(api.agents.agentThread)` for
278
+ * live state and `useMutation` for the run/cancel writes. For the full
279
+ * conversation surface (durable history + streaming + approvals) use
280
+ * `useAgentChat`.
281
+ *
282
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
283
+ * `ctx.agents.&lt;name>.run` / `.cancel`, so the hook hard-codes no function names
284
+ * beyond the `agents:*` surface.
285
+ */
286
+ declare const useAgent: (options: UseAgentOptions) => UseAgentResult;
287
+ /**
288
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
289
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
290
+ * re-declared here (rather than imported) so this React entry never pulls in the
291
+ * server-only `@lunora/agent` module graph. Keep in sync with the `agent_messages`
292
+ * table in `packages/agent/src/component.ts`.
293
+ */
294
+ interface AgentChatMessage {
295
+ content: string;
296
+ createdAt?: number;
297
+ /**
298
+ * `true` for a client-side optimistic user message not yet acknowledged by
299
+ * the server. Cleared once the durable history carries the matching user turn.
300
+ */
301
+ optimistic?: boolean;
302
+ role: "assistant" | "system" | "tool" | "user";
303
+ seq: number;
304
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
305
+ status?: "approved" | "awaiting_approval" | "rejected";
306
+ toolCallId?: string;
307
+ toolCalls?: ReadonlyArray<{
308
+ id: string;
309
+ input: unknown;
310
+ name: string;
311
+ }>;
312
+ toolName?: string;
313
+ }
314
+ /**
315
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
316
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
317
+ * {@link UseAgentChatResult.streamingText} live and are never replayed; the
318
+ * persisted assistant message stays the single source of truth.
319
+ */
320
+ interface AgentTokenDelta {
321
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
322
+ kind?: "token";
323
+ /** The incremental text chunk the model just produced. */
324
+ text: string;
325
+ /** The thread this delta belongs to. */
326
+ threadKey: string;
327
+ /** The zero-based index of the turn producing the delta. */
328
+ turn: number;
329
+ }
330
+ /**
331
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
332
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
333
+ * surfaced by `useAgentToolEvents`, ignored by {@link UseAgentChatResult.streamingText}.
334
+ */
335
+ interface AgentProgressEvent {
336
+ /** The arbitrary, JSON-serializable payload the tool reported. */
337
+ data: unknown;
338
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
339
+ kind: "progress";
340
+ /** The thread this event belongs to. */
341
+ threadKey: string;
342
+ /** The tool call this progress belongs to. */
343
+ toolCallId: string;
344
+ }
345
+ /**
346
+ * A single event on the agent's live-only channel — a streamed token delta or a
347
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
348
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
349
+ * it unset).
350
+ */
351
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
352
+ /** The `agents:agentMessages` reference — live durable thread history. */
353
+ type AgentMessagesReference$1 = FunctionReference<"query", {
354
+ key: string;
355
+ limit?: number;
356
+ }, ReadonlyArray<Record<string, unknown>>>;
357
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
358
+ type AgentApprovalReference = FunctionReference<"mutation", {
359
+ decision: "approve" | "reject";
360
+ instanceId: string;
361
+ note?: string;
362
+ threadKey: string;
363
+ toolCallId: string;
364
+ }, {
365
+ resolved: boolean;
366
+ }>;
367
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
368
+ type AgentThreadReference = FunctionReference<"query", {
369
+ key: string;
370
+ }, Record<string, unknown> | undefined>;
371
+ /**
372
+ * An app stream reference that tees the agent's in-flight live events, keyed by
373
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
374
+ * sink — tool progress events; this hook consumes only the token arm.
375
+ */
376
+ type AgentTokenStreamReference = FunctionReference<"stream", {
377
+ key: string;
378
+ }, AgentLiveEvent>;
379
+ /**
380
+ * The `agents.*` reference surface the chat hook reads. A structural subset of
381
+ * the generated `api.agents`, so the whole generated `api` object is assignable.
382
+ */
383
+ interface UseAgentChatApi {
384
+ agents: {
385
+ agentMessages: AgentMessagesReference$1;
386
+ agentResolveApproval: AgentApprovalReference;
387
+ agentThread: AgentThreadReference;
388
+ };
389
+ }
390
+ interface UseAgentChatOptions {
391
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
392
+ api: UseAgentChatApi;
393
+ /**
394
+ * Optional app mutation over the agent's cancel path
395
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
396
+ * When omitted (or no run is in flight) {@link UseAgentChatResult.cancel} is a
397
+ * no-op.
398
+ */
399
+ cancel?: FunctionReference<"mutation">;
400
+ /** History depth forwarded to `agents:agentMessages`. */
401
+ limit?: number;
402
+ /**
403
+ * The app mutation that starts (or continues) a run — a thin wrapper over
404
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
405
+ * {@link UseAgentChatOptions.sendArgs} and the per-call args.
406
+ */
407
+ send: FunctionReference<"mutation">;
408
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
409
+ sendArgs?: Record<string, unknown>;
410
+ /**
411
+ * Optional live token-delta stream — an app stream function that tees the
412
+ * agent's in-flight deltas. When omitted {@link UseAgentChatResult.streamingText}
413
+ * stays empty and the UI updates message-by-message from durable history.
414
+ */
415
+ stream?: AgentTokenStreamReference;
416
+ /** The thread to observe and continue. */
417
+ threadKey: string;
418
+ }
419
+ interface UseAgentChatResult {
420
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
421
+ approve: (toolCallId: string, note?: string) => Promise<void>;
422
+ /**
423
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
424
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
425
+ */
426
+ cancel: () => Promise<void>;
427
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
428
+ messages: ReadonlyArray<AgentChatMessage>;
429
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
430
+ reject: (toolCallId: string, note?: string) => Promise<void>;
431
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
432
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
433
+ /** The live thread status, or `undefined` before the thread exists. */
434
+ status: AgentThreadStatus | undefined;
435
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
436
+ streamingText: string;
437
+ }
438
+ /**
439
+ * A first-class agent chat surface: live durable history + in-flight token
440
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey`.
441
+ *
442
+ * It composes the existing primitives rather than adding transport:
443
+ * `useSubscription(api.agents.agentMessages)` for durable history,
444
+ * `useSubscription(api.agents.agentThread)` for live status + the in-flight
445
+ * `instanceId`, {@link useStream} over an app token stream for in-flight deltas,
446
+ * and `useMutation` for the writes (`api.agents.agentResolveApproval` for
447
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*`
448
+ * surface is hard-coded — `send`/`cancel`/`stream` stay generic references.
449
+ *
450
+ * A `send` optimistically appends the user turn so it renders immediately; the
451
+ * optimistic row clears once the durable history carries the acknowledged turn.
452
+ * `streamingText` is live-only: it holds the current turn's streamed text and
453
+ * empties as soon as that turn's assistant message lands in `messages` (the
454
+ * persisted message is the source of truth), consistent with the loop's
455
+ * replay-safe, live-only delta design.
456
+ */
457
+ declare const useAgentChat: (options: UseAgentChatOptions) => UseAgentChatResult;
458
+ /**
459
+ * The `agents.agentState` reference the hook subscribes to for the thread's live
460
+ * synced state. A structural subset of the generated `api.agents` surface (like
461
+ * `UseAgentApi` for `agentThread`), so the whole generated `api` object is
462
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type
463
+ * is mirrored by the hook's generic `T`, since codegen pins the reference return
464
+ * as an optional record (it never evaluates agent config).
465
+ */
466
+ interface UseAgentStateApi {
467
+ agents: {
468
+ agentState: FunctionReference<"query", {
469
+ key: string;
470
+ }, Record<string, unknown> | undefined>;
471
+ };
472
+ }
473
+ interface UseAgentStateOptions {
474
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
475
+ api: UseAgentStateApi;
476
+ /** The thread whose synced state to observe. */
477
+ threadKey: string;
478
+ }
479
+ interface UseAgentStateResult<T> {
480
+ /** The subscription error, if the live channel reported one. */
481
+ error: Error | undefined;
482
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
483
+ state: T | undefined;
484
+ }
485
+ /**
486
+ * Subscribe to an agent thread's synced state — the `setState`-style value a
487
+ * tool writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`.
488
+ * A thin wrapper over `useSubscription(api.agents.agentState, { key })`: the
489
+ * server pushes a fresh frame whenever the state changes (the dedicated query's
490
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
491
+ * `state` updates only on a real `setState`.
492
+ *
493
+ * Generic over the app's state shape (`useAgentState` with a `SupportState` type
494
+ * argument, itself a record) — the reference is typed as an optional record
495
+ * because codegen cannot see the per-agent state type; the generic casts to `T`.
496
+ * The `extends` bound (not a bare unbounded type parameter) is required: this
497
+ * `.ts` file is parsed JSX-aware by the bundler, where an unbounded type-param
498
+ * arrow is ambiguous with a JSX element.
499
+ */
500
+ declare const useAgentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: UseAgentStateOptions) => UseAgentStateResult<T>;
501
+ /** The `agents:agentMessages` reference — live durable thread history. */
502
+ type AgentMessagesReference = FunctionReference<"query", {
503
+ key: string;
504
+ limit?: number;
505
+ }, ReadonlyArray<Record<string, unknown>>>;
506
+ /**
507
+ * An app stream reference that tees the agent's in-flight live events, keyed by
508
+ * thread. Carries token deltas and tool progress events; this hook consumes only
509
+ * the progress arm (`kind === "progress"`).
510
+ */
511
+ type AgentLiveStreamReference = FunctionReference<"stream", {
512
+ key: string;
513
+ }, AgentLiveEvent>;
514
+ /**
515
+ * The `agents.*` reference surface the tool-events hook reads. A structural
516
+ * subset of the generated `api.agents`, so the whole generated `api` object is
517
+ * assignable.
518
+ */
519
+ interface UseAgentToolEventsApi {
520
+ agents: {
521
+ agentMessages: AgentMessagesReference;
522
+ };
523
+ }
524
+ interface UseAgentToolEventsOptions {
525
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
526
+ api: UseAgentToolEventsApi;
527
+ /** History depth forwarded to `agents:agentMessages`. */
528
+ limit?: number;
529
+ /**
530
+ * Optional live event stream — the same app stream function `useAgentChat`
531
+ * uses. When supplied, ephemeral `ctx.reportProgress(...)` events for the
532
+ * thread are surfaced as `{ type: "progress" }` entries; when omitted only the
533
+ * durable lifecycle (call / result / awaiting-approval) is returned.
534
+ */
535
+ stream?: AgentLiveStreamReference;
536
+ /** The thread whose tool activity to observe. */
537
+ threadKey: string;
538
+ }
539
+ /**
540
+ * A single tool-lifecycle event for a thread. The durable arms
541
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
542
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
543
+ * stream and has no `seq`. Discriminate on `type`.
544
+ */
545
+ type AgentToolEvent = {
546
+ data: unknown;
547
+ toolCallId: string;
548
+ type: "progress";
549
+ } | {
550
+ input: unknown;
551
+ seq: number;
552
+ toolCallId: string;
553
+ toolName: string;
554
+ type: "call";
555
+ } | {
556
+ output: string;
557
+ seq: number;
558
+ status?: "approved" | "rejected";
559
+ toolCallId?: string;
560
+ toolName?: string;
561
+ type: "result";
562
+ } | {
563
+ seq: number;
564
+ toolCallId?: string;
565
+ toolName?: string;
566
+ type: "awaiting-approval";
567
+ };
568
+ interface UseAgentToolEventsResult {
569
+ /**
570
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
571
+ * followed by any in-flight ephemeral progress events. Rebuilt each render
572
+ * from the live subscription + stream — treat as derived, not identity-stable.
573
+ */
574
+ events: ReadonlyArray<AgentToolEvent>;
575
+ }
576
+ /**
577
+ * A focused view of a thread's tool activity: tool calls, their results,
578
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
579
+ * without the full chat message surface. Composes the existing primitives:
580
+ * `useSubscription(api.agents.agentMessages)` for the durable lifecycle and
581
+ * {@link useStream} over the optional app event stream for ephemeral progress.
582
+ *
583
+ * Progress events are live-only (the durable path never emits them): they ride
584
+ * the same sink as token deltas and are surfaced here, correlated to their tool
585
+ * call by `toolCallId`. For the conversational surface (messages + streaming
586
+ * text + approvals) use `useAgentChat`; this hook is the tool-observability slice.
587
+ */
588
+ declare const useAgentToolEvents: (options: UseAgentToolEventsOptions) => UseAgentToolEventsResult;
589
+ /**
590
+ * Token + identity plumbing. The token lives on the shared `LunoraClient`;
591
+ * `setToken(jwt)` after a sign-in makes subsequent RPC calls carry the
592
+ * `Authorization` header. `user` is resolved from better-auth's `get-session`
593
+ * endpoint via `client.getCurrentUser()` — fetched on mount and refetched
594
+ * whenever the token changes (`onAuthTokenChange`), and `null` when signed out.
595
+ *
596
+ * Multiple `useAuth` instances stay in sync: both `token` and `user` are read
597
+ * through `useSyncExternalStore` over the shared client (and a per-client
598
+ * identity store), so a `setToken` from one component re-renders every mounted
599
+ * hook with the freshly-resolved user.
600
+ */
228
601
  declare const useAuth: () => UseAuthResult;
602
+ type Setter<T> = (value: T) => void;
603
+ /**
604
+ * Subscribe to a local-only {@link ClientQueryRef} and re-render when its
605
+ * value changes. Unlike `useQuery`, this never touches the network — the
606
+ * value lives in a reactive store on the `LunoraClient` instance and is shared
607
+ * across every consumer of the same ref.
608
+ *
609
+ * The initial render reads the store synchronously (via
610
+ * `useSyncExternalStore`), so there is never an "undefined flash" — the value
611
+ * is either the one most recently set or `ref.defaultValue`.
612
+ *
613
+ * Returns a `[value, setter]` tuple, matching the `useState` convention.
614
+ * @example
615
+ * ```tsx
616
+ * import { useClientQuery, createClientQuery } from "@lunora/react";
617
+ *
618
+ * const sidebarOpen = createClientQuery("sidebarOpen", true);
619
+ *
620
+ * function Sidebar() {
621
+ * const [open, setOpen] = useClientQuery(sidebarOpen);
622
+ * return <aside data-open={open}>…</aside>;
623
+ * }
624
+ * ```
625
+ */
626
+ declare const useClientQuery: <T extends unknown>(ref: ClientQueryRef<T>) => [T, Setter<T>];
229
627
  /**
230
- * Reactive view of the client's aggregate live-socket status across all shard
231
- * connections. Re-renders on every transition (`idle` → `connecting` →
232
- * `connected` → `offline`). Use it to drive a connection indicator so an
233
- * operator can tell a healthy live channel from a silently-dropped socket.
234
- */
628
+ * Reactive view of the client's aggregate live-socket status across all shard
629
+ * connections. Re-renders on every transition (`idle` → `connecting` →
630
+ * `connected` → `offline`). Use it to drive a connection indicator so an
631
+ * operator can tell a healthy live channel from a silently-dropped socket.
632
+ */
235
633
  declare const useConnectionStatus: () => ConnectionStatus;
634
+ /** A targeting context merged on top of the app's default (`defineFlags({ identify })`). */
635
+ type FlagContext = Record<string, unknown>;
636
+ /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
637
+ type FlagValue = boolean | number | string | {
638
+ [key: string]: unknown;
639
+ } | unknown[] | null;
640
+ /**
641
+ * Subscribe to a single feature flag, live over Lunora's WebSocket.
642
+ *
643
+ * Returns `defaultValue` until the first evaluation lands, then the server's
644
+ * resolved value — re-pushed whenever the provider re-evaluates (e.g. a flag is
645
+ * toggled in Cloudflare Flagship). The flag's kind is inferred from
646
+ * `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean and
647
+ * `useFlag("hero", "control")` a string. `context` supplies a per-call targeting
648
+ * context merged on top of the app's default `identify` targeting key.
649
+ *
650
+ * Evaluation runs through whatever OpenFeature provider the app wired in
651
+ * `lunora/flags.ts`; the read never throws — a provider error resolves the
652
+ * default (the same fail-open contract as server-side `ctx.flags`).
653
+ */
654
+ declare const useFlag: <T extends FlagValue>(key: string, defaultValue: T, context?: FlagContext) => T;
655
+ /**
656
+ * Subscribe to several feature flags at once, live over Lunora's WebSocket.
657
+ *
658
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
659
+ * default, and the result is the same-shaped record with resolved values (the
660
+ * defaults until each evaluation lands). A single `context` applies to every
661
+ * flag. This is the batched form of {@link useFlag} — one effect manages one
662
+ * subscription per key, so it stays rules-of-hooks-safe even as the flag set
663
+ * changes between renders.
664
+ */
665
+ declare const useFlags: <T extends Record<string, FlagValue>>(flags: T, context?: FlagContext) => T;
666
+ /** The lifecycle of a stream the hook is observing. */
667
+ type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
668
+ interface UseStreamResult<T> {
669
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
670
+ cancel: () => void;
671
+ /** Chunks the server has pushed so far, in arrival order. */
672
+ chunks: ReadonlyArray<T>;
673
+ error: Error | undefined;
674
+ status: UseStreamStatus;
675
+ }
676
+ interface UseStreamOptions {
677
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
678
+ maxBuffer?: number;
679
+ shardKey?: string;
680
+ }
681
+ /**
682
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
683
+ * lifecycle status and a cancel function. Changing `fn` or the serialized
684
+ * `args` resets the stream — the previous iterator is cancelled and a fresh
685
+ * one opens with empty `chunks`.
686
+ *
687
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
688
+ * (mirrors `useQuery` / `useSubscription`).
689
+ */
690
+ declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: "skip" | ArgsOf<F>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
691
+ /**
692
+ * Result shape returned by {@link useHttpStream}.
693
+ * @experimental Part of the HTTP-SSE stream surface.
694
+ */
695
+ interface UseHttpStreamResult<T> {
696
+ /** Force-cancel the stream (aborts the fetch) and resolve the iterator. Safe to call multiple times. */
697
+ cancel: () => void;
698
+ /** Chunks the server has pushed so far, in arrival order. */
699
+ chunks: ReadonlyArray<T>;
700
+ error: Error | undefined;
701
+ status: UseStreamStatus;
702
+ }
703
+ /**
704
+ * Options accepted by {@link useHttpStream}.
705
+ * @experimental Part of the HTTP-SSE stream surface.
706
+ */
707
+ interface UseHttpStreamOptions {
708
+ /** Forwarded to `client.httpStream()` — caps the in-flight chunk buffer. */
709
+ maxBuffer?: number;
710
+ }
711
+ /**
712
+ * Consume an **HTTP-SSE route stream** (`httpRoute.&lt;verb>(path).stream()`) via
713
+ * `client.httpStream`. Distinct from `useStream`, which consumes the WS
714
+ * procedure stream (`kind: "stream"`). Returns the chunks received so far plus
715
+ * a lifecycle status and a cancel function. Changing the route or the
716
+ * serialized `args` resets the stream — the previous fetch is aborted (the
717
+ * server sees `request.signal`) and a fresh one opens with empty `chunks`.
718
+ * Unmount also aborts.
719
+ *
720
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
721
+ * (mirrors `useQuery` / `useStream`).
722
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
723
+ */
724
+ declare const useHttpStream: <Ref extends HttpStreamRef>(route: Ref, args: "skip" | HttpStreamArgsOf<Ref>, options?: UseHttpStreamOptions) => UseHttpStreamResult<HttpStreamChunkOf<Ref>>;
236
725
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
237
726
  type PaginatedArgs<F> = Omit<ArgsOf<F>, "paginationOpts">;
238
727
  /** The element type of the `page` array a paginated query returns. */
@@ -240,44 +729,44 @@ type PageItemOf<F> = ReturnOf<F> extends {
240
729
  page: (infer T)[];
241
730
  } ? T : unknown;
242
731
  /**
243
- * Subscribe to a reactively-paginated query and grow the feed page by page.
244
- *
245
- * The query function must accept a `paginationOpts: { numItems, cursor,
246
- * endCursor }` arg and return a `PaginationResult` (the shape
247
- * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
248
- * stable boundary cursors: each loaded page is a live subscription over a
249
- * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
250
- * Because boundaries are shared stable cursors, inserting or deleting a row in
251
- * the middle of the list grows/shrinks the affected page in place without
252
- * duplicating or skipping rows across page boundaries — the bug the legacy
253
- * "first N after the previous page's last row" model suffered under live edits.
254
- *
255
- * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
256
- * it is a no-op unless `status === "CanLoadMore"`. Background split/join
257
- * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
258
- * `use-paginated-core.ts`).
259
- *
260
- * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
261
- * feed to its first page. The public return shape (`results` / `status` /
262
- * `loadMore`) is unchanged from the legacy keyset implementation.
263
- */
732
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
733
+ *
734
+ * The query function must accept a `paginationOpts: { numItems, cursor,
735
+ * endCursor }` arg and return a `PaginationResult` (the shape
736
+ * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
737
+ * stable boundary cursors: each loaded page is a live subscription over a
738
+ * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
739
+ * Because boundaries are shared stable cursors, inserting or deleting a row in
740
+ * the middle of the list grows/shrinks the affected page in place without
741
+ * duplicating or skipping rows across page boundaries — the bug the legacy
742
+ * "first N after the previous page's last row" model suffered under live edits.
743
+ *
744
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
745
+ * it is a no-op unless `status === "CanLoadMore"`. Background split/join
746
+ * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
747
+ * `use-paginated-core.ts`).
748
+ *
749
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
750
+ * feed to its first page. The public return shape (`results` / `status` /
751
+ * `loadMore`) is unchanged from the legacy keyset implementation.
752
+ */
264
753
  declare const usePaginatedQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UsePaginatedQueryOptions) => UsePaginatedQueryResult<PageItemOf<F>>;
265
754
  /**
266
- * Subscribe to a reactively-paginated query and expose its pages discretely.
267
- *
268
- * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
269
- * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
270
- * inserted or deleted mid-list grows/shrinks the affected page without
271
- * duplicating or skipping rows across boundaries — but keeps each page as its
272
- * own inner array rather than flattening them, and adds the
273
- * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
274
- * shape. `fetchNextPage` appends the next page off the open-ended tail's
275
- * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
276
- *
277
- * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
278
- * feed to its first page. The public return shape is unchanged from the legacy
279
- * keyset implementation.
280
- */
755
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
756
+ *
757
+ * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
758
+ * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
759
+ * inserted or deleted mid-list grows/shrinks the affected page without
760
+ * duplicating or skipping rows across boundaries — but keeps each page as its
761
+ * own inner array rather than flattening them, and adds the
762
+ * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
763
+ * shape. `fetchNextPage` appends the next page off the open-ended tail's
764
+ * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
765
+ *
766
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
767
+ * feed to its first page. The public return shape is unchanged from the legacy
768
+ * keyset implementation.
769
+ */
281
770
  declare const useInfiniteQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UseInfiniteQueryOptions) => UseInfiniteQueryResult<PageItemOf<F>>;
282
771
  type CallOptions<F extends FunctionReference> = UseMutationCallOptions<unknown, unknown, ArgsOf<F>>;
283
772
  interface MutationHook<F extends FunctionReference> {
@@ -293,103 +782,128 @@ interface MutationHook<F extends FunctionReference> {
293
782
  /** Clear the latest `data`/`error` back to idle. */
294
783
  reset: () => void;
295
784
  /**
296
- * Bind a Convex-parity multi-query optimistic update to this mutation.
297
- * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
298
- * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
299
- * is supplied in the call options, which overrides the bound one.
300
- */
785
+ * Bind a Convex-parity multi-query optimistic update to this mutation.
786
+ * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
787
+ * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
788
+ * is supplied in the call options, which overrides the bound one.
789
+ */
301
790
  withOptimisticUpdate: (update: OptimisticUpdate<ArgsOf<F>>) => MutationHook<F>;
302
791
  }
303
792
  /**
304
- * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
305
- * given mutation reference. Prefer destructuring at the call site so the React
306
- * linter can track dependencies on each field independently.
307
- *
308
- * Built on TanStack Query's mutation cache (the same cache the query hooks use),
309
- * so it composes with Query Devtools and exposes the latest call's `data`/`error`
310
- * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
311
- * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
312
- *
313
- * `pending` is ref-counted across overlapping invocations of THIS hook instance
314
- * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
315
- * `false` only once every concurrent call has settled — and a sibling component
316
- * mutating the same function never affects it (TanStack's own `isPending` tracks
317
- * just the latest invocation).
318
- *
319
- * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
320
- * call options pass straight through to `client.mutation`, which applies and
321
- * rolls them back against the Lunora subscription cache (Convex parity) — not
322
- * through TanStack's `onMutate`.
323
- */
793
+ * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
794
+ * given mutation reference. Prefer destructuring at the call site so the React
795
+ * linter can track dependencies on each field independently.
796
+ *
797
+ * Built on TanStack Query's mutation cache (the same cache the query hooks use),
798
+ * so it composes with Query Devtools and exposes the latest call's `data`/`error`
799
+ * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
800
+ * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
801
+ *
802
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance
803
+ * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
804
+ * `false` only once every concurrent call has settled — and a sibling component
805
+ * mutating the same function never affects it (TanStack's own `isPending` tracks
806
+ * just the latest invocation).
807
+ *
808
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
809
+ * call options pass straight through to `client.mutation`, which applies and
810
+ * rolls them back against the Lunora subscription cache (Convex parity) — not
811
+ * through TanStack's `onMutate`.
812
+ */
324
813
  declare const useMutation: <F extends FunctionReference>(function_: F) => MutationHook<F>;
814
+ interface MutatorHook<TArgs> {
815
+ /** The latest invocation's error, or `undefined`. */
816
+ error: Error | undefined;
817
+ /** `true` when the latest invocation rejected. */
818
+ isError: boolean;
819
+ /** Run the mutator; resolves once the write is persisted, rejects on failure. */
820
+ mutate: (args: TArgs) => Promise<void>;
821
+ /** `true` while ANY invocation from this hook is in flight (ref-counted, so overlapping calls compose). */
822
+ pending: boolean;
823
+ /** Clear the latest `error` back to idle. */
824
+ reset: () => void;
825
+ }
826
+ /**
827
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
828
+ * custom-mutator handle from `@lunora/db`'s `bindMutators`. The optimistic
829
+ * overlay and server-authoritative push are owned by the bound handle (and
830
+ * TanStack DB's optimistic-transaction layer rebases pending overlays on every
831
+ * sync tick) — this hook only surfaces React state for the in-flight/error
832
+ * lifecycle. Reads stay on the existing `useLiveQuery`; no new query hook is
833
+ * needed.
834
+ *
835
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance,
836
+ * so it clears only once every concurrent call has settled.
837
+ */
838
+ declare const useMutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHook<TArgs>;
325
839
  /**
326
- * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
327
- * during SSR, then keep it live.
328
- *
329
- * The first render returns the preloaded value (TanStack's `initialData`),
330
- * so the server markup and the initial client markup match — no hydration
331
- * mismatch, no loading flash. After mount, a WS subscription attaches so
332
- * later server pushes update the value just like `useQuery`.
333
- *
334
- * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
335
- * full dehydrate/hydrate dance because the consumer hands us the resolved
336
- * value directly. Apps that want to share a pre-populated QueryClient across
337
- * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
338
- * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
339
- */
840
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
841
+ * during SSR, then keep it live.
842
+ *
843
+ * The first render returns the preloaded value (TanStack's `initialData`),
844
+ * so the server markup and the initial client markup match — no hydration
845
+ * mismatch, no loading flash. After mount, a WS subscription attaches so
846
+ * later server pushes update the value just like `useQuery`.
847
+ *
848
+ * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
849
+ * full dehydrate/hydrate dance because the consumer hands us the resolved
850
+ * value directly. Apps that want to share a pre-populated QueryClient across
851
+ * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
852
+ * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
853
+ */
340
854
  declare const usePreloadedQuery: <T>(preloaded: Preloaded<T>) => T;
341
855
  /**
342
- * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
343
- * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
344
- * attaches a live WS subscription on mount. It is a thin alias of
345
- * {@link usePreloadedQuery} so the React adapter exposes the same
346
- * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
347
- * while existing callers of `usePreloadedQuery` keep working unchanged.
348
- *
349
- * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
350
- * call it like a hook — at the top level of a component, unconditionally.
351
- */
856
+ * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
857
+ * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
858
+ * attaches a live WS subscription on mount. It is a thin alias of
859
+ * {@link usePreloadedQuery} so the React adapter exposes the same
860
+ * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
861
+ * while existing callers of `usePreloadedQuery` keep working unchanged.
862
+ *
863
+ * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
864
+ * call it like a hook — at the top level of a component, unconditionally.
865
+ */
352
866
  declare const hydratePreloaded: <T>(preloaded: Preloaded<T>) => T;
353
867
  /**
354
- * `usePresence` — collaborative-awareness hook, the client half of the
355
- * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
356
- * parity).
357
- *
358
- * It drives the two presence functions the server component ships:
359
- *
360
- * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
361
- * whenever the tab becomes visible, to upsert the caller's presence row and
362
- * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
363
- * carries the latest `data` from a ref, so `setData` takes effect on the next
364
- * tick without re-subscribing or resetting the timer.
365
- * - **listPresent** (a query): subscribed to over the live-query WS, so the
366
- * present-list updates reactively. Because the server patches a single row per
367
- * heartbeat, the client's **per-row subscription delta merge** applies just that
368
- * row to the cached list instead of re-sending every member — the list stays
369
- * cheap even with many participants heart-beating.
370
- *
371
- * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
372
- * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
373
- * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
374
- * the hook needs no client-side reaping.
375
- *
376
- * The two `FunctionReference`s come from your generated `api` (e.g.
377
- * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
378
- * stays decoupled from any specific app schema.
379
- */
380
- /**
381
- * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
382
- * `definePresence().functions.heartbeat` registers).
383
- */
868
+ * `usePresence` — collaborative-awareness hook, the client half of the
869
+ * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
870
+ * parity).
871
+ *
872
+ * It drives the two presence functions the server component ships:
873
+ *
874
+ * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
875
+ * whenever the tab becomes visible, to upsert the caller's presence row and
876
+ * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
877
+ * carries the latest `data` from a ref, so `setData` takes effect on the next
878
+ * tick without re-subscribing or resetting the timer.
879
+ * - **listPresent** (a query): subscribed to over the live-query WS, so the
880
+ * present-list updates reactively. Because the server patches a single row per
881
+ * heartbeat, the client's **per-row subscription delta merge** applies just that
882
+ * row to the cached list instead of re-sending every member — the list stays
883
+ * cheap even with many participants heart-beating.
884
+ *
885
+ * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
886
+ * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
887
+ * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
888
+ * the hook needs no client-side reaping.
889
+ *
890
+ * The two `FunctionReference`s come from your generated `api` (e.g.
891
+ * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
892
+ * stays decoupled from any specific app schema.
893
+ */
894
+ /**
895
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
896
+ * `definePresence().functions.heartbeat` registers).
897
+ */
384
898
  type HeartbeatReference = FunctionReference<"mutation", {
385
899
  data?: Record<string, unknown>;
386
900
  roomId: string;
387
901
  sessionId: string;
388
902
  }>;
389
903
  /**
390
- * A listPresent query reference: takes `{ roomId }` and returns the array of
391
- * present members.
392
- */
904
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
905
+ * present members.
906
+ */
393
907
  type ListPresentReference = FunctionReference<"query", {
394
908
  roomId: string;
395
909
  }>;
@@ -403,9 +917,9 @@ interface UsePresenceOptions<H extends HeartbeatReference, L extends ListPresent
403
917
  /** The `api.*` reference for the presence listPresent query. */
404
918
  listPresent: L;
405
919
  /**
406
- * Stable id for this presence row. Defaults to a fresh per-mount id (one row
407
- * per tab). Pass a user/connection id to control deduping.
408
- */
920
+ * Stable id for this presence row. Defaults to a fresh per-mount id (one row
921
+ * per tab). Pass a user/connection id to control deduping.
922
+ */
409
923
  sessionId?: string;
410
924
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
411
925
  shardKey?: string;
@@ -420,25 +934,31 @@ interface UsePresenceResult<L extends ListPresentReference> {
420
934
  }
421
935
  declare const usePresence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: UsePresenceOptions<H, L>) => UsePresenceResult<L>;
422
936
  /**
423
- * Subscribe to a server query.
424
- *
425
- * Returns `undefined` until the first response lands. Pass `"skip"` for
426
- * `args` to short-circuit the query (no network call, no subscription).
427
- *
428
- * Internally this routes through TanStack Query: the queryKey is
429
- * `["lunora", fn.__lunoraRef, args, shardKey]` (TanStack hashes structurally
430
- * so an args object built in a different key order still dedupes). The
431
- * subscription registry shares a single WS subscription across every consumer
432
- * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
433
- */
937
+ * Subscribe to a server query.
938
+ *
939
+ * Returns `undefined` until the first response lands. Pass `"skip"` for
940
+ * `args` to short-circuit the query (no network call, no subscription).
941
+ *
942
+ * When the `LunoraClient` was created with `hydrateOnStart: true` and a
943
+ * `queryCache` adapter, the first **enabled** render waits for the durable
944
+ * read cache to finish loading. If a cached value exists for this query it
945
+ * is fed as `initialData` so the user sees it immediately — no undefined
946
+ * flash before the socket round-trip.
947
+ *
948
+ * Internally this routes through TanStack Query: the queryKey is
949
+ * `["lunora", fn.__lunoraRef, args, shardKey]` (TanStack hashes structurally
950
+ * so an args object built in a different key order still dedupes). The
951
+ * subscription registry shares a single WS subscription across every consumer
952
+ * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
953
+ */
434
954
  declare const useQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => ReturnOf<F> | undefined;
435
955
  interface UseRateLimitOptions {
436
956
  /** Clock injection for tests. Defaults to `Date.now`. */
437
957
  now?: () => number;
438
958
  /**
439
- * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
440
- * down and `disabled` flips back automatically. Defaults to `1000`.
441
- */
959
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
960
+ * down and `disabled` flips back automatically. Defaults to `1000`.
961
+ */
442
962
  tickMs?: number;
443
963
  }
444
964
  interface UseRateLimitResult {
@@ -456,44 +976,161 @@ interface UseRateLimitResult {
456
976
  retryAfter: number;
457
977
  }
458
978
  /**
459
- * Client-side mirror of a rate limit for instant UX — disable a button or show
460
- * a countdown without a round-trip. It runs the same token-bucket / fixed-window
461
- * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
462
- * authoritative check; the server remains the source of truth.
463
- *
464
- * `config` is read on every render; pass a stable reference (module constant or
465
- * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
466
- */
979
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
980
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
981
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
982
+ * authoritative check; the server remains the source of truth.
983
+ *
984
+ * `config` is read on every render; pass a stable reference (module constant or
985
+ * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
986
+ */
467
987
  declare const useRateLimit: (config: RateLimitConfig, options?: UseRateLimitOptions) => UseRateLimitResult;
468
- /** The lifecycle of a stream the hook is observing. */
469
- type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
470
- interface UseStreamResult<T> {
471
- /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
472
- cancel: () => void;
473
- /** Chunks the server has pushed so far, in arrival order. */
474
- chunks: ReadonlyArray<T>;
475
- error: Error | undefined;
476
- status: UseStreamStatus;
988
+ /**
989
+ * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
990
+ * hook does not issue an initial HTTP fetch — it only delivers values that
991
+ * the server pushes over the WS.
992
+ */
993
+ declare const useSubscription: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => UseSubscriptionResult<ReturnOf<F>>;
994
+ /**
995
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
996
+ * capture and speaker playback implementations injected into the hook via its
997
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
998
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
999
+ * hook's transport + React-state logic and remains mockable in a non-browser
1000
+ * test env.
1001
+ */
1002
+ /**
1003
+ * The negotiated audio format the voice DO streams back. Mirrors
1004
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1005
+ * imported) so this React package never pulls in the server-only `@lunora/agent`
1006
+ * module graph.
1007
+ */
1008
+ type VoiceAudioFormat = "mp3" | "wav";
1009
+ /** Captures microphone audio and reports level / turn boundaries back to the hook. */
1010
+ interface VoiceMicrophone {
1011
+ /** Mute/unmute the mic without tearing down the capture graph. */
1012
+ setMuted: (muted: boolean) => void;
1013
+ /** Stop capture and release the media stream + audio graph. */
1014
+ stop: () => void;
477
1015
  }
478
- interface UseStreamOptions {
479
- /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
480
- maxBuffer?: number;
481
- shardKey?: string;
1016
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1017
+ interface VoiceSpeaker {
1018
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1019
+ enqueue: (audio: Uint8Array) => void;
1020
+ /** Drop everything queued and stop the current chunk (barge-in). */
1021
+ interrupt: () => void;
1022
+ /** Release the playback audio context. */
1023
+ stop: () => void;
1024
+ }
1025
+ /** Config passed to a {@link CreateMicrophone} factory. */
1026
+ interface MicrophoneConfig {
1027
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1028
+ interruptChunks: number;
1029
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1030
+ interruptThreshold: number;
1031
+ /** `true` while `status === "speaking"` — gates barge-in detection. */
1032
+ isSpeaking: () => boolean;
1033
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1034
+ onAudio: (pcm: Uint8Array) => void;
1035
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1036
+ onInterrupt: () => void;
1037
+ /** The current input RMS (0–1), for a level meter. */
1038
+ onLevel: (rms: number) => void;
1039
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1040
+ onSilence: () => void;
1041
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1042
+ silenceDurationMs: number;
1043
+ /** RMS below which audio counts as silence. */
1044
+ silenceThreshold: number;
482
1045
  }
1046
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1047
+ type CreateSpeaker = (config: {
1048
+ audioFormat: VoiceAudioFormat;
1049
+ }) => VoiceSpeaker;
483
1050
  /**
484
- * Subscribe to a streaming query. Returns the chunks pushed so far plus a
485
- * lifecycle status and a cancel function. Changing `fn` or the serialized
486
- * `args` resets the stream the previous iterator is cancelled and a fresh
487
- * one opens with empty `chunks`.
488
- *
489
- * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
490
- * (mirrors `useQuery` / `useSubscription`).
491
- */
492
- declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: "skip" | ArgsOf<F>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
1051
+ * The `agents.&lt;name>Voice` reference codegen emits for a voice-enabled agent a
1052
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1053
+ * generated member, so passing `api.agents.&lt;name>Voice` type-checks.
1054
+ */
1055
+ type VoiceReference = FunctionReference<"stream", {
1056
+ threadKey: string;
1057
+ }, Record<string, unknown>>;
1058
+ /** The lifecycle of a voice call, mirrored to the UI. */
1059
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1060
+ /** A minimal structural subset of the DOM `WebSocket` the hook drives. */
1061
+ interface VoiceSocket {
1062
+ binaryType: string;
1063
+ close: () => void;
1064
+ onclose: ((event: unknown) => void) | null;
1065
+ onerror: ((event: unknown) => void) | null;
1066
+ onmessage: ((event: {
1067
+ data: unknown;
1068
+ }) => void) | null;
1069
+ onopen: ((event: unknown) => void) | null;
1070
+ readonly readyState: number;
1071
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1072
+ }
1073
+ type CreateSocket = (url: string) => VoiceSocket;
1074
+ interface UseVoiceAgentOptions {
1075
+ /**
1076
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1077
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1078
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1079
+ */
1080
+ createMicrophone?: CreateMicrophone;
1081
+ /** Advanced/test seam: open the transport. Defaults to `new WebSocket(url)`. */
1082
+ createSocket?: CreateSocket;
1083
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1084
+ createSpeaker?: CreateSpeaker;
1085
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1086
+ interruptChunks?: number;
1087
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1088
+ interruptThreshold?: number;
1089
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1090
+ silenceDurationMs?: number;
1091
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1092
+ silenceThreshold?: number;
1093
+ /** The thread to converse on — shared with the agent's text turns. */
1094
+ threadKey: string;
1095
+ /** The generated `api.agents.&lt;name>Voice` reference — identifies the voice DO endpoint. */
1096
+ voice: VoiceReference;
1097
+ }
1098
+ interface UseVoiceAgentResult {
1099
+ /** The current input RMS (0–1) — drive a mic level meter. */
1100
+ audioLevel: number;
1101
+ /** `true` once the WS `ready` handshake completed. */
1102
+ connected: boolean;
1103
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1104
+ endCall: () => void;
1105
+ /** The last transport/pipeline error, or `undefined`. */
1106
+ error: Error | undefined;
1107
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1108
+ interimTranscript: string;
1109
+ /** `true` while the mic is muted. */
1110
+ isMuted: boolean;
1111
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1112
+ sendText: (text: string) => void;
1113
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1114
+ startCall: () => Promise<void>;
1115
+ /** The current call lifecycle. */
1116
+ status: VoiceStatus;
1117
+ /** Mute/unmute the microphone. Returns the new muted state. */
1118
+ toggleMute: () => boolean;
1119
+ /** The last finalized user utterance (STT result). */
1120
+ transcript: string;
1121
+ }
493
1122
  /**
494
- * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
495
- * hook does not issue an initial HTTP fetch it only delivers values that
496
- * the server pushes over the WS.
497
- */
498
- declare const useSubscription: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => UseSubscriptionResult<ReturnOf<F>>;
499
- export { AuthLoading, type AuthState, Authenticated, CheckoutButton, type CheckoutButtonProps, CustomerPortalButton, type CustomerPortalButtonProps, type HeartbeatReference, type ListPresentReference, LunoraProvider, type LunoraProviderProps, type MutationHook, 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, useInfiniteQuery, useLunora, useMutation, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription };
1123
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1124
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1125
+ * streams the agent's synthesized speech back through the browser's audio output,
1126
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1127
+ * `audioLevel`) to React state. Pass the generated `api.agents.&lt;name>Voice`
1128
+ * reference (never a string), matching `useAgentChat`'s reference-passing style.
1129
+ *
1130
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1131
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1132
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1133
+ * `createSocket`) so the hook is drivable outside a browser.
1134
+ */
1135
+ declare const useVoiceAgent: (options: UseVoiceAgentOptions) => UseVoiceAgentResult;
1136
+ 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 UseHttpStreamOptions, type UseHttpStreamResult, 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, useClientQuery, useConnectionStatus, useFlag, useFlags, useHttpStream, useInfiniteQuery, useLunora, useMutation, useMutator, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription, useVoiceAgent };