@lunora/react 1.0.0-alpha.8 → 1.0.0-alpha.81

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 (73) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +25 -18
  3. package/dist/index.d.mts +1127 -355
  4. package/dist/index.d.ts +1127 -355
  5. package/dist/index.mjs +1 -18
  6. package/dist/packem_shared/AuthLoading-dC08yqew.mjs +2 -0
  7. package/dist/packem_shared/LunoraProvider-DC06S-p1.mjs +2 -0
  8. package/dist/packem_shared/cache-DmbajSjf.mjs +1 -0
  9. package/dist/packem_shared/hydratePreloaded-CcBW4phD.mjs +2 -0
  10. package/dist/packem_shared/lunoraQueryOptions-B5PEocLy.mjs +1 -0
  11. package/dist/packem_shared/query-key-C6iUhRuD.mjs +1 -0
  12. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.mts +38 -0
  13. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.ts +38 -0
  14. package/dist/packem_shared/stable-key-B_BlboiY.mjs +1 -0
  15. package/dist/packem_shared/stream-state-abygFxmy.mjs +1 -0
  16. package/dist/packem_shared/use-paginated-core-CWfn4qb4.mjs +2 -0
  17. package/dist/packem_shared/useAction-CUSJu4yq.mjs +2 -0
  18. package/dist/packem_shared/useAgent-CNDRZNk_.mjs +2 -0
  19. package/dist/packem_shared/useAgentChat-CXJldvLG.mjs +2 -0
  20. package/dist/packem_shared/useAgentState-BOIQjgxe.mjs +2 -0
  21. package/dist/packem_shared/useAgentToolEvents-B4gy1Q5z.mjs +2 -0
  22. package/dist/packem_shared/useAuth-x4boOoAR.mjs +2 -0
  23. package/dist/packem_shared/useAuthSessions-Bq4-f3g-.mjs +2 -0
  24. package/dist/packem_shared/useAuthState-CoOG9XdT.mjs +2 -0
  25. package/dist/packem_shared/useClientQuery-DFs7trEf.mjs +2 -0
  26. package/dist/packem_shared/useConnectionStatus-XYsYGiT6.mjs +2 -0
  27. package/dist/packem_shared/useFlag-BDM923ke.mjs +2 -0
  28. package/dist/packem_shared/useHttpStream-D9vum8Qx.mjs +2 -0
  29. package/dist/packem_shared/useInfiniteQuery-C7wp0W2d.mjs +2 -0
  30. package/dist/packem_shared/useMutation-BnKec7bE.mjs +2 -0
  31. package/dist/packem_shared/useMutator-BtUd-xEA.mjs +2 -0
  32. package/dist/packem_shared/usePaginatedQuery-DJNa8KKD.mjs +2 -0
  33. package/dist/packem_shared/usePresence-BVjZyltT.mjs +2 -0
  34. package/dist/packem_shared/useQuery-BUzNP_Vb.mjs +2 -0
  35. package/dist/packem_shared/useRateLimit-Cckxi8m9.mjs +2 -0
  36. package/dist/packem_shared/useStream-CmGOT0qj.mjs +2 -0
  37. package/dist/packem_shared/useSubscription-BHVICtbD.mjs +2 -0
  38. package/dist/packem_shared/useVoiceAgent-C9NI6Vzl.mjs +2 -0
  39. package/dist/packem_shared/wire-key-L5JSXhhG.mjs +1 -0
  40. package/dist/payment.d.mts +93 -0
  41. package/dist/payment.d.ts +93 -0
  42. package/dist/payment.mjs +2 -0
  43. package/dist/server.d.mts +47 -29
  44. package/dist/server.d.ts +47 -29
  45. package/dist/server.mjs +1 -31
  46. package/dist/upload.d.mts +23 -0
  47. package/dist/upload.d.ts +23 -0
  48. package/dist/upload.mjs +2 -0
  49. package/package.json +14 -4
  50. package/dist/packem_shared/AuthLoading-DtKgZT2Z.mjs +0 -33
  51. package/dist/packem_shared/CheckoutButton-CVSry8U1.mjs +0 -185
  52. package/dist/packem_shared/LunoraProvider-D38Xp16l.mjs +0 -80
  53. package/dist/packem_shared/cache-CAp1fVNL.mjs +0 -75
  54. package/dist/packem_shared/hydratePreloaded-B6OHn0eL.mjs +0 -46
  55. package/dist/packem_shared/lunoraQueryOptions-Cij4KWBK.mjs +0 -16
  56. package/dist/packem_shared/query-key-B5eRQCbR.mjs +0 -13
  57. package/dist/packem_shared/query-options.d-D4okOpO8.d.mts +0 -38
  58. package/dist/packem_shared/query-options.d-D4okOpO8.d.ts +0 -38
  59. package/dist/packem_shared/stable-key-CaKZv9lp.mjs +0 -30
  60. package/dist/packem_shared/use-paginated-core-DP72UNWn.mjs +0 -176
  61. package/dist/packem_shared/useAuth-CNUKtOOp.mjs +0 -129
  62. package/dist/packem_shared/useAuthState-BiGhtSCs.mjs +0 -36
  63. package/dist/packem_shared/useConnectionStatus-DRSY9ldm.mjs +0 -30
  64. package/dist/packem_shared/useFlag-Bg5DpkGv.mjs +0 -224
  65. package/dist/packem_shared/useInfiniteQuery-BBIDFXBN.mjs +0 -97
  66. package/dist/packem_shared/useMutation-CrvMXRsk.mjs +0 -67
  67. package/dist/packem_shared/useMutator-IIrLtDiM.mjs +0 -47
  68. package/dist/packem_shared/usePaginatedQuery-AQO3kdp1.mjs +0 -46
  69. package/dist/packem_shared/usePresence-D7jLuxj0.mjs +0 -108
  70. package/dist/packem_shared/useQuery-EB74gtBJ.mjs +0 -42
  71. package/dist/packem_shared/useRateLimit-DTEffQEi.mjs +0 -64
  72. package/dist/packem_shared/useStream-MdYnWDL_.mjs +0 -125
  73. package/dist/packem_shared/useSubscription-DSJuryrU.mjs +0 -139
package/dist/index.d.mts CHANGED
@@ -1,174 +1,84 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { LunoraClient, OptimisticUpdate, User, ConnectionStatus, ReturnOf, ArgsOf, FunctionReference, MutatorHandle, Preloaded } from '@lunora/client';
3
- export type { ArgsOf, FunctionReference, LunoraClient, MutatorHandle, MutatorTransaction, OptimisticLocalStore, OptimisticUpdate, Preloaded, ReturnOf, User } from '@lunora/client';
2
+ import { LunoraClient, OptimisticUpdate, User, SubscriptionErrorCallback, SubscriptionError, FunctionReference, ArgsOf, ActionCallOptions, ReturnOf, AuthImpersonation, AuthSession, AuthUser, ClientQueryRef, ConnectionStatus, HttpStreamRef, HttpStreamArgsOf, HttpStreamChunkOf, MutatorHandle, Preloaded } from '@lunora/client';
3
+ export { type ArgsOf, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, 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 SubscriptionError, type SubscriptionErrorCallback, type User, createClientQuery, getErrorCode, getRetryAfterMs, isConflictError, isForbiddenError, isRateLimitedError, isUnauthorizedError } from '@lunora/client';
4
4
  import { QueryClient } from '@tanstack/react-query';
5
- export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-D4okOpO8.mjs";
5
+ export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-CdgGQ9s4.mjs";
6
6
  import { PaginationStatus } from '@lunora/client/pagination';
7
7
  export type { PaginationResult, PaginationStatus } from '@lunora/client/pagination';
8
8
  import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
