@lunora/react 1.0.0-alpha.4 → 1.0.0-alpha.40

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 (66) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/dist/index.d.mts +1045 -276
  4. package/dist/index.d.ts +1045 -276
  5. package/dist/index.mjs +1 -16
  6. package/dist/packem_shared/AuthLoading-eLWn4Z7G.mjs +2 -0
  7. package/dist/packem_shared/CheckoutButton-DS_DKgNf.mjs +2 -0
  8. package/dist/packem_shared/LunoraProvider-InsjxtOB.mjs +2 -0
  9. package/dist/packem_shared/cache-odCgnNLz.mjs +1 -0
  10. package/dist/packem_shared/hydratePreloaded-DltXxPnp.mjs +2 -0
  11. package/dist/packem_shared/lunoraQueryOptions-BhiUY9ZF.mjs +1 -0
  12. package/dist/packem_shared/query-key-Y92N0Dci.mjs +1 -0
  13. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.mts +38 -0
  14. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.ts +38 -0
  15. package/dist/packem_shared/stable-key-BSG0zK_E.mjs +1 -0
  16. package/dist/packem_shared/use-paginated-core-DYjRFno_.mjs +2 -0
  17. package/dist/packem_shared/useAgent-DNKxqQ9F.mjs +2 -0
  18. package/dist/packem_shared/useAgentChat-BdDuGIHz.mjs +2 -0
  19. package/dist/packem_shared/useAgentState-DO0yz6OU.mjs +2 -0
  20. package/dist/packem_shared/useAgentToolEvents-DTWZCIfd.mjs +2 -0
  21. package/dist/packem_shared/useAuth-CWkJn7i9.mjs +2 -0
  22. package/dist/packem_shared/useAuthSessions-Dw4Zhtxa.mjs +2 -0
  23. package/dist/packem_shared/useAuthState-jnCMkIwt.mjs +2 -0
  24. package/dist/packem_shared/useClientQuery-EPo__hzu.mjs +2 -0
  25. package/dist/packem_shared/useConnectionStatus-PL5D-S7t.mjs +2 -0
  26. package/dist/packem_shared/useFlag-Dh7bXXPx.mjs +2 -0
  27. package/dist/packem_shared/useHttpStream-DFswZrRk.mjs +2 -0
  28. package/dist/packem_shared/useInfiniteQuery-DyExohf2.mjs +2 -0
  29. package/dist/packem_shared/useMutation-B4uL3Rde.mjs +2 -0
  30. package/dist/packem_shared/useMutator-D3CGrk5-.mjs +2 -0
  31. package/dist/packem_shared/usePaginatedQuery-Roo_jyC9.mjs +2 -0
  32. package/dist/packem_shared/usePresence-xAbekAr_.mjs +2 -0
  33. package/dist/packem_shared/useQuery-m-trnMUV.mjs +2 -0
  34. package/dist/packem_shared/useRateLimit-DqikMrX9.mjs +2 -0
  35. package/dist/packem_shared/useStream-CGcSWvPI.mjs +2 -0
  36. package/dist/packem_shared/useSubscription-CiQk8tFR.mjs +2 -0
  37. package/dist/packem_shared/useVoiceAgent-4gj2W2jc.mjs +2 -0
  38. package/dist/packem_shared/wire-key-8Ju6XYoB.mjs +1 -0
  39. package/dist/server.d.mts +29 -29
  40. package/dist/server.d.ts +29 -29
  41. package/dist/server.mjs +1 -31
  42. package/dist/upload.d.mts +2 -0
  43. package/dist/upload.d.ts +2 -0
  44. package/dist/upload.mjs +2 -0
  45. package/package.json +10 -4
  46. package/dist/packem_shared/AuthLoading-DtKgZT2Z.mjs +0 -33
  47. package/dist/packem_shared/CheckoutButton-CVSry8U1.mjs +0 -185
  48. package/dist/packem_shared/LunoraProvider-D38Xp16l.mjs +0 -80
  49. package/dist/packem_shared/cache-CItk3fgN.mjs +0 -75
  50. package/dist/packem_shared/hydratePreloaded-BlFL9FGq.mjs +0 -46
  51. package/dist/packem_shared/lunoraQueryOptions-CsuWzjg1.mjs +0 -16
  52. package/dist/packem_shared/query-key-C5rufkEE.mjs +0 -21
  53. package/dist/packem_shared/query-options.d-D4okOpO8.d.mts +0 -38
  54. package/dist/packem_shared/query-options.d-D4okOpO8.d.ts +0 -38
  55. package/dist/packem_shared/use-paginated-core-CoOfcc-p.mjs +0 -161
  56. package/dist/packem_shared/useAuth-CNUKtOOp.mjs +0 -129
  57. package/dist/packem_shared/useAuthState-BiGhtSCs.mjs +0 -36
  58. package/dist/packem_shared/useConnectionStatus-DRSY9ldm.mjs +0 -30
  59. package/dist/packem_shared/useInfiniteQuery-MH0x4l8h.mjs +0 -97
  60. package/dist/packem_shared/useMutation-CrvMXRsk.mjs +0 -67
  61. package/dist/packem_shared/usePaginatedQuery-D3PTDRGS.mjs +0 -46
  62. package/dist/packem_shared/usePresence-D7jLuxj0.mjs +0 -108
  63. package/dist/packem_shared/useQuery-C5S0W-7K.mjs +0 -41
  64. package/dist/packem_shared/useRateLimit-DTEffQEi.mjs +0 -64
  65. package/dist/packem_shared/useStream-BRY9nemd.mjs +0 -125
  66. package/dist/packem_shared/useSubscription-CHMCjyQg.mjs +0 -139
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, AuthImpersonation, AuthSession, AuthUser, 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
  }
@@ -213,26 +199,661 @@ interface UseAuthResult {
213
199
  token: string | null;
214
200
  user: User | null;
215
201
  }
