@lunora/react 1.0.0-alpha.9 → 1.0.0-alpha.91

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