9
+ export { RestrictionError, UploadControl, UploadError, type UploadRestrictions } from '@visulima/storage-client';
10
+ 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';
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 `&lt;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
- /**
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
- */
80
- interface Subscription {
81
- readonly cancelAtPeriodEnd: boolean;
82
- readonly createdAt: number;
83
- readonly currentPeriodEnd?: number;
84
- readonly id: string;
85
- readonly priceId: string;
86
- readonly provider: "polar" | "stripe";
87
- readonly quantity: number;
88
- readonly referenceId: string;
89
- readonly state: "active" | "canceled" | "past_due" | "paused" | "trialing";
90
- readonly updatedAt: number;
91
- }
92
- /** The `{ url }` shape every checkout/portal trigger resolves to. */
93
- interface RedirectTarget {
94
- readonly url: string;
95
- }
96
- /** A thunk the app supplies that calls its own Lunora action and resolves a redirect URL. */
97
- type RedirectTrigger = () => Promise<RedirectTarget>;
98
- interface UseCheckoutResult {
99
- /** Run the trigger and redirect the browser to the resolved URL. Resolves once the redirect is issued; rejects on failure. */
100
- checkout: () => Promise<void>;
101
- /** The most recent failure, or `undefined`. */
102
- error: Error | undefined;
103
- /** `true` while the trigger is in flight (before the redirect is issued). */
104
- pending: boolean;
105
- }
106
- /**
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
- */
118
- declare const useCheckout: (trigger: RedirectTrigger) => UseCheckoutResult;
119
- /**
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
- */
125
- interface RedirectButtonOwnProps {
126
- /** Accessible label when the visible `children` are icon-only. */
127
- "aria-label"?: string;
128
- children?: ReactNode;
129
- className?: string;
130
- /** Force-disable the control regardless of pending state. */
131
- disabled?: boolean;
132
- /** Called with the failure when the trigger rejects. The error is also surfaced via `useCheckout`. */
133
- onError?: (error: Error) => void;
134
- title?: string;
135
- }
136
- interface CheckoutButtonProps extends RedirectButtonOwnProps {
137
- /** Calls the app's checkout action and resolves the hosted-checkout `{ url }`. */
138
- onCheckout: RedirectTrigger;
139
- }
140
- interface CustomerPortalButtonProps extends RedirectButtonOwnProps {
141
- /** Calls the app's portal action and resolves the customer-portal `{ url }`. */
142
- onPortal: RedirectTrigger;
143
- }
144
- /**
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;
162
66
  interface UseQueryOptions {
67
+ /**
68
+ * Called when the server pushes a subscription-scoped error (an RLS denial, a
69
+ * query that starts failing server-side). Without a handler such an error has
70
+ * nowhere to go and the hook's value simply freezes at its last good result.
71
+ */
72
+ onError?: SubscriptionErrorCallback;
163
73
  shardKey?: string;
164
74
  }
165
75
  interface UseMutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
166
76
  optimistic?: (current: TCurrent | undefined) => TValue;
167
77
  /**
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
- */
78
+ * Convex-parity multi-query optimistic update forwarded to
79
+ * `client.mutation`. Patches many subscribed queries at once via an
80
+ * `OptimisticLocalStore`, rolled back atomically on failure.
81
+ */
172
82
  optimisticUpdate?: OptimisticUpdate<TArgs>;
173
83
  shardKey?: string;
174
84
  }
@@ -179,9 +89,19 @@ interface UseSubscriptionResult<T> {
179
89
  interface UsePaginatedQueryOptions {
180
90
  /** Page size for the first page (and the default for `loadMore`). */
181
91
  initialNumItems: number;
92
+ /** Called when a page subscription (or its initial fetch) fails; also surfaced on `error`. */
93
+ onError?: SubscriptionErrorCallback;
182
94
  shardKey?: string;
183
95
  }
184
96
  interface UsePaginatedQueryResult<T> {
97
+ /**
98
+ * The last page failure, or `undefined`. A tail page that fails before its
99
+ * first frame is dropped so `status` returns to `"CanLoadMore"` and
100
+ * `loadMore` can retry it; the first page has nothing to fall back to and
101
+ * stays `"LoadingFirstPage"` with this set. Cleared by the next successful
102
+ * frame, by `loadMore`, or by an args change.
103
+ */
104
+ error: SubscriptionError | undefined;
185
105
  /** `true` while the first page or a `loadMore` page is in flight. */
186
106
  isLoading: boolean;
187
107
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
@@ -193,9 +113,13 @@ interface UsePaginatedQueryResult<T> {
193
113
  interface UseInfiniteQueryOptions {
194
114
  /** Page size for the first page (and the default for `fetchNextPage`). */
195
115
  initialNumItems: number;
116
+ /** Called when a page subscription (or its initial fetch) fails; also surfaced on `error`. */
117
+ onError?: SubscriptionErrorCallback;
196
118
  shardKey?: string;
197
119
  }
198
120
  interface UseInfiniteQueryResult<T> {
121
+ /** The last page failure, or `undefined` — see `UsePaginatedQueryResult.error`. */
122
+ error: SubscriptionError | undefined;
199
123
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
200
124
  fetchNextPage: (numberItems?: number) => void;
201
125
  /** `true` when the loaded tail reports it can load another page. */
@@ -213,58 +137,720 @@ interface UseAuthResult {
213
137
  token: string | null;
214
138
  user: User | null;
215
139
  }
140
+ interface ActionHook<F extends FunctionReference> {
141
+ /**
142
+ * Invoke the action. Awaitable, and rejects on failure — the same contract
143
+ * as `useMutation`'s `mutate`.
144
+ */
145
+ call: (args: ArgsOf<F>, options?: ActionCallOptions) => Promise<ReturnOf<F>>;
146
+ /** The latest invocation's resolved value, or `undefined` before the first success. */
147
+ data: ReturnOf<F> | undefined;
148
+ /** The latest invocation's error, or `undefined`. */
149
+ error: Error | undefined;
150
+ /** `true` while ANY invocation from this hook is in flight (ref-counted, so overlapping calls compose). */
151
+ pending: boolean;
152
+ /** Clear the latest `data`/`error` back to idle. */
153
+ reset: () => void;
154
+ }
155
+ /**
156
+ * Returns `{ call, pending, data, error, reset }` for the given action reference.
157
+ * Prefer destructuring at the call site so the React linter can track
158
+ * dependencies on each field independently.
159
+ *
160
+ * Actions were the one procedure kind with no hook: `useQuery` and `useMutation`
161
+ * shipped, so every app that called an action reached for `useLunora()` and
162
+ * re-derived the same pending/error wrapper by hand. This is that wrapper, once.
163
+ *
164
+ * The request state machine is the shared `createCallRunner` from
165
+ * `@lunora/client` — the same one Vue, Solid and Svelte bind to their own
166
+ * primitives — so `pending`, error normalization and latest-invocation ordering
167
+ * behave identically in every adapter. Only the `useState` cells are React's.
168
+ * TanStack's mutation cache still carries the call so it shows up in Query
169
+ * Devtools alongside `useQuery`/`useMutation`.
170
+ *
171
+ * **Lifecycle contract** (identical across the adapters): `data` and `error`
172
+ * both track the LATEST invocation, not the last to settle — a double-click
173
+ * whose first call resolves after the second cannot overwrite the second's
174
+ * outcome. A success clears `error`; a failure leaves the previous `data` in
175
+ * place, so a transient error does not blank the view. `reset()` clears both,
176
+ * but does NOT cancel an in-flight call, whose result still lands.
177
+ *
178
+ * **Why the two TanStack defaults are overridden.** `networkMode` is `"always"`
179
+ * because the default `"online"` pauses the retryer *after* the call is already
180
+ * marked pending: offline, the promise would never settle, the spinner would
181
+ * stick, and the action would silently fire minutes later on reconnect. `retry`
182
+ * is pinned to `0` — not inherited from an app-supplied QueryClient — because
183
+ * `client.action` sends no idempotency key, so a retry after a 502 on an action
184
+ * that already ran server-side would run it a second time. A mutation may pause
185
+ * and retry safely; it carries a `mutationId` and an offline queue. An action
186
+ * carries neither.
187
+ *
188
+ * **What it deliberately does not carry.** There is no `optimistic` /
189
+ * `optimisticUpdate` and no `withOptimisticUpdate`, which `useMutation` has. An
190
+ * optimistic update patches the subscription cache on the assumption the write
191
+ * will land; an action is not a write — it runs in the Worker, may call a third
192
+ * party, and has no declared effect on any query. Offering the option would
193
+ * imply a rollback guarantee nothing can honour.
194
+ *
195
+ * ```tsx
196
+ * const { call: runCommand, pending } = useAction(api.commands.run);
197
+ *
198
+ * await runCommand({ command: "lunora", args: ["verify"] });
199
+ * ```
200
+ */
201
+ declare const useAction: <F extends FunctionReference>(function_: F) => ActionHook<F>;
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.<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
+ * Called when the live thread subscription reports an error (a session
383
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
384
+ * failure is invisible and `thread` / `status` freeze at their last value.
385
+ */
386
+ onError?: SubscriptionErrorCallback;
387
+ /**
388
+ * The app mutation that starts (or continues) a run — a thin wrapper over
389
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
390
+ * {@link UseAgentOptions.runArgs} and the per-call args.
391
+ */
392
+ run: FunctionReference<"mutation">;
393
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
394
+ runArgs?: Record<string, unknown>;
395
+ /** The thread to observe and drive. */
396
+ threadKey: string;
397
+ }
398
+ interface UseAgentResult {
399
+ /**
400
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
401
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
402
+ */
403
+ cancel: () => Promise<void>;
404
+ /** The live thread subscription's last error, or `undefined`. */
405
+ error: Error | undefined;
406
+ /** `true` while a `run` invocation is in flight. */
407
+ pending: boolean;
408
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
409
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
410
+ /** The live thread status, or `undefined` before the thread exists. */
411
+ status: AgentThreadStatus | undefined;
412
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
413
+ thread: AgentThreadRecord | undefined;
414
+ }
415
+ /**
416
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
417
+ * chat message surface. Composes `useSubscription(api.agents.agentThread)` for
418
+ * live state and `useMutation` for the run/cancel writes. For the full
419
+ * conversation surface (durable history + streaming + approvals) use
420
+ * `useAgentChat`.
421
+ *
422
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
423
+ * `ctx.agents.<name>.run` / `.cancel`, so the hook hard-codes no function names
424
+ * beyond the `agents:*` surface.
425
+ */
426
+ declare const useAgent: (options: UseAgentOptions) => UseAgentResult;
427
+ /**
428
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
429
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
430
+ * re-declared here (rather than imported) so this React entry never pulls in the
431
+ * server-only `@lunora/agent` module graph. Keep in sync with the `agent_messages`
432
+ * table in `packages/agent/src/component.ts`.
433
+ */
434
+ interface AgentChatMessage {
435
+ content: string;
436
+ createdAt?: number;
437
+ /**
438
+ * `true` for a client-side optimistic user message not yet acknowledged by
439
+ * the server. Cleared once the durable history carries the matching user turn.
440
+ */
441
+ optimistic?: boolean;
442
+ role: "assistant" | "system" | "tool" | "user";
443
+ seq: number;
444
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
445
+ status?: "approved" | "awaiting_approval" | "rejected";
446
+ toolCallId?: string;
447
+ toolCalls?: ReadonlyArray<{
448
+ id: string;
449
+ input: unknown;
450
+ name: string;
451
+ }>;
452
+ toolName?: string;
453
+ }
454
+ /**
455
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
456
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
457
+ * {@link UseAgentChatResult.streamingText} live and are never replayed; the
458
+ * persisted assistant message stays the single source of truth.
459
+ */
460
+ interface AgentTokenDelta {
461
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
462
+ kind?: "token";
463
+ /** The incremental text chunk the model just produced. */
464
+ text: string;
465
+ /** The thread this delta belongs to. */
466
+ threadKey: string;
467
+ /** The zero-based index of the turn producing the delta. */
468
+ turn: number;
469
+ }
216
470
  /**
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
- */
471
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
472
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
473
+ * surfaced by `useAgentToolEvents`, ignored by {@link UseAgentChatResult.streamingText}.
474
+ */
475
+ interface AgentProgressEvent {
476
+ /** The arbitrary, JSON-serializable payload the tool reported. */
477
+ data: unknown;
478
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
479
+ kind: "progress";
480
+ /** The thread this event belongs to. */
481
+ threadKey: string;
482
+ /** The tool call this progress belongs to. */
483
+ toolCallId: string;
484
+ }
485
+ /**
486
+ * A single event on the agent's live-only channel — a streamed token delta or a
487
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
488
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
489
+ * it unset).
490
+ */
491
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
492
+ /** The `agents:agentMessages` reference — live durable thread history. */
493
+ type AgentMessagesReference$1 = FunctionReference<"query", {
494
+ key: string;
495
+ limit?: number;
496
+ }, ReadonlyArray<Record<string, unknown>>>;
497
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
498
+ type AgentApprovalReference = FunctionReference<"mutation", {
499
+ decision: "approve" | "reject";
500
+ instanceId: string;
501
+ note?: string;
502
+ threadKey: string;
503
+ toolCallId: string;
504
+ }, {
505
+ resolved: boolean;
506
+ }>;
507
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
508
+ type AgentThreadReference = FunctionReference<"query", {
509
+ key: string;
510
+ }, Record<string, unknown> | undefined>;
511
+ /**
512
+ * An app stream reference that tees the agent's in-flight live events, keyed by
513
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
514
+ * sink — tool progress events; this hook consumes only the token arm.
515
+ */
516
+ type AgentTokenStreamReference = FunctionReference<"stream", {
517
+ key: string;
518
+ }, AgentLiveEvent>;
519
+ /**
520
+ * The `agents.*` reference surface the chat hook reads. A structural subset of
521
+ * the generated `api.agents`, so the whole generated `api` object is assignable.
522
+ */
523
+ interface UseAgentChatApi {
524
+ agents: {
525
+ agentMessages: AgentMessagesReference$1;
526
+ agentResolveApproval: AgentApprovalReference;
527
+ agentThread: AgentThreadReference;
528
+ };
529
+ }
530
+ interface UseAgentChatOptions {
531
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
532
+ api: UseAgentChatApi;
533
+ /**
534
+ * Optional app mutation over the agent's cancel path
535
+ * (`ctx.agents.<name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
536
+ * When omitted (or no run is in flight) {@link UseAgentChatResult.cancel} is a
537
+ * no-op.
538
+ */
539
+ cancel?: FunctionReference<"mutation">;
540
+ /** History depth forwarded to `agents:agentMessages`. */
541
+ limit?: number;
542
+ /**
543
+ * Called when the live history or thread subscription reports an error (a
544
+ * session expiry, an RLS denial). Without it — and without reading `error` —
545
+ * such a failure is invisible and `messages` / `status` freeze at their last
546
+ * value.
547
+ */
548
+ onError?: SubscriptionErrorCallback;
549
+ /**
550
+ * The app mutation that starts (or continues) a run — a thin wrapper over
551
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
552
+ * {@link UseAgentChatOptions.sendArgs} and the per-call args.
553
+ */
554
+ send: FunctionReference<"mutation">;
555
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
556
+ sendArgs?: Record<string, unknown>;
557
+ /**
558
+ * Optional live token-delta stream — an app stream function that tees the
559
+ * agent's in-flight deltas. When omitted {@link UseAgentChatResult.streamingText}
560
+ * stays empty and the UI updates message-by-message from durable history.
561
+ */
562
+ stream?: AgentTokenStreamReference;
563
+ /** The thread to observe and continue. */
564
+ threadKey: string;
565
+ }
566
+ interface UseAgentChatResult {
567
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
568
+ approve: (toolCallId: string, note?: string) => Promise<void>;
569
+ /**
570
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
571
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
572
+ */
573
+ cancel: () => Promise<void>;
574
+ /** The history or thread subscription's last error, or `undefined`. */
575
+ error: Error | undefined;
576
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
577
+ messages: ReadonlyArray<AgentChatMessage>;
578
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
579
+ reject: (toolCallId: string, note?: string) => Promise<void>;
580
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
581
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
582
+ /** The live thread status, or `undefined` before the thread exists. */
583
+ status: AgentThreadStatus | undefined;
584
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
585
+ streamingText: string;
586
+ }
587
+ /**
588
+ * A first-class agent chat surface: live durable history + in-flight token
589
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey`.
590
+ *
591
+ * It composes the existing primitives rather than adding transport:
592
+ * `useSubscription(api.agents.agentMessages)` for durable history,
593
+ * `useSubscription(api.agents.agentThread)` for live status + the in-flight
594
+ * `instanceId`, {@link useStream} over an app token stream for in-flight deltas,
595
+ * and `useMutation` for the writes (`api.agents.agentResolveApproval` for
596
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*`
597
+ * surface is hard-coded — `send`/`cancel`/`stream` stay generic references.
598
+ *
599
+ * A `send` optimistically appends the user turn so it renders immediately; the
600
+ * optimistic row clears once the durable history carries the acknowledged turn.
601
+ * `streamingText` is live-only: it holds the current turn's streamed text and
602
+ * empties as soon as that turn's assistant message lands in `messages` (the
603
+ * persisted message is the source of truth), consistent with the loop's
604
+ * replay-safe, live-only delta design.
605
+ */
606
+ declare const useAgentChat: (options: UseAgentChatOptions) => UseAgentChatResult;
607
+ /**
608
+ * The `agents.agentState` reference the hook subscribes to for the thread's live
609
+ * synced state. A structural subset of the generated `api.agents` surface (like
610
+ * `UseAgentApi` for `agentThread`), so the whole generated `api` object is
611
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type
612
+ * is mirrored by the hook's generic `T`, since codegen pins the reference return
613
+ * as an optional record (it never evaluates agent config).
614
+ */
615
+ interface UseAgentStateApi {
616
+ agents: {
617
+ agentState: FunctionReference<"query", {
618
+ key: string;
619
+ }, Record<string, unknown> | undefined>;
620
+ };
621
+ }
622
+ interface UseAgentStateOptions {
623
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
624
+ api: UseAgentStateApi;
625
+ /** The thread whose synced state to observe. */
626
+ threadKey: string;
627
+ }
628
+ interface UseAgentStateResult<T> {
629
+ /** The subscription error, if the live channel reported one. */
630
+ error: Error | undefined;
631
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
632
+ state: T | undefined;
633
+ }
634
+ /**
635
+ * Subscribe to an agent thread's synced state — the `setState`-style value a
636
+ * tool writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`.
637
+ * A thin wrapper over `useSubscription(api.agents.agentState, { key })`: the
638
+ * server pushes a fresh frame whenever the state changes (the dedicated query's
639
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
640
+ * `state` updates only on a real `setState`.
641
+ *
642
+ * Generic over the app's state shape (`useAgentState` with a `SupportState` type
643
+ * argument, itself a record) — the reference is typed as an optional record
644
+ * because codegen cannot see the per-agent state type; the generic casts to `T`.
645
+ * The `extends` bound (not a bare unbounded type parameter) is required: this
646
+ * `.ts` file is parsed JSX-aware by the bundler, where an unbounded type-param
647
+ * arrow is ambiguous with a JSX element.
648
+ */
649
+ declare const useAgentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: UseAgentStateOptions) => UseAgentStateResult<T>;
650
+ /** The `agents:agentMessages` reference — live durable thread history. */
651
+ type AgentMessagesReference = FunctionReference<"query", {
652
+ key: string;
653
+ limit?: number;
654
+ }, ReadonlyArray<Record<string, unknown>>>;
655
+ /**
656
+ * An app stream reference that tees the agent's in-flight live events, keyed by
657
+ * thread. Carries token deltas and tool progress events; this hook consumes only
658
+ * the progress arm (`kind === "progress"`).
659
+ */
660
+ type AgentLiveStreamReference = FunctionReference<"stream", {
661
+ key: string;
662
+ }, AgentLiveEvent>;
663
+ /**
664
+ * The `agents.*` reference surface the tool-events hook reads. A structural
665
+ * subset of the generated `api.agents`, so the whole generated `api` object is
666
+ * assignable.
667
+ */
668
+ interface UseAgentToolEventsApi {
669
+ agents: {
670
+ agentMessages: AgentMessagesReference;
671
+ };
672
+ }
673
+ interface UseAgentToolEventsOptions {
674
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
675
+ api: UseAgentToolEventsApi;
676
+ /** History depth forwarded to `agents:agentMessages`. */
677
+ limit?: number;
678
+ /**
679
+ * Optional live event stream — the same app stream function `useAgentChat`
680
+ * uses. When supplied, ephemeral `ctx.reportProgress(...)` events for the
681
+ * thread are surfaced as `{ type: "progress" }` entries; when omitted only the
682
+ * durable lifecycle (call / result / awaiting-approval) is returned.
683
+ */
684
+ stream?: AgentLiveStreamReference;
685
+ /** The thread whose tool activity to observe. */
686
+ threadKey: string;
687
+ }
688
+ /**
689
+ * A single tool-lifecycle event for a thread. The durable arms
690
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
691
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
692
+ * stream and has no `seq`. Discriminate on `type`.
693
+ */
694
+ type AgentToolEvent = {
695
+ data: unknown;
696
+ toolCallId: string;
697
+ type: "progress";
698
+ } | {
699
+ input: unknown;
700
+ seq: number;
701
+ toolCallId: string;
702
+ toolName: string;
703
+ type: "call";
704
+ } | {
705
+ output: string;
706
+ seq: number;
707
+ status?: "approved" | "rejected";
708
+ toolCallId?: string;
709
+ toolName?: string;
710
+ type: "result";
711
+ } | {
712
+ seq: number;
713
+ toolCallId?: string;
714
+ toolName?: string;
715
+ type: "awaiting-approval";
716
+ };
717
+ interface UseAgentToolEventsResult {
718
+ /**
719
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
720
+ * followed by any in-flight ephemeral progress events. Rebuilt each render
721
+ * from the live subscription + stream — treat as derived, not identity-stable.
722
+ */
723
+ events: ReadonlyArray<AgentToolEvent>;
724
+ }
725
+ /**
726
+ * A focused view of a thread's tool activity: tool calls, their results,
727
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
728
+ * without the full chat message surface. Composes the existing primitives:
729
+ * `useSubscription(api.agents.agentMessages)` for the durable lifecycle and
730
+ * {@link useStream} over the optional app event stream for ephemeral progress.
731
+ *
732
+ * Progress events are live-only (the durable path never emits them): they ride
733
+ * the same sink as token deltas and are surfaced here, correlated to their tool
734
+ * call by `toolCallId`. For the conversational surface (messages + streaming
735
+ * text + approvals) use `useAgentChat`; this hook is the tool-observability slice.
736
+ */
737
+ declare const useAgentToolEvents: (options: UseAgentToolEventsOptions) => UseAgentToolEventsResult;
738
+ /**
739
+ * Token + identity plumbing. The token lives on the shared `LunoraClient`;
740
+ * `setToken(jwt)` after a sign-in makes subsequent RPC calls carry the
741
+ * `Authorization` header. `user` is resolved from better-auth's `get-session`
742
+ * endpoint via `client.getCurrentUser()` — fetched on mount and refetched
743
+ * whenever the token changes (`onAuthTokenChange`), and `null` when signed out.
744
+ *
745
+ * Multiple `useAuth` instances stay in sync: both `token` and `user` are read
746
+ * through `useSyncExternalStore` over the shared client (and a per-client
747
+ * identity store), so a `setToken` from one component re-renders every mounted
748
+ * hook with the freshly-resolved user.
749
+ */
228
750
  declare const useAuth: () => UseAuthResult;