202
+ /** The shape every list hook in this file returns. */
203
+ interface AdminAuthListResult<T> {
204
+ /** Rows loaded so far (the full current window, not just the latest page). `undefined` before the first response. */
205
+ readonly data: ReadonlyArray<T> | undefined;
206
+ /** The read error, or `undefined`. */
207
+ readonly error: Error | undefined;
208
+ /**
209
+ * `true` when the server reports more rows exist beyond the current window
210
+ * (`total > data.length`). `false` before the first response resolves.
211
+ */
212
+ readonly hasMore: boolean;
213
+ /** `true` only before the first response has resolved (matches TanStack's `isLoading`, not `isFetching`). */
214
+ readonly loading: boolean;
215
+ /**
216
+ * Grow the requested window by one page and re-fetch. A no-op while
217
+ * `hasMore` is `false`. This is a growing-window re-fetch (re-request
218
+ * `{ limit }` from the top), not a page-accumulator — `AuthPage` is
219
+ * offset/limit-based, not cursor-based, and there is no live delta stream
220
+ * to keep page boundaries stable against (unlike
221
+ * `@lunora/react`'s `usePaginatedQuery`). See the design doc for the
222
+ * trade-off.
223
+ */
224
+ readonly loadMore: () => void;
225
+ /** Re-run the read — e.g. after a caller performs a mutation via a plain `client.*` call (mirrors Studio's `onDone={refetchOrgs}` pattern). */
226
+ readonly refetch: () => void;
227
+ /** `AuthPage.total` — the server-reported row count across the whole collection, not just the current window. `undefined` before the first response. */
228
+ readonly total: number | undefined;
229
+ }
230
+ /** Options shared by every `useAuthUsers`-style hook. */
231
+ interface AdminAuthQueryOptions {
232
+ /** Gate the read (rules-of-hooks safe). Defaults to `true`. */
233
+ enabled?: boolean;
234
+ /** Page size for the first read; `loadMore` grows the window by this amount. Defaults to 50. */
235
+ pageSize?: number;
236
+ }
237
+ /** Options for {@link useAuthUsers}. */
238
+ interface UseAuthUsersOptions extends AdminAuthQueryOptions {
239
+ filterField?: string;
240
+ filterValue?: string;
241
+ search?: string;
242
+ searchField?: string;
243
+ sortBy?: string;
244
+ sortDirection?: "asc" | "desc";
245
+ }
246
+ /**
247
+ * List authenticated users, paged and optionally searched/filtered/sorted.
248
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` HTTP endpoint via
249
+ * `client.listAuthUsers` (never the WS/live transport) — the worker must be
250
+ * built with an `authAdmin` and `adminToken`.
251
+ *
252
+ * Mirrors `packages/studio/src/features/auth/users-panel.tsx`'s
253
+ * `useClientQuery(["lunora-auth-users", …], () => client.listAuthUsers(…))`
254
+ * read, minus the studio-specific polling (`useAutoRefresh`) — an app using
255
+ * this hook decides its own refresh cadence by calling `refetch()`.
256
+ */
257
+ declare const useAuthUsers: (options?: UseAuthUsersOptions) => AdminAuthListResult<AuthUser>;
258
+ /** Options for {@link useOrganizations}. */
259
+ type UseOrganizationsOptions = AdminAuthQueryOptions;
260
+ /**
261
+ * List organizations (requires the better-auth `organization` plugin).
262
+ * Hits `client.listAuthOrganizations` — an HTTP-only admin-gated read, same
263
+ * transport note as {@link useAuthUsers}.
264
+ *
265
+ * Mirrors `organizations-panel.tsx`'s
266
+ * `useClientQuery(["lunora-auth-orgs"], () => client.listAuthOrganizations({ limit: 100 }))`.
267
+ * Mutations (`client.createAuthOrganization`, `client.deleteAuthOrganization`,
268
+ * …) stay plain `client.*` calls; call this hook's `refetch()` afterward —
269
+ * see the design doc's "mutation ergonomics" section for why no hidden
270
+ * invalidation-on-mutate is wired in.
271
+ */
272
+ declare const useOrganizations: (options?: UseOrganizationsOptions) => AdminAuthListResult<Record<string, unknown>>;
273
+ /** Options for {@link useAuthSessions}. */
274
+ interface UseAuthSessionsOptions extends AdminAuthQueryOptions {
275
+ /** Scope the list to one user's sessions; omit for the global cross-user browser. */
276
+ userId?: string;
277
+ }
278
+ /**
279
+ * List auth sessions, paged and optionally scoped to one user. Hits
280
+ * `client.listAuthSessions` — HTTP-only, same transport note as
281
+ * {@link useAuthUsers}.
282
+ *
283
+ * Mirrors `auth-sessions-panel.tsx`'s
284
+ * `useClientQuery(["lunora-auth-sessions", …], () => client.listAuthSessions({ limit }))`.
285
+ * Revoking a session (`client.revokeAuthSession`/`revokeAuthUserSessions`)
286
+ * stays a plain `client.*` call followed by this hook's `refetch()`.
287
+ */
288
+ declare const useAuthSessions: (options?: UseAuthSessionsOptions) => AdminAuthListResult<AuthSession>;
289
+ /** Everything {@link useImpersonate} returns. */
290
+ interface UseImpersonateResult {
291
+ /** The latest successful impersonation's token + user + expiry, or `undefined`. */
292
+ readonly data: AuthImpersonation | undefined;
293
+ /** The latest attempt's error, or `undefined`. */
294
+ readonly error: Error | undefined;
295
+ /**
296
+ * Mint an impersonation session for `userId`, resolving its bearer
297
+ * `AuthImpersonation`. Deliberately does **not** call
298
+ * `client.setAuthToken(...)` on the current client — see the security
299
+ * note below.
300
+ */
301
+ readonly impersonate: (userId: string) => Promise<AuthImpersonation>;
302
+ /** `true` while an impersonation request is in flight. */
303
+ readonly pending: boolean;
304
+ /** Clear `data`/`error` back to idle. */
305
+ readonly reset: () => void;
306
+ }
307
+ /**
308
+ * Mint an impersonation session via `client.impersonateAuthUser` — the one
309
+ * genuinely mutation-shaped hook of the four prototyped here (TanStack
310
+ * `useMutation` underneath, matching `@lunora/react`'s own `useMutation`
311
+ * ergonomics: `data`/`error`/`pending`/`reset`).
312
+ *
313
+ * **Security note (open question — see the design doc):** Studio's
314
+ * `user-detail-drawer.tsx` (`onImpersonate`) mints the token and displays it
315
+ * in a read-only text field; it never calls `client.setAuthToken(token)` on
316
+ * the admin's own client instance. This hook preserves that discipline
317
+ * deliberately — silently swapping the *current* session would sign the
318
+ * admin out of their own admin session with no visible transition and no
319
+ * "return to admin" path. The caller decides what to do with the resolved
320
+ * `AuthImpersonation` (open a second tab/incognito window authenticated as
321
+ * the target user, surface it for manual copy, etc.). What the ideal UX is
322
+ * (a dedicated "Acting as X — Return to admin" banner + explicit swap-back)
323
+ * is an open product question this spike does not resolve.
324
+ *
325
+ * Unlike the three list hooks, impersonating a user has no single paired
326
+ * list to invalidate (it may affect a sessions list, but not the user/org
327
+ * list currently being viewed) — mirroring Studio's own `refresh: false` on
328
+ * this action, this hook does not auto-invalidate anything. A caller that
329
+ * also renders `useAuthSessions` can call its `refetch()` explicitly.
330
+ */
331
+ declare const useImpersonate: () => UseImpersonateResult;
332
+ /**
333
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
334
+ * `@lunora/agent`'s `AgentThreadStatus` — re-declared here (rather than imported)
335
+ * so this React entry never pulls in the server-only `@lunora/agent` module
336
+ * graph (the kit stays React + DOM only). Keep in sync with
337
+ * `packages/agent/src/types.ts`.
338
+ */
339
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
340
+ /**
341
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
342
+ * subset of the persisted thread row — every field beyond `status` is optional so
343
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
344
+ * `agent_threads` table in `packages/agent/src/component.ts`.
345
+ */
346
+ interface AgentThreadRecord {
347
+ createdAt?: number;
348
+ /** The failure message when `status === "error"`. */
349
+ error?: string;
350
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
351
+ instanceId?: string;
352
+ messageCount?: number;
353
+ /** The verified thread owner, when the run was started with one. */
354
+ owner?: string;
355
+ status: AgentThreadStatus;
356
+ title?: string;
357
+ updatedAt?: number;
358
+ }
359
+ /**
360
+ * The `agents.agentThread` reference the hook subscribes to for live thread state
361
+ * (status + the in-flight `instanceId`). A structural subset of the generated
362
+ * `api.agents` surface, so the whole generated `api` object is assignable.
363
+ */
364
+ interface UseAgentApi {
365
+ agents: {
366
+ agentThread: FunctionReference<"query", {
367
+ key: string;
368
+ }, Record<string, unknown> | undefined>;
369
+ };
370
+ }
371
+ interface UseAgentOptions {
372
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
373
+ api: UseAgentApi;
374
+ /**
375
+ * Optional app mutation over the agent's cancel path
376
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
377
+ * When omitted (or no run is in flight) {@link UseAgentResult.cancel} is a
378
+ * no-op.
379
+ */
380
+ cancel?: FunctionReference<"mutation">;
381
+ /**
382
+ * The app mutation that starts (or continues) a run — a thin wrapper over
383
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
384
+ * {@link UseAgentOptions.runArgs} and the per-call args.
385
+ */
386
+ run: FunctionReference<"mutation">;
387
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
388
+ runArgs?: Record<string, unknown>;
389
+ /** The thread to observe and drive. */
390
+ threadKey: string;
391
+ }
392
+ interface UseAgentResult {
393
+ /**
394
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
395
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
396
+ */
397
+ cancel: () => Promise<void>;
398
+ /** `true` while a `run` invocation is in flight. */
399
+ pending: boolean;
400
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
401
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
402
+ /** The live thread status, or `undefined` before the thread exists. */
403
+ status: AgentThreadStatus | undefined;
404
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
405
+ thread: AgentThreadRecord | undefined;
406
+ }
407
+ /**
408
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
409
+ * chat message surface. Composes `useSubscription(api.agents.agentThread)` for
410
+ * live state and `useMutation` for the run/cancel writes. For the full
411
+ * conversation surface (durable history + streaming + approvals) use
412
+ * `useAgentChat`.
413
+ *
414
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
415
+ * `ctx.agents.&lt;name>.run` / `.cancel`, so the hook hard-codes no function names
416
+ * beyond the `agents:*` surface.
417
+ */
418
+ declare const useAgent: (options: UseAgentOptions) => UseAgentResult;
419
+ /**
420
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
421
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
422
+ * re-declared here (rather than imported) so this React entry never pulls in the
423
+ * server-only `@lunora/agent` module graph. Keep in sync with the `agent_messages`
424
+ * table in `packages/agent/src/component.ts`.
425
+ */
426
+ interface AgentChatMessage {
427
+ content: string;
428
+ createdAt?: number;
429
+ /**
430
+ * `true` for a client-side optimistic user message not yet acknowledged by
431
+ * the server. Cleared once the durable history carries the matching user turn.
432
+ */
433
+ optimistic?: boolean;
434
+ role: "assistant" | "system" | "tool" | "user";
435
+ seq: number;
436
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
437
+ status?: "approved" | "awaiting_approval" | "rejected";
438
+ toolCallId?: string;
439
+ toolCalls?: ReadonlyArray<{
440
+ id: string;
441
+ input: unknown;
442
+ name: string;
443
+ }>;
444
+ toolName?: string;
445
+ }
446
+ /**
447
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
448
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
449
+ * {@link UseAgentChatResult.streamingText} live and are never replayed; the
450
+ * persisted assistant message stays the single source of truth.
451
+ */
452
+ interface AgentTokenDelta {
453
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
454
+ kind?: "token";
455
+ /** The incremental text chunk the model just produced. */
456
+ text: string;
457
+ /** The thread this delta belongs to. */
458
+ threadKey: string;
459
+ /** The zero-based index of the turn producing the delta. */
460
+ turn: number;
461
+ }
216
462
  /**
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
- */
463
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
464
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
465
+ * surfaced by `useAgentToolEvents`, ignored by {@link UseAgentChatResult.streamingText}.
466
+ */
467
+ interface AgentProgressEvent {
468
+ /** The arbitrary, JSON-serializable payload the tool reported. */
469
+ data: unknown;
470
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
471
+ kind: "progress";
472
+ /** The thread this event belongs to. */
473
+ threadKey: string;
474
+ /** The tool call this progress belongs to. */
475
+ toolCallId: string;
476
+ }
477
+ /**
478
+ * A single event on the agent's live-only channel — a streamed token delta or a
479
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
480
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
481
+ * it unset).
482
+ */
483
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
484
+ /** The `agents:agentMessages` reference — live durable thread history. */
485
+ type AgentMessagesReference$1 = FunctionReference<"query", {
486
+ key: string;
487
+ limit?: number;
488
+ }, ReadonlyArray<Record<string, unknown>>>;
489
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
490
+ type AgentApprovalReference = FunctionReference<"mutation", {
491
+ decision: "approve" | "reject";
492
+ instanceId: string;
493
+ note?: string;
494
+ threadKey: string;
495
+ toolCallId: string;
496
+ }, {
497
+ resolved: boolean;
498
+ }>;
499
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
500
+ type AgentThreadReference = FunctionReference<"query", {
501
+ key: string;
502
+ }, Record<string, unknown> | undefined>;
503
+ /**
504
+ * An app stream reference that tees the agent's in-flight live events, keyed by
505
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
506
+ * sink — tool progress events; this hook consumes only the token arm.
507
+ */
508
+ type AgentTokenStreamReference = FunctionReference<"stream", {
509
+ key: string;
510
+ }, AgentLiveEvent>;
511
+ /**
512
+ * The `agents.*` reference surface the chat hook reads. A structural subset of
513
+ * the generated `api.agents`, so the whole generated `api` object is assignable.
514
+ */
515
+ interface UseAgentChatApi {
516
+ agents: {
517
+ agentMessages: AgentMessagesReference$1;
518
+ agentResolveApproval: AgentApprovalReference;
519
+ agentThread: AgentThreadReference;
520
+ };
521
+ }
522
+ interface UseAgentChatOptions {
523
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
524
+ api: UseAgentChatApi;
525
+ /**
526
+ * Optional app mutation over the agent's cancel path
527
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
528
+ * When omitted (or no run is in flight) {@link UseAgentChatResult.cancel} is a
529
+ * no-op.
530
+ */
531
+ cancel?: FunctionReference<"mutation">;
532
+ /** History depth forwarded to `agents:agentMessages`. */
533
+ limit?: number;
534
+ /**
535
+ * The app mutation that starts (or continues) a run — a thin wrapper over
536
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
537
+ * {@link UseAgentChatOptions.sendArgs} and the per-call args.
538
+ */
539
+ send: FunctionReference<"mutation">;
540
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
541
+ sendArgs?: Record<string, unknown>;
542
+ /**
543
+ * Optional live token-delta stream — an app stream function that tees the
544
+ * agent's in-flight deltas. When omitted {@link UseAgentChatResult.streamingText}
545
+ * stays empty and the UI updates message-by-message from durable history.
546
+ */
547
+ stream?: AgentTokenStreamReference;
548
+ /** The thread to observe and continue. */
549
+ threadKey: string;
550
+ }
551
+ interface UseAgentChatResult {
552
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
553
+ approve: (toolCallId: string, note?: string) => Promise<void>;
554
+ /**
555
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
556
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
557
+ */
558
+ cancel: () => Promise<void>;
559
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
560
+ messages: ReadonlyArray<AgentChatMessage>;
561
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
562
+ reject: (toolCallId: string, note?: string) => Promise<void>;
563
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
564
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
565
+ /** The live thread status, or `undefined` before the thread exists. */
566
+ status: AgentThreadStatus | undefined;
567
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
568
+ streamingText: string;
569
+ }
570
+ /**
571
+ * A first-class agent chat surface: live durable history + in-flight token
572
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey`.
573
+ *
574
+ * It composes the existing primitives rather than adding transport:
575
+ * `useSubscription(api.agents.agentMessages)` for durable history,
576
+ * `useSubscription(api.agents.agentThread)` for live status + the in-flight
577
+ * `instanceId`, {@link useStream} over an app token stream for in-flight deltas,
578
+ * and `useMutation` for the writes (`api.agents.agentResolveApproval` for
579
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*`
580
+ * surface is hard-coded — `send`/`cancel`/`stream` stay generic references.
581
+ *
582
+ * A `send` optimistically appends the user turn so it renders immediately; the
583
+ * optimistic row clears once the durable history carries the acknowledged turn.
584
+ * `streamingText` is live-only: it holds the current turn's streamed text and
585
+ * empties as soon as that turn's assistant message lands in `messages` (the
586
+ * persisted message is the source of truth), consistent with the loop's
587
+ * replay-safe, live-only delta design.
588
+ */
589
+ declare const useAgentChat: (options: UseAgentChatOptions) => UseAgentChatResult;
590
+ /**
591
+ * The `agents.agentState` reference the hook subscribes to for the thread's live
592
+ * synced state. A structural subset of the generated `api.agents` surface (like
593
+ * `UseAgentApi` for `agentThread`), so the whole generated `api` object is
594
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type
595
+ * is mirrored by the hook's generic `T`, since codegen pins the reference return
596
+ * as an optional record (it never evaluates agent config).
597
+ */
598
+ interface UseAgentStateApi {
599
+ agents: {
600
+ agentState: FunctionReference<"query", {
601
+ key: string;
602
+ }, Record<string, unknown> | undefined>;
603
+ };
604
+ }
605
+ interface UseAgentStateOptions {
606
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
607
+ api: UseAgentStateApi;
608
+ /** The thread whose synced state to observe. */
609
+ threadKey: string;
610
+ }
611
+ interface UseAgentStateResult<T> {
612
+ /** The subscription error, if the live channel reported one. */
613
+ error: Error | undefined;
614
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
615
+ state: T | undefined;
616
+ }
617
+ /**
618
+ * Subscribe to an agent thread's synced state — the `setState`-style value a
619
+ * tool writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`.
620
+ * A thin wrapper over `useSubscription(api.agents.agentState, { key })`: the
621
+ * server pushes a fresh frame whenever the state changes (the dedicated query's
622
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
623
+ * `state` updates only on a real `setState`.
624
+ *
625
+ * Generic over the app's state shape (`useAgentState` with a `SupportState` type
626
+ * argument, itself a record) — the reference is typed as an optional record
627
+ * because codegen cannot see the per-agent state type; the generic casts to `T`.
628
+ * The `extends` bound (not a bare unbounded type parameter) is required: this
629
+ * `.ts` file is parsed JSX-aware by the bundler, where an unbounded type-param
630
+ * arrow is ambiguous with a JSX element.
631
+ */
632
+ declare const useAgentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: UseAgentStateOptions) => UseAgentStateResult<T>;
633
+ /** The `agents:agentMessages` reference — live durable thread history. */
634
+ type AgentMessagesReference = FunctionReference<"query", {
635
+ key: string;
636
+ limit?: number;
637
+ }, ReadonlyArray<Record<string, unknown>>>;
638
+ /**
639
+ * An app stream reference that tees the agent's in-flight live events, keyed by
640
+ * thread. Carries token deltas and tool progress events; this hook consumes only
641
+ * the progress arm (`kind === "progress"`).
642
+ */
643
+ type AgentLiveStreamReference = FunctionReference<"stream", {
644
+ key: string;
645
+ }, AgentLiveEvent>;
646
+ /**
647
+ * The `agents.*` reference surface the tool-events hook reads. A structural
648
+ * subset of the generated `api.agents`, so the whole generated `api` object is
649
+ * assignable.
650
+ */
651
+ interface UseAgentToolEventsApi {
652
+ agents: {
653
+ agentMessages: AgentMessagesReference;
654
+ };
655
+ }
656
+ interface UseAgentToolEventsOptions {
657
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
658
+ api: UseAgentToolEventsApi;
659
+ /** History depth forwarded to `agents:agentMessages`. */
660
+ limit?: number;
661
+ /**
662
+ * Optional live event stream — the same app stream function `useAgentChat`
663
+ * uses. When supplied, ephemeral `ctx.reportProgress(...)` events for the
664
+ * thread are surfaced as `{ type: "progress" }` entries; when omitted only the
665
+ * durable lifecycle (call / result / awaiting-approval) is returned.
666
+ */
667
+ stream?: AgentLiveStreamReference;
668
+ /** The thread whose tool activity to observe. */
669
+ threadKey: string;
670
+ }
671
+ /**
672
+ * A single tool-lifecycle event for a thread. The durable arms
673
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
674
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
675
+ * stream and has no `seq`. Discriminate on `type`.
676
+ */
677
+ type AgentToolEvent = {
678
+ data: unknown;
679
+ toolCallId: string;
680
+ type: "progress";
681
+ } | {
682
+ input: unknown;
683
+ seq: number;
684
+ toolCallId: string;
685
+ toolName: string;
686
+ type: "call";
687
+ } | {
688
+ output: string;
689
+ seq: number;
690
+ status?: "approved" | "rejected";
691
+ toolCallId?: string;
692
+ toolName?: string;
693
+ type: "result";
694
+ } | {
695
+ seq: number;
696
+ toolCallId?: string;
697
+ toolName?: string;
698
+ type: "awaiting-approval";
699
+ };
700
+ interface UseAgentToolEventsResult {
701
+ /**
702
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
703
+ * followed by any in-flight ephemeral progress events. Rebuilt each render
704
+ * from the live subscription + stream — treat as derived, not identity-stable.
705
+ */
706
+ events: ReadonlyArray<AgentToolEvent>;
707
+ }
708
+ /**
709
+ * A focused view of a thread's tool activity: tool calls, their results,
710
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
711
+ * without the full chat message surface. Composes the existing primitives:
712
+ * `useSubscription(api.agents.agentMessages)` for the durable lifecycle and
713
+ * {@link useStream} over the optional app event stream for ephemeral progress.
714
+ *
715
+ * Progress events are live-only (the durable path never emits them): they ride
716
+ * the same sink as token deltas and are surfaced here, correlated to their tool
717
+ * call by `toolCallId`. For the conversational surface (messages + streaming
718
+ * text + approvals) use `useAgentChat`; this hook is the tool-observability slice.
719
+ */
720
+ declare const useAgentToolEvents: (options: UseAgentToolEventsOptions) => UseAgentToolEventsResult;
721
+ /**
722
+ * Token + identity plumbing. The token lives on the shared `LunoraClient`;
723
+ * `setToken(jwt)` after a sign-in makes subsequent RPC calls carry the
724
+ * `Authorization` header. `user` is resolved from better-auth's `get-session`
725
+ * endpoint via `client.getCurrentUser()` — fetched on mount and refetched
726
+ * whenever the token changes (`onAuthTokenChange`), and `null` when signed out.
727
+ *
728
+ * Multiple `useAuth` instances stay in sync: both `token` and `user` are read
729
+ * through `useSyncExternalStore` over the shared client (and a per-client
730
+ * identity store), so a `setToken` from one component re-renders every mounted
731
+ * hook with the freshly-resolved user.
732
+ */
228
733
  declare const useAuth: () => UseAuthResult;
