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

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