751
+ type Setter<T> = (value: T) => void;
752
+ /**
753
+ * Subscribe to a local-only {@link ClientQueryRef} and re-render when its
754
+ * value changes. Unlike `useQuery`, this never touches the network — the
755
+ * value lives in a reactive store on the `LunoraClient` instance and is shared
756
+ * across every consumer of the same ref.
757
+ *
758
+ * The initial render reads the store synchronously (via
759
+ * `useSyncExternalStore`), so there is never an "undefined flash" — the value
760
+ * is either the one most recently set or `ref.defaultValue`.
761
+ *
762
+ * Returns a `[value, setter]` tuple, matching the `useState` convention.
763
+ * @example
764
+ * ```tsx
765
+ * import { useClientQuery, createClientQuery } from "@lunora/react";
766
+ *
767
+ * const sidebarOpen = createClientQuery("sidebarOpen", true);
768
+ *
769
+ * function Sidebar() {
770
+ * const [open, setOpen] = useClientQuery(sidebarOpen);
771
+ * return <aside data-open={open}>…</aside>;
772
+ * }
773
+ * ```
774
+ */
775
+ declare const useClientQuery: <T extends unknown>(ref: ClientQueryRef<T>) => [T, Setter<T>];
229
776
  /**
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
- */
777
+ * Reactive view of the client's aggregate live-socket status across all shard
778
+ * connections. Re-renders on every transition (`idle` → `connecting` →
779
+ * `connected` → `offline`). Use it to drive a connection indicator so an
780
+ * operator can tell a healthy live channel from a silently-dropped socket.
781
+ */
235
782
  declare const useConnectionStatus: () => ConnectionStatus;