734
+ type Setter<T> = (value: T) => void;
735
+ /**
736
+ * Subscribe to a local-only {@link ClientQueryRef} and re-render when its
737
+ * value changes. Unlike `useQuery`, this never touches the network — the
738
+ * value lives in a reactive store on the `LunoraClient` instance and is shared
739
+ * across every consumer of the same ref.
740
+ *
741
+ * The initial render reads the store synchronously (via
742
+ * `useSyncExternalStore`), so there is never an "undefined flash" — the value
743
+ * is either the one most recently set or `ref.defaultValue`.
744
+ *
745
+ * Returns a `[value, setter]` tuple, matching the `useState` convention.
746
+ * @example
747
+ * ```tsx
748
+ * import { useClientQuery, createClientQuery } from "@lunora/react";
749
+ *
750
+ * const sidebarOpen = createClientQuery("sidebarOpen", true);
751
+ *
752
+ * function Sidebar() {
753
+ * const [open, setOpen] = useClientQuery(sidebarOpen);
754
+ * return <aside data-open={open}>…</aside>;
755
+ * }
756
+ * ```
757
+ */
758
+ declare const useClientQuery: <T extends unknown>(ref: ClientQueryRef<T>) => [T, Setter<T>];
229
759
  /**
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
- */
760
+ * Reactive view of the client's aggregate live-socket status across all shard
761
+ * connections. Re-renders on every transition (`idle` → `connecting` →
762
+ * `connected` → `offline`). Use it to drive a connection indicator so an
763
+ * operator can tell a healthy live channel from a silently-dropped socket.
764
+ */
235
765
  declare const useConnectionStatus: () => ConnectionStatus;