236
- /** A targeting context merged on top of the app's default (`defineFlags({ identify })`). */
237
- type FlagContext = Record<string, unknown>;
238
783
  /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
239
784
  type FlagValue = boolean | number | string | {
240
785
  [key: string]: unknown;
241
786
  } | unknown[] | null;
242
787
  /**
243
- * Subscribe to a single feature flag, live over Lunora's WebSocket.
244
- *
245
- * Returns `defaultValue` until the first evaluation lands, then the server's
246
- * resolved value — re-pushed whenever the provider re-evaluates (e.g. a flag is
247
- * toggled in Cloudflare Flagship). The flag's kind is inferred from
248
- * `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean and
249
- * `useFlag("hero", "control")` a string. `context` supplies a per-call targeting
250
- * context merged on top of the app's default `identify` targeting key.
251
- *
252
- * Evaluation runs through whatever OpenFeature provider the app wired in
253
- * `lunora/flags.ts`; the read never throws — a provider error resolves the
254
- * default (the same fail-open contract as server-side `ctx.flags`).
255
- */
256
- declare const useFlag: <T extends FlagValue>(key: string, defaultValue: T, context?: FlagContext) => T;
257
- /**
258
- * Subscribe to several feature flags at once, live over Lunora's WebSocket.
259
- *
260
- * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
261
- * default, and the result is the same-shaped record with resolved values (the
262
- * defaults until each evaluation lands). A single `context` applies to every
263
- * flag. This is the batched form of {@link useFlag} — one effect manages one
264
- * subscription per key, so it stays rules-of-hooks-safe even as the flag set
265
- * changes between renders.
266
- */
267
- declare const useFlags: <T extends Record<string, FlagValue>>(flags: T, context?: FlagContext) => T;
788
+ * Subscribe to a single feature flag, live over Lunora's WebSocket.
789
+ *
790
+ * Returns `defaultValue` until the first evaluation lands, then the server's
791
+ * resolved value — re-pushed whenever the provider re-evaluates (e.g. a flag is
792
+ * toggled in Cloudflare Flagship). The flag's kind is inferred from
793
+ * `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean and
794
+ * `useFlag("hero", "control")` a string.
795
+ *
796
+ * The reactive channel is public, so the server evaluates every flag under the
797
+ * socket's own verified identity — the targeting key your `defineFlags({
798
+ * identify })` derives — and accepts no client-supplied targeting context. For
799
+ * evaluation under a context you compute, call `ctx.flags.*` inside a query,
800
+ * mutation, or action and return the resolved value.
801
+ *
802
+ * Evaluation runs through whatever OpenFeature provider the app wired in
803
+ * `lunora/flags.ts`; the read never throws — a provider error resolves the
804
+ * default (the same fail-open contract as server-side `ctx.flags`).
805
+ */
806
+ declare const useFlag: <T extends FlagValue>(key: string, defaultValue: T) => T;
807
+ /**
808
+ * Subscribe to several feature flags at once, live over Lunora's WebSocket.
809
+ *
810
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
811
+ * default, and the result is the same-shaped record with resolved values (the
812
+ * defaults until each evaluation lands). This is the batched form of
813
+ * {@link useFlag} — one effect manages one subscription per key, so it stays
814
+ * rules-of-hooks-safe even as the flag set changes between renders. Like
815
+ * {@link useFlag} it evaluates under the socket's server-verified identity only.
816
+ */
817
+ declare const useFlags: <T extends Record<string, FlagValue>>(flags: T) => T;
818
+ /** The lifecycle of a stream the hook is observing. */
819
+ type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
820
+ /**
821
+ * Result shape returned by {@link useHttpStream}.
822
+ * @experimental Part of the HTTP-SSE stream surface.
823
+ */
824
+ interface UseHttpStreamResult<T> {
825
+ /** Force-cancel the stream (aborts the fetch) and resolve the iterator. Safe to call multiple times. */
826
+ cancel: () => void;
827
+ /** Chunks the server has pushed so far, in arrival order. */
828
+ chunks: ReadonlyArray<T>;
829
+ error: Error | undefined;
830
+ status: UseStreamStatus;
831
+ }
832
+ /**
833
+ * Options accepted by {@link useHttpStream}.
834
+ * @experimental Part of the HTTP-SSE stream surface.
835
+ */
836
+ interface UseHttpStreamOptions {
837
+ /** Forwarded to `client.httpStream()` — caps the in-flight chunk buffer. */
838
+ maxBuffer?: number;
839
+ }
840
+ /**
841
+ * Consume an **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`) via
842
+ * `client.httpStream`. Distinct from `useStream`, which consumes the WS
843
+ * procedure stream (`kind: "stream"`). Returns the chunks received so far plus
844
+ * a lifecycle status and a cancel function. Changing the route or the
845
+ * serialized `args` resets the stream — the previous fetch is aborted (the
846
+ * server sees `request.signal`) and a fresh one opens with empty `chunks`.
847
+ * Unmount also aborts.
848
+ *
849
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
850
+ * (mirrors `useQuery` / `useStream`).
851
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
852
+ */
853
+ declare const useHttpStream: <Ref extends HttpStreamRef>(route: Ref, args: "skip" | HttpStreamArgsOf<Ref>, options?: UseHttpStreamOptions) => UseHttpStreamResult<HttpStreamChunkOf<Ref>>;
268
854
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
269
855
  type PaginatedArgs<F> = Omit<ArgsOf<F>, "paginationOpts">;
270
856
  /** The element type of the `page` array a paginated query returns. */
@@ -272,44 +858,48 @@ type PageItemOf<F> = ReturnOf<F> extends {
272
858
  page: (infer T)[];
273
859
  } ? T : unknown;
274
860
  /**
275
- * Subscribe to a reactively-paginated query and grow the feed page by page.
276
- *
277
- * The query function must accept a `paginationOpts: { numItems, cursor,
278
- * endCursor }` arg and return a `PaginationResult` (the shape
279
- * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
280
- * stable boundary cursors: each loaded page is a live subscription over a
281
- * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
282
- * Because boundaries are shared stable cursors, inserting or deleting a row in
283
- * the middle of the list grows/shrinks the affected page in place without
284
- * duplicating or skipping rows across page boundaries — the bug the legacy
285
- * "first N after the previous page's last row" model suffered under live edits.
286
- *
287
- * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
288
- * it is a no-op unless `status === "CanLoadMore"`. Background split/join
289
- * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
290
- * `use-paginated-core.ts`).
291
- *
292
- * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
293
- * feed to its first page. The public return shape (`results` / `status` /
294
- * `loadMore`) is unchanged from the legacy keyset implementation.
295
- */
861
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
862
+ *
863
+ * Pass `onError` (and read `error`) to see a page failure: without it the hook
864
+ * only reports `status`, and a first page that fails reads as an eternal
865
+ * `isLoading`.
866
+ *
867
+ * The query function must accept a `paginationOpts: { numItems, cursor,
868
+ * endCursor }` arg and return a `PaginationResult` (the shape
869
+ * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
870
+ * stable boundary cursors: each loaded page is a live subscription over a
871
+ * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
872
+ * Because boundaries are shared stable cursors, inserting or deleting a row in
873
+ * the middle of the list grows/shrinks the affected page in place without
874
+ * duplicating or skipping rows across page boundaries — the bug the legacy
875
+ * "first N after the previous page's last row" model suffered under live edits.
876
+ *
877
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
878
+ * it is a no-op unless `status === "CanLoadMore"`. Background split/join
879
+ * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
880
+ * `use-paginated-core.ts`).
881
+ *
882
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
883
+ * feed to its first page. The public return shape (`results` / `status` /
884
+ * `loadMore`) is unchanged from the legacy keyset implementation.
885
+ */
296
886
  declare const usePaginatedQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UsePaginatedQueryOptions) => UsePaginatedQueryResult<PageItemOf<F>>;