766
+ /** A targeting context merged on top of the app's default (`defineFlags({ identify })`). */
767
+ type FlagContext = Record<string, unknown>;
768
+ /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
769
+ type FlagValue = boolean | number | string | {
770
+ [key: string]: unknown;
771
+ } | unknown[] | null;
772
+ /**
773
+ * Subscribe to a single feature flag, live over Lunora's WebSocket.
774
+ *
775
+ * Returns `defaultValue` until the first evaluation lands, then the server's
776
+ * resolved value — re-pushed whenever the provider re-evaluates (e.g. a flag is
777
+ * toggled in Cloudflare Flagship). The flag's kind is inferred from
778
+ * `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean and
779
+ * `useFlag("hero", "control")` a string. `context` supplies a per-call targeting
780
+ * context merged on top of the app's default `identify` targeting key.
781
+ *
782
+ * Evaluation runs through whatever OpenFeature provider the app wired in
783
+ * `lunora/flags.ts`; the read never throws — a provider error resolves the
784
+ * default (the same fail-open contract as server-side `ctx.flags`).
785
+ */
786
+ declare const useFlag: <T extends FlagValue>(key: string, defaultValue: T, context?: FlagContext) => T;
787
+ /**
788
+ * Subscribe to several feature flags at once, live over Lunora's WebSocket.
789
+ *
790
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
791
+ * default, and the result is the same-shaped record with resolved values (the
792
+ * defaults until each evaluation lands). A single `context` applies to every
793
+ * flag. This is the batched form of {@link useFlag} — one effect manages one
794
+ * subscription per key, so it stays rules-of-hooks-safe even as the flag set
795
+ * changes between renders.
796
+ */
797
+ declare const useFlags: <T extends Record<string, FlagValue>>(flags: T, context?: FlagContext) => T;
798
+ /** The lifecycle of a stream the hook is observing. */
799
+ type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
800
+ interface UseStreamResult<T> {
801
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
802
+ cancel: () => void;
803
+ /** Chunks the server has pushed so far, in arrival order. */
804
+ chunks: ReadonlyArray<T>;
805
+ error: Error | undefined;
806
+ status: UseStreamStatus;
807
+ }
808
+ interface UseStreamOptions {
809
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
810
+ maxBuffer?: number;
811
+ shardKey?: string;
812
+ }
813
+ /**
814
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
815
+ * lifecycle status and a cancel function. Changing `fn` or the serialized
816
+ * `args` resets the stream — the previous iterator is cancelled and a fresh
817
+ * one opens with empty `chunks`.
818
+ *
819
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
820
+ * (mirrors `useQuery` / `useSubscription`).
821
+ */
822
+ declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: "skip" | ArgsOf<F>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
823
+ /**
824
+ * Result shape returned by {@link useHttpStream}.
825
+ * @experimental Part of the HTTP-SSE stream surface.
826
+ */
827
+ interface UseHttpStreamResult<T> {
828
+ /** Force-cancel the stream (aborts the fetch) and resolve the iterator. Safe to call multiple times. */
829
+ cancel: () => void;
830
+ /** Chunks the server has pushed so far, in arrival order. */
831
+ chunks: ReadonlyArray<T>;
832
+ error: Error | undefined;
833
+ status: UseStreamStatus;
834
+ }
835
+ /**
836
+ * Options accepted by {@link useHttpStream}.
837
+ * @experimental Part of the HTTP-SSE stream surface.
838
+ */
839
+ interface UseHttpStreamOptions {
840
+ /** Forwarded to `client.httpStream()` — caps the in-flight chunk buffer. */
841
+ maxBuffer?: number;
842
+ }
843
+ /**
844
+ * Consume an **HTTP-SSE route stream** (`httpRoute.&lt;verb>(path).stream()`) via
845
+ * `client.httpStream`. Distinct from `useStream`, which consumes the WS
846
+ * procedure stream (`kind: "stream"`). Returns the chunks received so far plus
847
+ * a lifecycle status and a cancel function. Changing the route or the
848
+ * serialized `args` resets the stream — the previous fetch is aborted (the
849
+ * server sees `request.signal`) and a fresh one opens with empty `chunks`.
850
+ * Unmount also aborts.
851
+ *
852
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
853
+ * (mirrors `useQuery` / `useStream`).
854
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
855
+ */
856
+ declare const useHttpStream: <Ref extends HttpStreamRef>(route: Ref, args: "skip" | HttpStreamArgsOf<Ref>, options?: UseHttpStreamOptions) => UseHttpStreamResult<HttpStreamChunkOf<Ref>>;
236
857
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
237
858
  type PaginatedArgs<F> = Omit<ArgsOf<F>, "paginationOpts">;