297
887
  /**
298
- * Subscribe to a reactively-paginated query and expose its pages discretely.
299
- *
300
- * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
301
- * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
302
- * inserted or deleted mid-list grows/shrinks the affected page without
303
- * duplicating or skipping rows across boundaries — but keeps each page as its
304
- * own inner array rather than flattening them, and adds the
305
- * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
306
- * shape. `fetchNextPage` appends the next page off the open-ended tail's
307
- * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
308
- *
309
- * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
310
- * feed to its first page. The public return shape is unchanged from the legacy
311
- * keyset implementation.
312
- */
888
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
889
+ *
890
+ * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
891
+ * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
892
+ * inserted or deleted mid-list grows/shrinks the affected page without
893
+ * duplicating or skipping rows across boundaries — but keeps each page as its
894
+ * own inner array rather than flattening them, and adds the
895
+ * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
896
+ * shape. `fetchNextPage` appends the next page off the open-ended tail's
897
+ * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
898
+ *
899
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
900
+ * feed to its first page. The public return shape is unchanged from the legacy
901
+ * keyset implementation.
902
+ */
313
903
  declare const useInfiniteQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UseInfiniteQueryOptions) => UseInfiniteQueryResult<PageItemOf<F>>;
314
904
  type CallOptions<F extends FunctionReference> = UseMutationCallOptions<unknown, unknown, ArgsOf<F>>;