238
859
  /** The element type of the `page` array a paginated query returns. */
@@ -240,44 +861,44 @@ type PageItemOf<F> = ReturnOf<F> extends {
240
861
  page: (infer T)[];
241
862
  } ? T : unknown;
242
863
  /**
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
- */
864
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
865
+ *
866
+ * The query function must accept a `paginationOpts: { numItems, cursor,
867
+ * endCursor }` arg and return a `PaginationResult` (the shape
868
+ * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
869
+ * stable boundary cursors: each loaded page is a live subscription over a
870
+ * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
871
+ * Because boundaries are shared stable cursors, inserting or deleting a row in
872
+ * the middle of the list grows/shrinks the affected page in place without
873
+ * duplicating or skipping rows across page boundaries — the bug the legacy
874
+ * "first N after the previous page's last row" model suffered under live edits.
875
+ *
876
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
877
+ * it is a no-op unless `status === "CanLoadMore"`. Background split/join
878
+ * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
879
+ * `use-paginated-core.ts`).
880
+ *
881
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
882
+ * feed to its first page. The public return shape (`results` / `status` /
883
+ * `loadMore`) is unchanged from the legacy keyset implementation.
884
+ */
264
885
  declare const usePaginatedQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UsePaginatedQueryOptions) => UsePaginatedQueryResult<PageItemOf<F>>;
265
886
  /**
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
- */
887
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
888
+ *
889
+ * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
890
+ * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
891
+ * inserted or deleted mid-list grows/shrinks the affected page without
892
+ * duplicating or skipping rows across boundaries — but keeps each page as its
893
+ * own inner array rather than flattening them, and adds the
894
+ * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
895
+ * shape. `fetchNextPage` appends the next page off the open-ended tail's
896
+ * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
897
+ *
898
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
899
+ * feed to its first page. The public return shape is unchanged from the legacy
900
+ * keyset implementation.
901
+ */
281
902
  declare const useInfiniteQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UseInfiniteQueryOptions) => UseInfiniteQueryResult<PageItemOf<F>>;
282
903
  type CallOptions<F extends FunctionReference> = UseMutationCallOptions<unknown, unknown, ArgsOf<F>>;
283
904
  interface MutationHook<F extends FunctionReference> {
@@ -293,103 +914,128 @@ interface MutationHook<F extends FunctionReference> {
293
914
  /** Clear the latest `data`/`error` back to idle. */
294
915
  reset: () => void;
295
916
  /**
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
- */
917
+ * Bind a Convex-parity multi-query optimistic update to this mutation.
918
+ * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
919
+ * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
920
+ * is supplied in the call options, which overrides the bound one.
921
+ */
301
922
  withOptimisticUpdate: (update: OptimisticUpdate<ArgsOf<F>>) => MutationHook<F>;
302
923
  }
303
924
  /**
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
- */
925
+ * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
926
+ * given mutation reference. Prefer destructuring at the call site so the React
927
+ * linter can track dependencies on each field independently.
928
+ *
929
+ * Built on TanStack Query's mutation cache (the same cache the query hooks use),
930
+ * so it composes with Query Devtools and exposes the latest call's `data`/`error`
931
+ * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
932
+ * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
933
+ *
934
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance
935
+ * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
936
+ * `false` only once every concurrent call has settled — and a sibling component
937
+ * mutating the same function never affects it (TanStack's own `isPending` tracks
938
+ * just the latest invocation).
939
+ *
940
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
941
+ * call options pass straight through to `client.mutation`, which applies and
942
+ * rolls them back against the Lunora subscription cache (Convex parity) — not
943
+ * through TanStack's `onMutate`.
944
+ */
324
945
  declare const useMutation: <F extends FunctionReference>(function_: F) => MutationHook<F>;
946
+ interface MutatorHook<TArgs> {
947
+ /** The latest invocation's error, or `undefined`. */
948
+ error: Error | undefined;
949
+ /** `true` when the latest invocation rejected. */
950
+ isError: boolean;
951
+ /** Run the mutator; resolves once the write is persisted, rejects on failure. */
952
+ mutate: (args: TArgs) => Promise<void>;
953
+ /** `true` while ANY invocation from this hook is in flight (ref-counted, so overlapping calls compose). */
954
+ pending: boolean;
955
+ /** Clear the latest `error` back to idle. */
956
+ reset: () => void;
957
+ }
325
958
  /**
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
- */
959
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
960
+ * custom-mutator handle from `@lunora/db`'s `bindMutators`. The optimistic
961
+ * overlay and server-authoritative push are owned by the bound handle (and
962
+ * TanStack DB's optimistic-transaction layer rebases pending overlays on every
963
+ * sync tick) this hook only surfaces React state for the in-flight/error
964
+ * lifecycle. Reads stay on the existing `useLiveQuery`; no new query hook is
965
+ * needed.
966
+ *
967
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance,
968
+ * so it clears only once every concurrent call has settled.
969
+ */
970
+ declare const useMutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHook<TArgs>;
971
+ /**
972
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
973
+ * during SSR, then keep it live.
974
+ *
975
+ * The first render returns the preloaded value (TanStack's `initialData`),
976
+ * so the server markup and the initial client markup match — no hydration
977
+ * mismatch, no loading flash. After mount, a WS subscription attaches so
978
+ * later server pushes update the value just like `useQuery`.
979
+ *
980
+ * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
981
+ * full dehydrate/hydrate dance because the consumer hands us the resolved
982
+ * value directly. Apps that want to share a pre-populated QueryClient across
983
+ * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
984
+ * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
985
+ */
340
986
  declare const usePreloadedQuery: <T>(preloaded: Preloaded<T>) => T;
341
987
  /**
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
- */
988
+ * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
989
+ * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
990
+ * attaches a live WS subscription on mount. It is a thin alias of
991
+ * {@link usePreloadedQuery} so the React adapter exposes the same
992
+ * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
993
+ * while existing callers of `usePreloadedQuery` keep working unchanged.
994
+ *
995
+ * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
996
+ * call it like a hook — at the top level of a component, unconditionally.
997
+ */
352
998
  declare const hydratePreloaded: <T>(preloaded: Preloaded<T>) => T;
353
999
  /**
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
- */
1000
+ * `usePresence` — collaborative-awareness hook, the client half of the
1001
+ * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
1002
+ * parity).
1003
+ *
1004
+ * It drives the two presence functions the server component ships:
1005
+ *
1006
+ * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
1007
+ * whenever the tab becomes visible, to upsert the caller's presence row and
1008
+ * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
1009
+ * carries the latest `data` from a ref, so `setData` takes effect on the next
1010
+ * tick without re-subscribing or resetting the timer.
1011
+ * - **listPresent** (a query): subscribed to over the live-query WS, so the
1012
+ * present-list updates reactively. Because the server patches a single row per
1013
+ * heartbeat, the client's **per-row subscription delta merge** applies just that
1014
+ * row to the cached list instead of re-sending every member — the list stays
1015
+ * cheap even with many participants heart-beating.
1016
+ *
1017
+ * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
1018
+ * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
1019
+ * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
1020
+ * the hook needs no client-side reaping.
1021
+ *
1022
+ * The two `FunctionReference`s come from your generated `api` (e.g.
1023
+ * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
1024
+ * stays decoupled from any specific app schema.
1025
+ */
1026
+ /**
1027
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
1028
+ * `definePresence().functions.heartbeat` registers).
1029
+ */
384
1030
  type HeartbeatReference = FunctionReference<"mutation", {
385
1031
  data?: Record<string, unknown>;
386
1032
  roomId: string;
387
1033
  sessionId: string;
388
1034
  }>;
389
1035
  /**
390
- * A listPresent query reference: takes `{ roomId }` and returns the array of
391
- * present members.
392
- */
1036
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
1037
+ * present members.
1038
+ */
393
1039
  type ListPresentReference = FunctionReference<"query", {
394
1040
  roomId: string;
395
1041
  }>;
@@ -403,9 +1049,9 @@ interface UsePresenceOptions<H extends HeartbeatReference, L extends ListPresent
403
1049
  /** The `api.*` reference for the presence listPresent query. */
404
1050
  listPresent: L;
405
1051
  /**
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
- */
1052
+ * Stable id for this presence row. Defaults to a fresh per-mount id (one row
1053
+ * per tab). Pass a user/connection id to control deduping.
1054
+ */
409
1055
  sessionId?: string;
410
1056
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
411
1057
  shardKey?: string;
@@ -420,25 +1066,31 @@ interface UsePresenceResult<L extends ListPresentReference> {
420
1066
  }
421
1067
  declare const usePresence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: UsePresenceOptions<H, L>) => UsePresenceResult<L>;