315
905
  interface MutationHook<F extends FunctionReference> {
@@ -325,34 +915,34 @@ interface MutationHook<F extends FunctionReference> {
325
915
  /** Clear the latest `data`/`error` back to idle. */
326
916
  reset: () => void;
327
917
  /**
328
- * Bind a Convex-parity multi-query optimistic update to this mutation.
329
- * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
330
- * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
331
- * is supplied in the call options, which overrides the bound one.
332
- */
918
+ * Bind a Convex-parity multi-query optimistic update to this mutation.
919
+ * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
920
+ * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
921
+ * is supplied in the call options, which overrides the bound one.
922
+ */
333
923
  withOptimisticUpdate: (update: OptimisticUpdate<ArgsOf<F>>) => MutationHook<F>;
334
924
  }
335
925
  /**
336
- * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
337
- * given mutation reference. Prefer destructuring at the call site so the React
338
- * linter can track dependencies on each field independently.
339
- *
340
- * Built on TanStack Query's mutation cache (the same cache the query hooks use),
341
- * so it composes with Query Devtools and exposes the latest call's `data`/`error`
342
- * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
343
- * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
344
- *
345
- * `pending` is ref-counted across overlapping invocations of THIS hook instance
346
- * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
347
- * `false` only once every concurrent call has settled — and a sibling component
348
- * mutating the same function never affects it (TanStack's own `isPending` tracks
349
- * just the latest invocation).
350
- *
351
- * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
352
- * call options pass straight through to `client.mutation`, which applies and
353
- * rolls them back against the Lunora subscription cache (Convex parity) — not
354
- * through TanStack's `onMutate`.
355
- */
926
+ * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
927
+ * given mutation reference. Prefer destructuring at the call site so the React
928
+ * linter can track dependencies on each field independently.
929
+ *
930
+ * Built on TanStack Query's mutation cache (the same cache the query hooks use),
931
+ * so it composes with Query Devtools and exposes the latest call's `data`/`error`
932
+ * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
933
+ * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
934
+ *
935
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance
936
+ * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
937
+ * `false` only once every concurrent call has settled — and a sibling component
938
+ * mutating the same function never affects it (TanStack's own `isPending` tracks
939
+ * just the latest invocation).
940
+ *
941
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
942
+ * call options pass straight through to `client.mutation`, which applies and
943
+ * rolls them back against the Lunora subscription cache (Convex parity) — not
944
+ * through TanStack's `onMutate`.
945
+ */
356
946
  declare const useMutation: <F extends FunctionReference>(function_: F) => MutationHook<F>;
357
947
  interface MutatorHook<TArgs> {
358
948
  /** The latest invocation's error, or `undefined`. */
@@ -367,86 +957,94 @@ interface MutatorHook<TArgs> {
367
957
  reset: () => void;
368
958
  }
369
959
  /**
370
- * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
371
- * custom-mutator handle from `@lunora/db`'s `bindMutators`. The optimistic
372
- * overlay and server-authoritative push are owned by the bound handle (and
373
- * TanStack DB's optimistic-transaction layer rebases pending overlays on every
374
- * sync tick) — this hook only surfaces React state for the in-flight/error
375
- * lifecycle. Reads stay on the existing `useLiveQuery`; no new query hook is
376
- * needed.
377
- *
378
- * `pending` is ref-counted across overlapping invocations of THIS hook instance,
379
- * so it clears only once every concurrent call has settled.
380
- */
960
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
961
+ * custom-mutator handle from `@lunora/db`'s `bindMutators`. The optimistic
962
+ * overlay and server-authoritative push are owned by the bound handle (and
963
+ * TanStack DB's optimistic-transaction layer rebases pending overlays on every
964
+ * sync tick) — this hook only surfaces React state for the in-flight/error
965
+ * lifecycle. Reads stay on the existing `useLiveQuery`; no new query hook is
966
+ * needed.
967
+ *
968
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance,
969
+ * so it clears only once every concurrent call has settled.
970
+ */
381
971
  declare const useMutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHook<TArgs>;
382
972
  /**
383
- * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
384
- * during SSR, then keep it live.
385
- *
386
- * The first render returns the preloaded value (TanStack's `initialData`),
387
- * so the server markup and the initial client markup match — no hydration
388
- * mismatch, no loading flash. After mount, a WS subscription attaches so
389
- * later server pushes update the value just like `useQuery`.
390
- *
391
- * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
392
- * full dehydrate/hydrate dance because the consumer hands us the resolved
393
- * value directly. Apps that want to share a pre-populated QueryClient across
394
- * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
395
- * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
396
- */
397
- declare const usePreloadedQuery: <T>(preloaded: Preloaded<T>) => T;
398
- /**
399
- * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
400
- * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
401
- * attaches a live WS subscription on mount. It is a thin alias of
402
- * {@link usePreloadedQuery} so the React adapter exposes the same
403
- * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
404
- * while existing callers of `usePreloadedQuery` keep working unchanged.
405
- *
406
- * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
407
- * call it like a hook — at the top level of a component, unconditionally.
408
- */
409
- declare const hydratePreloaded: <T>(preloaded: Preloaded<T>) => T;
410
- /**
411
- * `usePresence` — collaborative-awareness hook, the client half of the
412
- * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
413
- * parity).
414
- *
415
- * It drives the two presence functions the server component ships:
416
- *
417
- * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
418
- * whenever the tab becomes visible, to upsert the caller's presence row and
419
- * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
420
- * carries the latest `data` from a ref, so `setData` takes effect on the next
421
- * tick without re-subscribing or resetting the timer.
422
- * - **listPresent** (a query): subscribed to over the live-query WS, so the
423
- * present-list updates reactively. Because the server patches a single row per
424
- * heartbeat, the client's **per-row subscription delta merge** applies just that
425
- * row to the cached list instead of re-sending every member — the list stays
426
- * cheap even with many participants heart-beating.
427
- *
428
- * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
429
- * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
430
- * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
431
- * the hook needs no client-side reaping.
432
- *
433
- * The two `FunctionReference`s come from your generated `api` (e.g.
434
- * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
435
- * stays decoupled from any specific app schema.
436
- */
437
- /**
438
- * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
439
- * `definePresence().functions.heartbeat` registers).
440
- */
973
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
974
+ * during SSR, then keep it live.
975
+ *
976
+ * The first render returns the preloaded value (TanStack's `initialData`),
977
+ * so the server markup and the initial client markup match — no hydration
978
+ * mismatch, no loading flash. After mount, a WS subscription attaches so
979
+ * later server pushes update the value just like `useQuery`.
980
+ *
981
+ * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
982
+ * full dehydrate/hydrate dance because the consumer hands us the resolved
983
+ * value directly. Apps that want to share a pre-populated QueryClient across
984
+ * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
985
+ * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
986
+ *
987
+ * Pass `onError` to surface a subscription-scoped error the server pushes (a
988
+ * session expiry, an RLS denial). Without it such an error is dropped and the
989
+ * hook keeps rendering the SSR snapshot as if it were live.
990
+ */
991
+ declare const usePreloadedQuery: <T>(preloaded: Preloaded<T>, options?: {
992
+ onError?: SubscriptionErrorCallback;
993
+ }) => T;
994
+ /**
995
+ * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
996
+ * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
997
+ * attaches a live WS subscription on mount. It is a thin alias of
998
+ * {@link usePreloadedQuery} so the React adapter exposes the same
999
+ * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
1000
+ * while existing callers of `usePreloadedQuery` keep working unchanged.
1001
+ *
1002
+ * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
1003
+ * call it like a hook — at the top level of a component, unconditionally.
1004
+ */
1005
+ declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, options?: {
1006
+ onError?: SubscriptionErrorCallback;
1007
+ }) => T;
1008
+ /**
1009
+ * `usePresence` — collaborative-awareness hook, the client half of the
1010
+ * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
1011
+ * parity).
1012
+ *
1013
+ * It drives the two presence functions the server component ships:
1014
+ *
1015
+ * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
1016
+ * whenever the tab becomes visible, to upsert the caller's presence row and
1017
+ * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
1018
+ * carries the latest `data` from a ref, so `setData` takes effect on the next
1019
+ * tick without re-subscribing or resetting the timer.
1020
+ * - **listPresent** (a query): subscribed to over the live-query WS, so the
1021
+ * present-list updates reactively. Because the server patches a single row per
1022
+ * heartbeat, the client's **per-row subscription delta merge** applies just that
1023
+ * row to the cached list instead of re-sending every member — the list stays
1024
+ * cheap even with many participants heart-beating.
1025
+ *
1026
+ * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
1027
+ * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
1028
+ * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
1029
+ * the hook needs no client-side reaping.
1030
+ *
1031
+ * The two `FunctionReference`s come from your generated `api` (e.g.
1032
+ * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
1033
+ * stays decoupled from any specific app schema.
1034
+ */
1035
+ /**
1036
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
1037
+ * `definePresence().functions.heartbeat` registers).
1038
+ */
441
1039
  type HeartbeatReference = FunctionReference<"mutation", {
442
1040
  data?: Record<string, unknown>;
443
1041
  roomId: string;
444
1042
  sessionId: string;
445
1043
  }>;
446
1044
  /**
447
- * A listPresent query reference: takes `{ roomId }` and returns the array of
448
- * present members.
449
- */
1045
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
1046
+ * present members.
1047
+ */
450
1048
  type ListPresentReference = FunctionReference<"query", {
451
1049
  roomId: string;
452
1050
  }>;
@@ -460,14 +1058,22 @@ interface UsePresenceOptions<H extends HeartbeatReference, L extends ListPresent
460
1058
  /** The `api.*` reference for the presence listPresent query. */
461
1059
  listPresent: L;
462
1060
  /**
463
- * Stable id for this presence row. Defaults to a fresh per-mount id (one row
464
- * per tab). Pass a user/connection id to control deduping.
465
- */
1061
+ * Called when the `listPresent` subscription reports an error (a session
1062
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
1063
+ * failure is invisible and `present` freezes at its last value.
1064
+ */
1065
+ onError?: SubscriptionErrorCallback;
1066
+ /**
1067
+ * Stable id for this presence row. Defaults to a fresh per-mount id (one row
1068
+ * per tab). Pass a user/connection id to control deduping.
1069
+ */
466
1070
  sessionId?: string;
467
1071
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
468
1072
  shardKey?: string;
469
1073
  }
470
1074
  interface UsePresenceResult<L extends ListPresentReference> {
1075
+ /** The `listPresent` subscription's last error, or `undefined`. */
1076
+ error: SubscriptionError | undefined;
471
1077
  /** The present members for the room, as `listPresent` returns them. `undefined` until the first push. */
472
1078
  present: ReturnOf<L> | undefined;
473
1079
  /** This mount's session id (generated when not supplied). */
@@ -477,25 +1083,35 @@ interface UsePresenceResult<L extends ListPresentReference> {
477
1083
  }
478
1084
  declare const usePresence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: UsePresenceOptions<H, L>) => UsePresenceResult<L>;
479
1085
  /**
480
- * Subscribe to a server query.
481
- *
482
- * Returns `undefined` until the first response lands. Pass `"skip"` for
483
- * `args` to short-circuit the query (no network call, no subscription).
484
- *
485
- * Internally this routes through TanStack Query: the queryKey is
486
- * `["lunora", fn.__lunoraRef, args, shardKey]` (TanStack hashes structurally
487
- * so an args object built in a different key order still dedupes). The
488
- * subscription registry shares a single WS subscription across every consumer
489
- * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
490
- */
1086
+ * Subscribe to a server query.
1087
+ *
1088
+ * Returns `undefined` until the first response lands. Pass `"skip"` for
1089
+ * `args` to short-circuit the query (no network call, no subscription).
1090
+ *
1091
+ * When the `LunoraClient` was created with `hydrateOnStart: true` and a
1092
+ * `queryCache` adapter, the first **enabled** render waits for the durable
1093
+ * read cache to finish loading. If a cached value exists for this query it
1094
+ * is fed as `initialData` so the user sees it immediately — no undefined
1095
+ * flash before the socket round-trip.
1096
+ *
1097
+ * Internally this routes through TanStack Query: the queryKey is
1098
+ * `["lunora", fn.__lunoraRef, args, shardKey]` (TanStack hashes structurally
1099
+ * so an args object built in a different key order still dedupes). The
1100
+ * subscription registry shares a single WS subscription across every consumer
1101
+ * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
1102
+ *
1103
+ * Pass `onError` to surface a subscription-scoped error the server pushes (an RLS
1104
+ * denial, a query that starts failing server-side). Without it such an error is
1105
+ * dropped and the returned value just freezes at its last good result.
1106
+ */
491
1107
  declare const useQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => ReturnOf<F> | undefined;
492
1108
  interface UseRateLimitOptions {
493
1109
  /** Clock injection for tests. Defaults to `Date.now`. */
494
1110
  now?: () => number;
495
1111
  /**
496
- * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
497
- * down and `disabled` flips back automatically. Defaults to `1000`.
498
- */
1112
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
1113
+ * down and `disabled` flips back automatically. Defaults to `1000`.
1114
+ */
499
1115
  tickMs?: number;
500
1116
  }
501
1117
  interface UseRateLimitResult {
@@ -513,17 +1129,15 @@ interface UseRateLimitResult {
513
1129
  retryAfter: number;
514
1130
  }
515
1131
  /**
516
- * Client-side mirror of a rate limit for instant UX — disable a button or show
517
- * a countdown without a round-trip. It runs the same token-bucket / fixed-window
518
- * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
519
- * authoritative check; the server remains the source of truth.
520
- *
521
- * `config` is read on every render; pass a stable reference (module constant or
522
- * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
523
- */
1132
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
1133
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
1134
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
1135
+ * authoritative check; the server remains the source of truth.
1136
+ *
1137
+ * `config` is read on every render; pass a stable reference (module constant or
1138
+ * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
1139
+ */
524
1140
  declare const useRateLimit: (config: RateLimitConfig, options?: UseRateLimitOptions) => UseRateLimitResult;
525
- /** The lifecycle of a stream the hook is observing. */
526
- type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
527
1141
  interface UseStreamResult<T> {
528
1142
  /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
529
1143
  cancel: () => void;
@@ -533,24 +1147,182 @@ interface UseStreamResult<T> {
533
1147
  status: UseStreamStatus;
534
1148
  }
535
1149
  interface UseStreamOptions {
1150
+ /**
1151
+ * Opt into resume-on-reconnect for a stream the server declared `durable`.
1152
+ * The hook keeps the chunks it already has and the socket re-attaches to the
1153
+ * same run, so a dropped connection mid-generation continues instead of
1154
+ * surfacing `STREAM_DISCONNECTED`. Has no effect on an ephemeral stream.
1155
+ */
1156
+ durable?: boolean;
536
1157
  /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
537
1158
  maxBuffer?: number;
538
1159
  shardKey?: string;
539
1160
  }
540
1161
  /**
541
- * Subscribe to a streaming query. Returns the chunks pushed so far plus a
542
- * lifecycle status and a cancel function. Changing `fn` or the serialized
543
- * `args` resets the stream — the previous iterator is cancelled and a fresh
544
- * one opens with empty `chunks`.
545
- *
546
- * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
547
- * (mirrors `useQuery` / `useSubscription`).
548
- */
1162
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
1163
+ * lifecycle status and a cancel function. Changing `fn` or the serialized
1164
+ * `args` resets the stream — the previous iterator is cancelled and a fresh
1165
+ * one opens with empty `chunks`.
1166
+ *
1167
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
1168
+ * (mirrors `useQuery` / `useSubscription`).
1169
+ */
549
1170
  declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: "skip" | ArgsOf<F>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
550
1171
  /**
551
- * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
552
- * hook does not issue an initial HTTP fetch — it only delivers values that
553
- * the server pushes over the WS.
554
- */
1172
+ * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
1173
+ * hook does not issue an initial HTTP fetch — it only delivers values that
1174
+ * the server pushes over the WS.
1175
+ *
1176
+ * A server-pushed error lands on `error` as a `LunoraError` carrying the
1177
+ * server's `code` (a bare `Error` only when the server sent no code), so
1178
+ * consumers can branch on the error kind; `onError` receives the raw
1179
+ * `SubscriptionError` in addition.
1180
+ */
555
1181
  declare const useSubscription: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => UseSubscriptionResult<ReturnOf<F>>;
556
- export { AuthLoading, type AuthState, Authenticated, CheckoutButton, type CheckoutButtonProps, CustomerPortalButton, type CustomerPortalButtonProps, type FlagContext, type FlagValue, type HeartbeatReference, type ListPresentReference, LunoraProvider, type LunoraProviderProps, type MutationHook, type MutatorHook, type PageItemOf, type PaginatedArgs, type RedirectTarget, type RedirectTrigger, type Subscription, Unauthenticated, type UseAuthResult, type UseCheckoutResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationCallOptions, type UsePaginatedQueryOptions, type UsePaginatedQueryResult, type UsePresenceOptions, type UsePresenceResult, type UseQueryOptions, type UseRateLimitOptions, type UseRateLimitResult, type UseStreamOptions, type UseStreamResult, type UseStreamStatus, type UseSubscriptionResult, hydratePreloaded, useAuth, useAuthState, useCheckout, useConnectionStatus, useFlag, useFlags, useInfiniteQuery, useLunora, useMutation, useMutator, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription };
1182
+ /**
1183
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
1184
+ * capture and speaker playback implementations injected into the hook via its
1185
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
1186
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
1187
+ * hook's transport + React-state logic and remains mockable in a non-browser
1188
+ * test env.
1189
+ */
1190
+ /**
1191
+ * The negotiated audio format the voice DO streams back. Mirrors
1192
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1193
+ * imported) so this React package never pulls in the server-only `@lunora/agent`
1194
+ * module graph.
1195
+ */
1196
+ type VoiceAudioFormat = "mp3" | "wav";
1197
+ /** Captures microphone audio and reports level / turn boundaries back to the hook. */
1198
+ interface VoiceMicrophone {
1199
+ /** Mute/unmute the mic without tearing down the capture graph. */
1200
+ setMuted: (muted: boolean) => void;
1201
+ /** Stop capture and release the media stream + audio graph. */
1202
+ stop: () => void;
1203
+ }
1204
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1205
+ interface VoiceSpeaker {
1206
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1207
+ enqueue: (audio: Uint8Array) => void;
1208
+ /** Drop everything queued and stop the current chunk (barge-in). */
1209
+ interrupt: () => void;
1210
+ /** Release the playback audio context. */
1211
+ stop: () => void;
1212
+ }
1213
+ /** Config passed to a {@link CreateMicrophone} factory. */
1214
+ interface MicrophoneConfig {
1215
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1216
+ interruptChunks: number;
1217
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1218
+ interruptThreshold: number;
1219
+ /** `true` while `status === "speaking"` — gates barge-in detection. */
1220
+ isSpeaking: () => boolean;
1221
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1222
+ onAudio: (pcm: Uint8Array) => void;
1223
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1224
+ onInterrupt: () => void;
1225
+ /** The current input RMS (0–1), for a level meter. */
1226
+ onLevel: (rms: number) => void;
1227
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1228
+ onSilence: () => void;
1229
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1230
+ silenceDurationMs: number;
1231
+ /** RMS below which audio counts as silence. */
1232
+ silenceThreshold: number;
1233
+ }
1234
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1235
+ type CreateSpeaker = (config: {
1236
+ audioFormat: VoiceAudioFormat;
1237
+ }) => VoiceSpeaker;
1238
+ /**
1239
+ * The `agents.<name>Voice` reference codegen emits for a voice-enabled agent — a
1240
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1241
+ * generated member, so passing `api.agents.<name>Voice` type-checks.
1242
+ */
1243
+ type VoiceReference = FunctionReference<"stream", {
1244
+ threadKey: string;
1245
+ }, Record<string, unknown>>;
1246
+ /** The lifecycle of a voice call, mirrored to the UI. */
1247
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1248
+ /** A minimal structural subset of the DOM `WebSocket` the hook drives. */
1249
+ interface VoiceSocket {
1250
+ binaryType: string;
1251
+ close: () => void;
1252
+ onclose: ((event: unknown) => void) | null;
1253
+ onerror: ((event: unknown) => void) | null;
1254
+ onmessage: ((event: {
1255
+ data: unknown;
1256
+ }) => void) | null;
1257
+ onopen: ((event: unknown) => void) | null;
1258
+ readonly readyState: number;
1259
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1260
+ }
1261
+ type CreateSocket = (url: string) => VoiceSocket;
1262
+ interface UseVoiceAgentOptions {
1263
+ /**
1264
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1265
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1266
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1267
+ */
1268
+ createMicrophone?: CreateMicrophone;
1269
+ /**
1270
+ * Advanced/test seam: open the transport. Defaults to the WebSocket
1271
+ * implementation the client was built with (`client.getWebSocketImpl()`),
1272
+ * NOT a raw `globalThis.WebSocket`.
1273
+ */
1274
+ createSocket?: CreateSocket;
1275
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1276
+ createSpeaker?: CreateSpeaker;
1277
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1278
+ interruptChunks?: number;
1279
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1280
+ interruptThreshold?: number;
1281
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1282
+ silenceDurationMs?: number;
1283
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1284
+ silenceThreshold?: number;
1285
+ /** The thread to converse on — shared with the agent's text turns. */
1286
+ threadKey: string;
1287
+ /** The generated `api.agents.<name>Voice` reference — identifies the voice DO endpoint. */
1288
+ voice: VoiceReference;
1289
+ }
1290
+ interface UseVoiceAgentResult {
1291
+ /** The current input RMS (0–1) — drive a mic level meter. */
1292
+ audioLevel: number;
1293
+ /** `true` once the WS `ready` handshake completed. */
1294
+ connected: boolean;
1295
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1296
+ endCall: () => void;
1297
+ /** The last transport/pipeline error, or `undefined`. */
1298
+ error: Error | undefined;
1299
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1300
+ interimTranscript: string;
1301
+ /** `true` while the mic is muted. */
1302
+ isMuted: boolean;
1303
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1304
+ sendText: (text: string) => void;
1305
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1306
+ startCall: () => Promise<void>;
1307
+ /** The current call lifecycle. */
1308
+ status: VoiceStatus;
1309
+ /** Mute/unmute the microphone. Returns the new muted state. */
1310
+ toggleMute: () => boolean;
1311
+ /** The last finalized user utterance (STT result). */
1312
+ transcript: string;
1313
+ }
1314
+ /**
1315
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1316
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1317
+ * streams the agent's synthesized speech back through the browser's audio output,
1318
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1319
+ * `audioLevel`) to React state. Pass the generated `api.agents.<name>Voice`
1320
+ * reference (never a string), matching `useAgentChat`'s reference-passing style.
1321
+ *
1322
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1323
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1324
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1325
+ * `createSocket`) so the hook is drivable outside a browser.
1326
+ */
1327
+ declare const useVoiceAgent: (options: UseVoiceAgentOptions) => UseVoiceAgentResult;
1328
+ export { type ActionHook, type AdminAuthListResult, type AgentChatMessage, type AgentLiveEvent, type AgentProgressEvent, type AgentThreadRecord, type AgentThreadStatus, type AgentTokenDelta, type AgentToolEvent, AuthLoading, type AuthState, Authenticated, type FlagValue, type HeartbeatReference, type ListPresentReference, LunoraProvider, type LunoraProviderProps, type MutationHook, type MutatorHook, type PageItemOf, type PaginatedArgs, 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 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, useAction, useAgent, useAgentChat, useAgentState, useAgentToolEvents, useAuth, useAuthSessions, useAuthState, useAuthUsers, useClientQuery, useConnectionStatus, useFlag, useFlags, useHttpStream, useImpersonate, useInfiniteQuery, useLunora, useMutation, useMutator, useOrganizations, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription, useVoiceAgent };