422
1068
  /**
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
- */
1069
+ * Subscribe to a server query.
1070
+ *
1071
+ * Returns `undefined` until the first response lands. Pass `"skip"` for
1072
+ * `args` to short-circuit the query (no network call, no subscription).
1073
+ *
1074
+ * When the `LunoraClient` was created with `hydrateOnStart: true` and a
1075
+ * `queryCache` adapter, the first **enabled** render waits for the durable
1076
+ * read cache to finish loading. If a cached value exists for this query it
1077
+ * is fed as `initialData` so the user sees it immediately — no undefined
1078
+ * flash before the socket round-trip.
1079
+ *
1080
+ * Internally this routes through TanStack Query: the queryKey is
1081
+ * `["lunora", fn.__lunoraRef, args, shardKey]` (TanStack hashes structurally
1082
+ * so an args object built in a different key order still dedupes). The
1083
+ * subscription registry shares a single WS subscription across every consumer
1084
+ * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
1085
+ */
434
1086
  declare const useQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => ReturnOf<F> | undefined;
435
1087
  interface UseRateLimitOptions {
436
1088
  /** Clock injection for tests. Defaults to `Date.now`. */
437
1089
  now?: () => number;
438
1090
  /**
439
- * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
440
- * down and `disabled` flips back automatically. Defaults to `1000`.
441
- */
1091
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
1092
+ * down and `disabled` flips back automatically. Defaults to `1000`.
1093
+ */
442
1094
  tickMs?: number;
443
1095
  }
444
1096
  interface UseRateLimitResult {
@@ -456,44 +1108,161 @@ interface UseRateLimitResult {
456
1108
  retryAfter: number;
457
1109
  }
458
1110
  /**
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
- */
1111
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
1112
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
1113
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
1114
+ * authoritative check; the server remains the source of truth.
1115
+ *
1116
+ * `config` is read on every render; pass a stable reference (module constant or
1117
+ * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
1118
+ */
467
1119
  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;
1120
+ /**
1121
+ * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
1122
+ * hook does not issue an initial HTTP fetch — it only delivers values that
1123
+ * the server pushes over the WS.
1124
+ */
1125
+ declare const useSubscription: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => UseSubscriptionResult<ReturnOf<F>>;
1126
+ /**
1127
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
1128
+ * capture and speaker playback implementations injected into the hook via its
1129
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
1130
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
1131
+ * hook's transport + React-state logic and remains mockable in a non-browser
1132
+ * test env.
1133
+ */
1134
+ /**
1135
+ * The negotiated audio format the voice DO streams back. Mirrors
1136
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1137
+ * imported) so this React package never pulls in the server-only `@lunora/agent`
1138
+ * module graph.
1139
+ */
1140
+ type VoiceAudioFormat = "mp3" | "wav";
1141
+ /** Captures microphone audio and reports level / turn boundaries back to the hook. */
1142
+ interface VoiceMicrophone {
1143
+ /** Mute/unmute the mic without tearing down the capture graph. */
1144
+ setMuted: (muted: boolean) => void;
1145
+ /** Stop capture and release the media stream + audio graph. */
1146
+ stop: () => void;
477
1147
  }
478
- interface UseStreamOptions {
479
- /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
480
- maxBuffer?: number;
481
- shardKey?: string;
1148
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1149
+ interface VoiceSpeaker {
1150
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1151
+ enqueue: (audio: Uint8Array) => void;
1152
+ /** Drop everything queued and stop the current chunk (barge-in). */
1153
+ interrupt: () => void;
1154
+ /** Release the playback audio context. */
1155
+ stop: () => void;
1156
+ }
1157
+ /** Config passed to a {@link CreateMicrophone} factory. */
1158
+ interface MicrophoneConfig {
1159
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1160
+ interruptChunks: number;
1161
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1162
+ interruptThreshold: number;
1163
+ /** `true` while `status === "speaking"` — gates barge-in detection. */
1164
+ isSpeaking: () => boolean;
1165
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1166
+ onAudio: (pcm: Uint8Array) => void;
1167
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1168
+ onInterrupt: () => void;
1169
+ /** The current input RMS (0–1), for a level meter. */
1170
+ onLevel: (rms: number) => void;
1171
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1172
+ onSilence: () => void;
1173
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1174
+ silenceDurationMs: number;
1175
+ /** RMS below which audio counts as silence. */
1176
+ silenceThreshold: number;
482
1177
  }
1178
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1179
+ type CreateSpeaker = (config: {
1180
+ audioFormat: VoiceAudioFormat;
1181
+ }) => VoiceSpeaker;
483
1182
  /**
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>>;
1183
+ * The `agents.&lt;name>Voice` reference codegen emits for a voice-enabled agent a
1184
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1185
+ * generated member, so passing `api.agents.&lt;name>Voice` type-checks.
1186
+ */
1187
+ type VoiceReference = FunctionReference<"stream", {
1188
+ threadKey: string;
1189
+ }, Record<string, unknown>>;
1190
+ /** The lifecycle of a voice call, mirrored to the UI. */
1191
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1192
+ /** A minimal structural subset of the DOM `WebSocket` the hook drives. */
1193
+ interface VoiceSocket {
1194
+ binaryType: string;
1195
+ close: () => void;
1196
+ onclose: ((event: unknown) => void) | null;
1197
+ onerror: ((event: unknown) => void) | null;
1198
+ onmessage: ((event: {
1199
+ data: unknown;
1200
+ }) => void) | null;
1201
+ onopen: ((event: unknown) => void) | null;
1202
+ readonly readyState: number;
1203
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1204
+ }
1205
+ type CreateSocket = (url: string) => VoiceSocket;
1206
+ interface UseVoiceAgentOptions {
1207
+ /**
1208
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1209
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1210
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1211
+ */
1212
+ createMicrophone?: CreateMicrophone;
1213
+ /** Advanced/test seam: open the transport. Defaults to `new WebSocket(url)`. */
1214
+ createSocket?: CreateSocket;
1215
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1216
+ createSpeaker?: CreateSpeaker;
1217
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1218
+ interruptChunks?: number;
1219
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1220
+ interruptThreshold?: number;
1221
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1222
+ silenceDurationMs?: number;
1223
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1224
+ silenceThreshold?: number;
1225
+ /** The thread to converse on — shared with the agent's text turns. */
1226
+ threadKey: string;
1227
+ /** The generated `api.agents.&lt;name>Voice` reference — identifies the voice DO endpoint. */
1228
+ voice: VoiceReference;
1229
+ }
1230
+ interface UseVoiceAgentResult {
1231
+ /** The current input RMS (0–1) — drive a mic level meter. */
1232
+ audioLevel: number;
1233
+ /** `true` once the WS `ready` handshake completed. */
1234
+ connected: boolean;
1235
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1236
+ endCall: () => void;
1237
+ /** The last transport/pipeline error, or `undefined`. */
1238
+ error: Error | undefined;
1239
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1240
+ interimTranscript: string;
1241
+ /** `true` while the mic is muted. */
1242
+ isMuted: boolean;
1243
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1244
+ sendText: (text: string) => void;
1245
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1246
+ startCall: () => Promise<void>;
1247
+ /** The current call lifecycle. */
1248
+ status: VoiceStatus;
1249
+ /** Mute/unmute the microphone. Returns the new muted state. */
1250
+ toggleMute: () => boolean;
1251
+ /** The last finalized user utterance (STT result). */
1252
+ transcript: string;
1253
+ }
493
1254
  /**
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 };
1255
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1256
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1257
+ * streams the agent's synthesized speech back through the browser's audio output,
1258
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1259
+ * `audioLevel`) to React state. Pass the generated `api.agents.&lt;name>Voice`
1260
+ * reference (never a string), matching `useAgentChat`'s reference-passing style.
1261
+ *
1262
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1263
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1264
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1265
+ * `createSocket`) so the hook is drivable outside a browser.
1266
+ */
1267
+ declare const useVoiceAgent: (options: UseVoiceAgentOptions) => UseVoiceAgentResult;
1268
+ export { type AdminAuthListResult, 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 UseAuthSessionsOptions, type UseAuthUsersOptions, type UseCheckoutResult, type UseHttpStreamOptions, type UseHttpStreamResult, type UseImpersonateResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationCallOptions, type UseOrganizationsOptions, 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, useAuthSessions, useAuthState, useAuthUsers, useCheckout, useClientQuery, useConnectionStatus, useFlag, useFlags, useHttpStream, useImpersonate, useInfiniteQuery, useLunora, useMutation, useMutator, useOrganizations, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription, useVoiceAgent };