@lunora/react 1.0.0-alpha.19 → 1.0.0-alpha.190

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 (71) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +25 -18
  3. package/dist/index.d.mts +1221 -358
  4. package/dist/index.d.ts +1221 -358
  5. package/dist/index.mjs +1 -19
  6. package/dist/packem_shared/AuthLoading-BZD1whno.mjs +2 -0
  7. package/dist/packem_shared/LunoraProvider-4XBOJ6Vx.mjs +1 -0
  8. package/dist/packem_shared/hydratePreloaded-Dw5X4aQP.mjs +2 -0
  9. package/dist/packem_shared/lunora-provider-DsXARssD.mjs +2 -0
  10. package/dist/packem_shared/lunoraQueryOptions-BuCFB9h1.mjs +1 -0
  11. package/dist/packem_shared/query-key-QcTqsWNc.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/stream-state-abygFxmy.mjs +1 -0
  15. package/dist/packem_shared/use-paginated-core-BFErPUQG.mjs +2 -0
  16. package/dist/packem_shared/useAction-CfzLxuvQ.mjs +2 -0
  17. package/dist/packem_shared/useAgent-fHMUCenH.mjs +2 -0
  18. package/dist/packem_shared/useAgentChat-BAN74BAJ.mjs +2 -0
  19. package/dist/packem_shared/useAgentState-BNuCb9iH.mjs +2 -0
  20. package/dist/packem_shared/useAgentToolEvents-BC-hiuYS.mjs +2 -0
  21. package/dist/packem_shared/useAuth-BPg3-tum.mjs +2 -0
  22. package/dist/packem_shared/useAuthSessions-DumEKLKj.mjs +2 -0
  23. package/dist/packem_shared/useAuthState-DUqteFyj.mjs +2 -0
  24. package/dist/packem_shared/useClientQuery-CSO7y12f.mjs +2 -0
  25. package/dist/packem_shared/useConnectionStatus-CcEKji7W.mjs +2 -0
  26. package/dist/packem_shared/useFlag-QOEvZAyV.mjs +2 -0
  27. package/dist/packem_shared/useHttpStream-CODrgO1l.mjs +2 -0
  28. package/dist/packem_shared/useInfiniteQuery-Ct_w49zB.mjs +2 -0
  29. package/dist/packem_shared/useMutation-BaDjKEXu.mjs +2 -0
  30. package/dist/packem_shared/useMutator-BtUd-xEA.mjs +2 -0
  31. package/dist/packem_shared/usePaginatedQuery-Dswd-75x.mjs +2 -0
  32. package/dist/packem_shared/usePresence-C-yVPG30.mjs +2 -0
  33. package/dist/packem_shared/useQuery-YIz-Busa.mjs +2 -0
  34. package/dist/packem_shared/useRateLimit-Cckxi8m9.mjs +2 -0
  35. package/dist/packem_shared/useStream-3ejjJfiS.mjs +2 -0
  36. package/dist/packem_shared/useSubscription-CnMN0IUI.mjs +2 -0
  37. package/dist/packem_shared/useVoiceAgent-B6iU4lhc.mjs +2 -0
  38. package/dist/payment.d.mts +103 -0
  39. package/dist/payment.d.ts +103 -0
  40. package/dist/payment.mjs +2 -0
  41. package/dist/server.d.mts +47 -29
  42. package/dist/server.d.ts +47 -29
  43. package/dist/server.mjs +1 -31
  44. package/dist/upload.d.mts +24 -0
  45. package/dist/upload.d.ts +24 -0
  46. package/dist/upload.mjs +2 -0
  47. package/package.json +14 -5
  48. package/dist/packem_shared/AuthLoading-DezUWNB2.mjs +0 -33
  49. package/dist/packem_shared/CheckoutButton-DUite8jJ.mjs +0 -189
  50. package/dist/packem_shared/LunoraProvider-BsuiW4Lk.mjs +0 -81
  51. package/dist/packem_shared/cache-BFlsXmup.mjs +0 -75
  52. package/dist/packem_shared/hydratePreloaded-Dsf9YuII.mjs +0 -54
  53. package/dist/packem_shared/lunoraQueryOptions-C3uwOTMW.mjs +0 -16
  54. package/dist/packem_shared/query-key-BmCbgidV.mjs +0 -13
  55. package/dist/packem_shared/query-options.d-D4okOpO8.d.mts +0 -38
  56. package/dist/packem_shared/query-options.d-D4okOpO8.d.ts +0 -38
  57. package/dist/packem_shared/stable-key-CGp4e2Ux.mjs +0 -38
  58. package/dist/packem_shared/use-paginated-core-CWSzk1J1.mjs +0 -180
  59. package/dist/packem_shared/useAuth-BSutjJaa.mjs +0 -129
  60. package/dist/packem_shared/useAuthState-CyF35qZR.mjs +0 -36
  61. package/dist/packem_shared/useConnectionStatus-PJ7vyCHy.mjs +0 -30
  62. package/dist/packem_shared/useFlag-hhoN_xYA.mjs +0 -224
  63. package/dist/packem_shared/useInfiniteQuery-Dy42_srs.mjs +0 -97
  64. package/dist/packem_shared/useMutation-BeqeIjTr.mjs +0 -67
  65. package/dist/packem_shared/useMutator-IIrLtDiM.mjs +0 -47
  66. package/dist/packem_shared/usePaginatedQuery-Tx-B3mAP.mjs +0 -46
  67. package/dist/packem_shared/usePresence-DC8VIyLB.mjs +0 -108
  68. package/dist/packem_shared/useQuery-_fTR6DCQ.mjs +0 -54
  69. package/dist/packem_shared/useRateLimit-DTEffQEi.mjs +0 -64
  70. package/dist/packem_shared/useStream-DFuryaIC.mjs +0 -125
  71. package/dist/packem_shared/useSubscription-D38Jdyr8.mjs +0 -139
package/dist/index.d.mts CHANGED
@@ -1,174 +1,100 @@
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, type FunctionReference, type LunoraClient, type LunoraErrorCode, type MutatorHandle, type MutatorTransaction, type OptimisticLocalStore, type OptimisticUpdate, type Preloaded, type ReturnOf, type User, getErrorCode, getRetryAfterMs, isConflictError, isForbiddenError, isRateLimitedError, isUnauthorizedError } from '@lunora/client';
2
+ import { LunoraClient, OptimisticUpdate, User, SubscriptionErrorCallback, SubscriptionError, FunctionReference, ArgsOf, ActionCallOptions, ReturnOf, AuthImpersonation, AuthSession, AuthUser, ClientQueryRef, ConnectionStatus, HttpStreamRef, HttpStreamArgsOf, HttpStreamChunkOf, MutatorHandle, Preloaded } from '@lunora/client';
3
+ export { type ArgsOf, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type ClientQueryRef, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamRef, type LunoraClient, type LunoraErrorCode, type MutatorHandle, type MutatorTransaction, type OptimisticLocalStore, type OptimisticUpdate, type Preloaded, type ReturnOf, type SubscriptionError, type SubscriptionErrorCallback, type User, createClientQuery, getErrorCode, getRetryAfterMs, isConflictError, isForbiddenError, isRateLimitedError, isUnauthorizedError } from '@lunora/client';
4
4
  import { QueryClient } from '@tanstack/react-query';
5
- export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-D4okOpO8.mjs";
5
+ export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-CdgGQ9s4.mjs";
6
+ import { AuthStatus } from '@lunora/client/auth';
6
7
  import { PaginationStatus } from '@lunora/client/pagination';
7
8
  export type { PaginationResult, PaginationStatus } from '@lunora/client/pagination';
8
9
  import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
10
+ export { RestrictionError, UploadControl, UploadError, type UploadRestrictions } from '@visulima/storage-client';
11
+ 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
12
  interface AuthGateProps {
10
13
  children: ReactNode;
11
14
  }
12
- /** Renders `children` only once a token is set on the client (after hydration). */
13
- declare const Authenticated: ({
14
- children
15
- }: AuthGateProps) => ReactNode;
16
- /** Renders `children` only when auth has settled and no token is set. */
17
- declare const Unauthenticated: ({
18
- children
19
- }: AuthGateProps) => ReactNode;
20
- /** 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
- */
15
+ /**
16
+ * Renders `children` once authentication has settled in the caller's favour — a
17
+ * credential is held and nothing has contradicted it. Follows the shared
18
+ * `AuthStatus` contract in `@lunora/client/auth`, so an unreachable identity
19
+ * endpoint keeps the gate open (with `useAuth().user` still `null`).
20
+ */
21
+ declare const Authenticated: ({ children }: AuthGateProps) => ReactNode;
22
+ /** Renders `children` only when auth has settled and there is no session. */
23
+ declare const Unauthenticated: ({ children }: AuthGateProps) => ReactNode;
24
+ /** Renders `children` while auth is still settling — before hydration, or while the first identity resolve is in flight. */
25
+ declare const AuthLoading: ({ children }: AuthGateProps) => ReactNode;
26
+ /**
27
+ * Resolved auth-gate state, derived from the shared `AuthStatus` contract in
28
+ * `@lunora/client/auth` — the same mapping Vue, Solid, Svelte and Angular use.
29
+ */
29
30
  interface AuthState {
30
31
  isAuthenticated: boolean;
31
32
  isLoading: boolean;
32
33
  }
33
34
  /**
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
- */
35
+ * Three-state auth status for gating UI.
36
+ *
37
+ * `isLoading` covers the server render and the first hydration render (the
38
+ * identity store's server snapshot is `"loading"`, so the markup agrees and no
39
+ * signed-out UI flashes in) as well as the window where a credential is held and
40
+ * its first identity resolve is still in flight.
41
+ *
42
+ * `isAuthenticated` follows the credential, not the identity record: an
43
+ * unreachable identity endpoint keeps the gate open with `user === null`. A UI
44
+ * that needs to tell that apart reads `useAuth().status`.
45
+ */
42
46
  declare const useAuthState: () => AuthState;
43
47
  interface LunoraProviderProps {
44
48
  children: ReactNode;
45
49
  client: LunoraClient;
46
50
  /**
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
- */
51
+ * Bring-your-own QueryClient. When omitted, the provider creates one with
52
+ * defaults tuned for Lunora's push-driven model: `staleTime: Infinity` (the
53
+ * WS subscription is the only invalidation signal), `retry: 0` (failures
54
+ * route through the offline queue on the client), and `gcTime: 5min` (keep
55
+ * results around for a short return-to-view window).
56
+ *
57
+ * If a parent `<QueryClientProvider>` is already mounted, the provider
58
+ * uses *that* client and does NOT install an inner one (so apps with their
59
+ * own setup don't double-wrap).
60
+ */
57
61
  queryClient?: QueryClient;
58
62
  }
59
63
  /**
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;
64
+ * Provides both the {@link LunoraClient} and a TanStack `QueryClient` to the
65
+ * tree. The detection logic for a parent QueryClientProvider keeps this safe to
66
+ * drop into an app that already runs TanStack Query for its own purposes.
67
+ */
68
+ declare const LunoraProvider: ({ children, client, queryClient }: LunoraProviderProps) => ReactElement;
69
69
  /**
70
- * Read the {@link LunoraClient} from the nearest `&lt;LunoraProvider>`. Kept
71
- * colocated with the provider for back-compat.
72
- */
70
+ * Read the {@link LunoraClient} from the nearest `<LunoraProvider>`. Kept
71
+ * colocated with the provider for back-compat.
72
+ */
73
73
  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
74
  interface UseQueryOptions {
75
+ /**
76
+ * Called when the server pushes a subscription-scoped error (an RLS denial, a
77
+ * query that starts failing server-side). Without a handler such an error has
78
+ * nowhere to go and the hook's value simply freezes at its last good result.
79
+ */
80
+ onError?: SubscriptionErrorCallback;
163
81
  shardKey?: string;
164
82
  }
165
83
  interface UseMutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
84
+ /**
85
+ * Single-query shortcut forwarded to `client.mutation`: the transform is
86
+ * layered onto the subscription registered under **this write's own**
87
+ * `(reference, args, shardKey)` and nothing else. A `messages:send` mutation
88
+ * and a `messages:list` query share neither, so for that shape — nearly every
89
+ * shape — reach for {@link UseMutationCallOptions.optimisticUpdate}, whose
90
+ * store names the query it patches.
91
+ */
166
92
  optimistic?: (current: TCurrent | undefined) => TValue;
167
93
  /**
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
- */
94
+ * Convex-parity multi-query optimistic update forwarded to
95
+ * `client.mutation`. Patches many subscribed queries at once via an
96
+ * `OptimisticLocalStore`, rolled back atomically on failure.
97
+ */
172
98
  optimisticUpdate?: OptimisticUpdate<TArgs>;
173
99
  shardKey?: string;
174
100
  }
@@ -179,9 +105,19 @@ interface UseSubscriptionResult<T> {
179
105
  interface UsePaginatedQueryOptions {
180
106
  /** Page size for the first page (and the default for `loadMore`). */
181
107
  initialNumItems: number;
108
+ /** Called when a page subscription (or its initial fetch) fails; also surfaced on `error`. */
109
+ onError?: SubscriptionErrorCallback;
182
110
  shardKey?: string;
183
111
  }
184
112
  interface UsePaginatedQueryResult<T> {
113
+ /**
114
+ * The last page failure, or `undefined`. A tail page that fails before its
115
+ * first frame is dropped so `status` returns to `"CanLoadMore"` and
116
+ * `loadMore` can retry it; the first page has nothing to fall back to and
117
+ * stays `"LoadingFirstPage"` with this set. Cleared by the next successful
118
+ * frame, by `loadMore`, or by an args change.
119
+ */
120
+ error: SubscriptionError | undefined;
185
121
  /** `true` while the first page or a `loadMore` page is in flight. */
186
122
  isLoading: boolean;
187
123
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
@@ -193,9 +129,13 @@ interface UsePaginatedQueryResult<T> {
193
129
  interface UseInfiniteQueryOptions {
194
130
  /** Page size for the first page (and the default for `fetchNextPage`). */
195
131
  initialNumItems: number;
132
+ /** Called when a page subscription (or its initial fetch) fails; also surfaced on `error`. */
133
+ onError?: SubscriptionErrorCallback;
196
134
  shardKey?: string;
197
135
  }
198
136
  interface UseInfiniteQueryResult<T> {
137
+ /** The last page failure, or `undefined` — see `UsePaginatedQueryResult.error`. */
138
+ error: SubscriptionError | undefined;
199
139
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
200
140
  fetchNextPage: (numberItems?: number) => void;
201
141
  /** `true` when the loaded tail reports it can load another page. */
@@ -210,61 +150,756 @@ interface UseInfiniteQueryResult<T> {
210
150
  }
211
151
  interface UseAuthResult {
212
152
  setToken: (token: string | null) => void;
153
+ /**
154
+ * The resolved auth state. Branch on this, not on `user === null` — see the
155
+ * contract in `@lunora/client/auth`; `user` is `null` both when signed out
156
+ * and when a held credential's identity could not be resolved.
157
+ */
158
+ status: AuthStatus;
213
159
  token: string | null;
214
160
  user: User | null;
215
161
  }
162
+ interface ActionHook<F extends FunctionReference> {
163
+ /**
164
+ * Invoke the action. Awaitable, and rejects on failure — the same contract
165
+ * as `useMutation`'s `mutate`.
166
+ */
167
+ call: (args: ArgsOf<F>, options?: ActionCallOptions) => Promise<ReturnOf<F>>;
168
+ /** The latest invocation's resolved value, or `undefined` before the first success. */
169
+ data: ReturnOf<F> | undefined;
170
+ /** The latest invocation's error, or `undefined`. */
171
+ error: Error | undefined;
172
+ /** `true` while ANY invocation from this hook is in flight (ref-counted, so overlapping calls compose). */
173
+ pending: boolean;
174
+ /** Clear the latest `data`/`error` back to idle. */
175
+ reset: () => void;
176
+ }
177
+ /**
178
+ * Returns `{ call, pending, data, error, reset }` for the given action reference.
179
+ * Prefer destructuring at the call site so the React linter can track
180
+ * dependencies on each field independently.
181
+ *
182
+ * Actions were the one procedure kind with no hook: `useQuery` and `useMutation`
183
+ * shipped, so every app that called an action reached for `useLunora()` and
184
+ * re-derived the same pending/error wrapper by hand. This is that wrapper, once.
185
+ *
186
+ * The request state machine is the shared `createCallRunner` from
187
+ * `@lunora/client` — the same one Vue, Solid and Svelte bind to their own
188
+ * primitives — so `pending`, error normalization and latest-invocation ordering
189
+ * behave identically in every adapter. Only the `useState` cells are React's.
190
+ * TanStack's mutation cache still carries the call so it shows up in Query
191
+ * Devtools alongside `useQuery`/`useMutation`.
192
+ *
193
+ * **Lifecycle contract** (identical across the adapters): `data` and `error`
194
+ * both track the LATEST invocation, not the last to settle — a double-click
195
+ * whose first call resolves after the second cannot overwrite the second's
196
+ * outcome. A success clears `error`; a failure leaves the previous `data` in
197
+ * place, so a transient error does not blank the view. `reset()` clears both,
198
+ * but does NOT cancel an in-flight call, whose result still lands.
199
+ *
200
+ * **Why the two TanStack defaults are overridden.** `networkMode` is `"always"`
201
+ * because the default `"online"` pauses the retryer *after* the call is already
202
+ * marked pending: offline, the promise would never settle, the spinner would
203
+ * stick, and the action would silently fire minutes later on reconnect. `retry`
204
+ * is pinned to `0` — not inherited from an app-supplied QueryClient — because
205
+ * `client.action` sends no idempotency key, so a retry after a 502 on an action
206
+ * that already ran server-side would run it a second time. `useMutation` pins
207
+ * both the same way, for a different reason: `client.mutation` queues an
208
+ * offline write itself, and a paused call would never reach that queue (it
209
+ * waits for the network itself only when the client cannot queue). An action
210
+ * has no queue at all, so offline it fails fast.
211
+ *
212
+ * **What it deliberately does not carry.** There is no `optimistic` /
213
+ * `optimisticUpdate` and no `withOptimisticUpdate`, which `useMutation` has. An
214
+ * optimistic update patches the subscription cache on the assumption the write
215
+ * will land; an action is not a write — it runs in the Worker, may call a third
216
+ * party, and has no declared effect on any query. Offering the option would
217
+ * imply a rollback guarantee nothing can honour.
218
+ *
219
+ * ```tsx
220
+ * const { call: runCommand, pending } = useAction(api.commands.run);
221
+ *
222
+ * await runCommand({ command: "lunora", args: ["verify"] });
223
+ * ```
224
+ *
225
+ * Not callable: `const run = useAction(api.x.y); run({ … })` is a `TS2349`.
226
+ * Destructure the invoker — `const { call: run } = useAction(api.x.y)`.
227
+ */
228
+ declare const useAction: <F extends FunctionReference>(function_: F) => ActionHook<F>;
229
+ /** The shape every list hook in this file returns. */
230
+ interface AdminAuthListResult<T> {
231
+ /** Rows loaded so far (the full current window, not just the latest page). `undefined` before the first response. */
232
+ readonly data: ReadonlyArray<T> | undefined;
233
+ /** The read error, or `undefined`. */
234
+ readonly error: Error | undefined;
235
+ /**
236
+ * `true` when the server reports more rows exist beyond the current window
237
+ * (`total > data.length`). `false` before the first response resolves.
238
+ */
239
+ readonly hasMore: boolean;
240
+ /** `true` only before the first response has resolved (matches TanStack's `isLoading`, not `isFetching`). */
241
+ readonly loading: boolean;
242
+ /**
243
+ * Grow the requested window by one page and re-fetch. A no-op while
244
+ * `hasMore` is `false`. This is a growing-window re-fetch (re-request
245
+ * `{ limit }` from the top), not a page-accumulator — `AuthPage` is
246
+ * offset/limit-based, not cursor-based, and there is no live delta stream
247
+ * to keep page boundaries stable against (unlike
248
+ * `@lunora/react`'s `usePaginatedQuery`). See the design doc for the
249
+ * trade-off.
250
+ */
251
+ readonly loadMore: () => void;
252
+ /** Re-run the read — e.g. after a caller performs a mutation via a plain `client.*` call (mirrors Studio's `onDone={refetchOrgs}` pattern). */
253
+ readonly refetch: () => void;
254
+ /** `AuthPage.total` — the server-reported row count across the whole collection, not just the current window. `undefined` before the first response. */
255
+ readonly total: number | undefined;
256
+ }
257
+ /** Options shared by every `useAuthUsers`-style hook. */
258
+ interface AdminAuthQueryOptions {
259
+ /** Gate the read (rules-of-hooks safe). Defaults to `true`. */
260
+ enabled?: boolean;
261
+ /** Page size for the first read; `loadMore` grows the window by this amount. Defaults to 50. */
262
+ pageSize?: number;
263
+ }
264
+ /** Options for {@link useAuthUsers}. */
265
+ interface UseAuthUsersOptions extends AdminAuthQueryOptions {
266
+ filterField?: string;
267
+ filterValue?: string;
268
+ search?: string;
269
+ searchField?: string;
270
+ sortBy?: string;
271
+ sortDirection?: "asc" | "desc";
272
+ }
273
+ /**
274
+ * List authenticated users, paged and optionally searched/filtered/sorted.
275
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` HTTP endpoint via
276
+ * `client.listAuthUsers` (never the WS/live transport) — the worker must be
277
+ * built with an `authAdmin` and `adminToken`.
278
+ *
279
+ * Mirrors `packages/studio/src/features/auth/users-panel.tsx`'s
280
+ * `useClientQuery(["lunora-auth-users", …], () => client.listAuthUsers(…))`
281
+ * read, minus the studio-specific polling (`useAutoRefresh`) — an app using
282
+ * this hook decides its own refresh cadence by calling `refetch()`.
283
+ */
284
+ declare const useAuthUsers: (options?: UseAuthUsersOptions) => AdminAuthListResult<AuthUser>;
285
+ /** Options for {@link useOrganizations}. */
286
+ type UseOrganizationsOptions = AdminAuthQueryOptions;
287
+ /**
288
+ * List organizations (requires the better-auth `organization` plugin).
289
+ * Hits `client.listAuthOrganizations` — an HTTP-only admin-gated read, same
290
+ * transport note as {@link useAuthUsers}.
291
+ *
292
+ * Mirrors `organizations-panel.tsx`'s
293
+ * `useClientQuery(["lunora-auth-orgs"], () => client.listAuthOrganizations({ limit: 100 }))`.
294
+ * Mutations (`client.createAuthOrganization`, `client.deleteAuthOrganization`,
295
+ * …) stay plain `client.*` calls; call this hook's `refetch()` afterward —
296
+ * see the design doc's "mutation ergonomics" section for why no hidden
297
+ * invalidation-on-mutate is wired in.
298
+ */
299
+ declare const useOrganizations: (options?: UseOrganizationsOptions) => AdminAuthListResult<Record<string, unknown>>;
300
+ /** Options for {@link useSignUpInvitations}. */
301
+ type UseSignUpInvitationsOptions = AdminAuthQueryOptions;
302
+ /**
303
+ * List sign-up invitations (requires the `inviteOnly` plugin). Hits
304
+ * `client.listAuthSignUpInvitations` — an HTTP-only admin-gated read, same
305
+ * transport note as {@link useAuthUsers}.
306
+ *
307
+ * Rows come back unfiltered and newest-first; a row is pending when `acceptedAt`
308
+ * is null and `expiresAt` is in the future. Mutations
309
+ * (`client.createAuthSignUpInvitation`, `client.revokeAuthSignUpInvitation`)
310
+ * stay plain `client.*` calls — call `refetch()` afterward, as the other admin
311
+ * hooks do.
312
+ */
313
+ declare const useSignUpInvitations: (options?: UseSignUpInvitationsOptions) => AdminAuthListResult<Record<string, unknown>>;
314
+ /** Options for {@link useAuthSessions}. */
315
+ interface UseAuthSessionsOptions extends AdminAuthQueryOptions {
316
+ /** Scope the list to one user's sessions; omit for the global cross-user browser. */
317
+ userId?: string;
318
+ }
319
+ /**
320
+ * List auth sessions, paged and optionally scoped to one user. Hits
321
+ * `client.listAuthSessions` — HTTP-only, same transport note as
322
+ * {@link useAuthUsers}.
323
+ *
324
+ * Mirrors `auth-sessions-panel.tsx`'s
325
+ * `useClientQuery(["lunora-auth-sessions", …], () => client.listAuthSessions({ limit }))`.
326
+ * Revoking a session (`client.revokeAuthSession`/`revokeAuthUserSessions`)
327
+ * stays a plain `client.*` call followed by this hook's `refetch()`.
328
+ */
329
+ declare const useAuthSessions: (options?: UseAuthSessionsOptions) => AdminAuthListResult<AuthSession>;
330
+ /** Everything {@link useImpersonate} returns. */
331
+ interface UseImpersonateResult {
332
+ /** The latest successful impersonation's token + user + expiry, or `undefined`. */
333
+ readonly data: AuthImpersonation | undefined;
334
+ /** The latest attempt's error, or `undefined`. */
335
+ readonly error: Error | undefined;
336
+ /**
337
+ * Mint an impersonation session for `userId`, resolving its bearer
338
+ * `AuthImpersonation`. Deliberately does **not** call
339
+ * `client.setAuthToken(...)` on the current client — see the security
340
+ * note below.
341
+ */
342
+ readonly impersonate: (userId: string) => Promise<AuthImpersonation>;
343
+ /** `true` while an impersonation request is in flight. */
344
+ readonly pending: boolean;
345
+ /** Clear `data`/`error` back to idle. */
346
+ readonly reset: () => void;
347
+ }
348
+ /**
349
+ * Mint an impersonation session via `client.impersonateAuthUser` — the one
350
+ * genuinely mutation-shaped hook of the four prototyped here (TanStack
351
+ * `useMutation` underneath, matching `@lunora/react`'s own `useMutation`
352
+ * ergonomics: `data`/`error`/`pending`/`reset`).
353
+ *
354
+ * **Security note (open question — see the design doc):** Studio's
355
+ * `user-detail-drawer.tsx` (`onImpersonate`) mints the token and displays it
356
+ * in a read-only text field; it never calls `client.setAuthToken(token)` on
357
+ * the admin's own client instance. This hook preserves that discipline
358
+ * deliberately — silently swapping the *current* session would sign the
359
+ * admin out of their own admin session with no visible transition and no
360
+ * "return to admin" path. The caller decides what to do with the resolved
361
+ * `AuthImpersonation` (open a second tab/incognito window authenticated as
362
+ * the target user, surface it for manual copy, etc.). What the ideal UX is
363
+ * (a dedicated "Acting as X — Return to admin" banner + explicit swap-back)
364
+ * is an open product question this spike does not resolve.
365
+ *
366
+ * Unlike the three list hooks, impersonating a user has no single paired
367
+ * list to invalidate (it may affect a sessions list, but not the user/org
368
+ * list currently being viewed) — mirroring Studio's own `refresh: false` on
369
+ * this action, this hook does not auto-invalidate anything. A caller that
370
+ * also renders `useAuthSessions` can call its `refetch()` explicitly.
371
+ */
372
+ declare const useImpersonate: () => UseImpersonateResult;
373
+ /**
374
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
375
+ * `@lunora/agent`'s `AgentThreadStatus` — re-declared here (rather than imported)
376
+ * so this React entry never pulls in the server-only `@lunora/agent` module
377
+ * graph (the kit stays React + DOM only). Keep in sync with
378
+ * `packages/agent/src/types.ts`.
379
+ */
380
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
381
+ /**
382
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
383
+ * subset of the persisted thread row — every field beyond `status` is optional so
384
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
385
+ * `agent_threads` table in `packages/agent/src/component.ts`.
386
+ */
387
+ interface AgentThreadRecord {
388
+ createdAt?: number;
389
+ /**
390
+ * The failure message when `status === "error"`, `null` once a later run
391
+ * cleared it, absent on a thread that has never failed. Read it for
392
+ * truthiness — `null` and absent both mean "no error".
393
+ */
394
+ error?: null | string;
395
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
396
+ instanceId?: string;
397
+ messageCount?: number;
398
+ /** The verified thread owner, when the run was started with one. */
399
+ owner?: string;
400
+ status: AgentThreadStatus;
401
+ title?: string;
402
+ updatedAt?: number;
403
+ }
404
+ /**
405
+ * The `agents.agentThread` reference the hook subscribes to for live thread state
406
+ * (status + the in-flight `instanceId`). A structural subset of the generated
407
+ * `api.agents` surface, so the whole generated `api` object is assignable.
408
+ */
409
+ interface UseAgentApi {
410
+ agents: {
411
+ agentThread: FunctionReference<"query", {
412
+ key: string;
413
+ }, Record<string, unknown> | undefined>;
414
+ };
415
+ }
416
+ interface UseAgentOptions {
417
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
418
+ api: UseAgentApi;
419
+ /**
420
+ * Optional app mutation over the agent's cancel path
421
+ * (`ctx.agents.<name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
422
+ * When omitted (or no run is in flight) {@link UseAgentResult.cancel} is a
423
+ * no-op.
424
+ */
425
+ cancel?: FunctionReference<"mutation">;
426
+ /**
427
+ * Called when the live thread subscription reports an error (a session
428
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
429
+ * failure is invisible and `thread` / `status` freeze at their last value.
430
+ */
431
+ onError?: SubscriptionErrorCallback;
432
+ /**
433
+ * The app mutation that starts (or continues) a run — a thin wrapper over
434
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
435
+ * {@link UseAgentOptions.runArgs} and the per-call args.
436
+ */
437
+ run: FunctionReference<"mutation">;
438
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
439
+ runArgs?: Record<string, unknown>;
440
+ /** The thread to observe and drive. */
441
+ threadKey: string;
442
+ }
443
+ interface UseAgentResult {
444
+ /**
445
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
446
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
447
+ */
448
+ cancel: () => Promise<void>;
449
+ /** The live thread subscription's last error, or `undefined`. */
450
+ error: Error | undefined;
451
+ /** `true` while a `run` invocation is in flight. */
452
+ pending: boolean;
453
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
454
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
455
+ /** The live thread status, or `undefined` before the thread exists. */
456
+ status: AgentThreadStatus | undefined;
457
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
458
+ thread: AgentThreadRecord | undefined;
459
+ }
460
+ /**
461
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
462
+ * chat message surface. Composes `useSubscription(api.agents.agentThread)` for
463
+ * live state and `useMutation` for the run/cancel writes. For the full
464
+ * conversation surface (durable history + streaming + approvals) use
465
+ * `useAgentChat`.
466
+ *
467
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
468
+ * `ctx.agents.<name>.run` / `.cancel`, so the hook hard-codes no function names
469
+ * beyond the `agents:*` surface.
470
+ */
471
+ declare const useAgent: (options: UseAgentOptions) => UseAgentResult;
472
+ /**
473
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
474
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
475
+ * re-declared here (rather than imported) so this React entry never pulls in the
476
+ * server-only `@lunora/agent` module graph. Keep in sync with the `agent_messages`
477
+ * table in `packages/agent/src/component.ts`.
478
+ */
479
+ interface AgentChatMessage {
480
+ content: string;
481
+ createdAt?: number;
482
+ /**
483
+ * `true` for a client-side optimistic user message not yet acknowledged by
484
+ * the server. Cleared once the durable history carries the matching user turn.
485
+ */
486
+ optimistic?: boolean;
487
+ role: "assistant" | "system" | "tool" | "user";
488
+ seq: number;
489
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
490
+ status?: "approved" | "awaiting_approval" | "rejected";
491
+ toolCallId?: string;
492
+ toolCalls?: ReadonlyArray<{
493
+ id: string;
494
+ input: unknown;
495
+ name: string;
496
+ }>;
497
+ toolName?: string;
498
+ }
499
+ /**
500
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
501
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
502
+ * {@link UseAgentChatResult.streamingText} live and are never replayed; the
503
+ * persisted assistant message stays the single source of truth.
504
+ */
505
+ interface AgentTokenDelta {
506
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
507
+ kind?: "token";
508
+ /** The incremental text chunk the model just produced. */
509
+ text: string;
510
+ /** The thread this delta belongs to. */
511
+ threadKey: string;
512
+ /** The zero-based index of the turn producing the delta. */
513
+ turn: number;
514
+ }
515
+ /**
516
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
517
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
518
+ * surfaced by `useAgentToolEvents`, ignored by {@link UseAgentChatResult.streamingText}.
519
+ */
520
+ interface AgentProgressEvent {
521
+ /** The arbitrary, JSON-serializable payload the tool reported. */
522
+ data: unknown;
523
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
524
+ kind: "progress";
525
+ /** The thread this event belongs to. */
526
+ threadKey: string;
527
+ /** The tool call this progress belongs to. */
528
+ toolCallId: string;
529
+ }
530
+ /**
531
+ * A single event on the agent's live-only channel — a streamed token delta or a
532
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
533
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
534
+ * it unset).
535
+ */
536
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
537
+ /** The `agents:agentMessages` reference — live durable thread history. */
538
+ type AgentMessagesReference$1 = FunctionReference<"query", {
539
+ key: string;
540
+ limit?: number;
541
+ }, ReadonlyArray<Record<string, unknown>>>;
542
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
543
+ type AgentApprovalReference = FunctionReference<"mutation", {
544
+ decision: "approve" | "reject";
545
+ instanceId: string;
546
+ note?: string;
547
+ threadKey: string;
548
+ toolCallId: string;
549
+ }, {
550
+ resolved: boolean;
551
+ }>;
552
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
553
+ type AgentThreadReference = FunctionReference<"query", {
554
+ key: string;
555
+ }, Record<string, unknown> | undefined>;
556
+ /**
557
+ * An app stream reference that tees the agent's in-flight live events, keyed by
558
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
559
+ * sink — tool progress events; this hook consumes only the token arm.
560
+ */
561
+ type AgentTokenStreamReference = FunctionReference<"stream", {
562
+ key: string;
563
+ }, AgentLiveEvent>;
216
564
  /**
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
- */
565
+ * The `agents.*` reference surface the chat hook reads. A structural subset of
566
+ * the generated `api.agents`, so the whole generated `api` object is assignable.
567
+ */
568
+ interface UseAgentChatApi {
569
+ agents: {
570
+ agentMessages: AgentMessagesReference$1;
571
+ agentResolveApproval: AgentApprovalReference;
572
+ agentThread: AgentThreadReference;
573
+ };
574
+ }
575
+ interface UseAgentChatOptions {
576
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
577
+ api: UseAgentChatApi;
578
+ /**
579
+ * Optional app mutation over the agent's cancel path
580
+ * (`ctx.agents.<name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
581
+ * When omitted (or no run is in flight) {@link UseAgentChatResult.cancel} is a
582
+ * no-op.
583
+ */
584
+ cancel?: FunctionReference<"mutation">;
585
+ /** History depth forwarded to `agents:agentMessages`. */
586
+ limit?: number;
587
+ /**
588
+ * Called when the live history or thread subscription reports an error (a
589
+ * session expiry, an RLS denial). Without it — and without reading `error` —
590
+ * such a failure is invisible and `messages` / `status` freeze at their last
591
+ * value.
592
+ */
593
+ onError?: SubscriptionErrorCallback;
594
+ /**
595
+ * The app mutation that starts (or continues) a run — a thin wrapper over
596
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
597
+ * {@link UseAgentChatOptions.sendArgs} and the per-call args.
598
+ */
599
+ send: FunctionReference<"mutation">;
600
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
601
+ sendArgs?: Record<string, unknown>;
602
+ /**
603
+ * Optional live token-delta stream — an app stream function that tees the
604
+ * agent's in-flight deltas. When omitted {@link UseAgentChatResult.streamingText}
605
+ * stays empty and the UI updates message-by-message from durable history.
606
+ */
607
+ stream?: AgentTokenStreamReference;
608
+ /** The thread to observe and continue. */
609
+ threadKey: string;
610
+ }
611
+ interface UseAgentChatResult {
612
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
613
+ approve: (toolCallId: string, note?: string) => Promise<void>;
614
+ /**
615
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
616
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
617
+ */
618
+ cancel: () => Promise<void>;
619
+ /** The history or thread subscription's last error, or `undefined`. */
620
+ error: Error | undefined;
621
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
622
+ messages: ReadonlyArray<AgentChatMessage>;
623
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
624
+ reject: (toolCallId: string, note?: string) => Promise<void>;
625
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
626
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
627
+ /** The live thread status, or `undefined` before the thread exists. */
628
+ status: AgentThreadStatus | undefined;
629
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
630
+ streamingText: string;
631
+ }
632
+ /**
633
+ * A first-class agent chat surface: live durable history + in-flight token
634
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey`.
635
+ *
636
+ * It composes the existing primitives rather than adding transport:
637
+ * `useSubscription(api.agents.agentMessages)` for durable history,
638
+ * `useSubscription(api.agents.agentThread)` for live status + the in-flight
639
+ * `instanceId`, {@link useStream} over an app token stream for in-flight deltas,
640
+ * and `useMutation` for the writes (`api.agents.agentResolveApproval` for
641
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*`
642
+ * surface is hard-coded — `send`/`cancel`/`stream` stay generic references.
643
+ *
644
+ * A `send` optimistically appends the user turn so it renders immediately; the
645
+ * optimistic row clears once the durable history carries the acknowledged turn.
646
+ * `streamingText` is live-only: it holds the current turn's streamed text and
647
+ * empties as soon as that turn's assistant message lands in `messages` (the
648
+ * persisted message is the source of truth), consistent with the loop's
649
+ * replay-safe, live-only delta design.
650
+ */
651
+ declare const useAgentChat: (options: UseAgentChatOptions) => UseAgentChatResult;
652
+ /**
653
+ * The `agents.agentState` reference the hook subscribes to for the thread's live
654
+ * synced state. A structural subset of the generated `api.agents` surface (like
655
+ * `UseAgentApi` for `agentThread`), so the whole generated `api` object is
656
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type
657
+ * is mirrored by the hook's generic `T`, since codegen pins the reference return
658
+ * as an optional record (it never evaluates agent config).
659
+ */
660
+ interface UseAgentStateApi {
661
+ agents: {
662
+ agentState: FunctionReference<"query", {
663
+ key: string;
664
+ }, Record<string, unknown> | undefined>;
665
+ };
666
+ }
667
+ interface UseAgentStateOptions {
668
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
669
+ api: UseAgentStateApi;
670
+ /** The thread whose synced state to observe. */
671
+ threadKey: string;
672
+ }
673
+ interface UseAgentStateResult<T> {
674
+ /** The subscription error, if the live channel reported one. */
675
+ error: Error | undefined;
676
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
677
+ state: T | undefined;
678
+ }
679
+ /**
680
+ * Subscribe to an agent thread's synced state — the `setState`-style value a
681
+ * tool writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`.
682
+ * A thin wrapper over `useSubscription(api.agents.agentState, { key })`: the
683
+ * server pushes a fresh frame whenever the state changes (the dedicated query's
684
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
685
+ * `state` updates only on a real `setState`.
686
+ *
687
+ * Generic over the app's state shape (`useAgentState` with a `SupportState` type
688
+ * argument, itself a record) — the reference is typed as an optional record
689
+ * because codegen cannot see the per-agent state type; the generic casts to `T`.
690
+ * The `extends` bound (not a bare unbounded type parameter) is required: this
691
+ * `.ts` file is parsed JSX-aware by the bundler, where an unbounded type-param
692
+ * arrow is ambiguous with a JSX element.
693
+ */
694
+ declare const useAgentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: UseAgentStateOptions) => UseAgentStateResult<T>;
695
+ /** The `agents:agentMessages` reference — live durable thread history. */
696
+ type AgentMessagesReference = FunctionReference<"query", {
697
+ key: string;
698
+ limit?: number;
699
+ }, ReadonlyArray<Record<string, unknown>>>;
700
+ /**
701
+ * An app stream reference that tees the agent's in-flight live events, keyed by
702
+ * thread. Carries token deltas and tool progress events; this hook consumes only
703
+ * the progress arm (`kind === "progress"`).
704
+ */
705
+ type AgentLiveStreamReference = FunctionReference<"stream", {
706
+ key: string;
707
+ }, AgentLiveEvent>;
708
+ /**
709
+ * The `agents.*` reference surface the tool-events hook reads. A structural
710
+ * subset of the generated `api.agents`, so the whole generated `api` object is
711
+ * assignable.
712
+ */
713
+ interface UseAgentToolEventsApi {
714
+ agents: {
715
+ agentMessages: AgentMessagesReference;
716
+ };
717
+ }
718
+ interface UseAgentToolEventsOptions {
719
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
720
+ api: UseAgentToolEventsApi;
721
+ /** History depth forwarded to `agents:agentMessages`. */
722
+ limit?: number;
723
+ /**
724
+ * Optional live event stream — the same app stream function `useAgentChat`
725
+ * uses. When supplied, ephemeral `ctx.reportProgress(...)` events for the
726
+ * thread are surfaced as `{ type: "progress" }` entries; when omitted only the
727
+ * durable lifecycle (call / result / awaiting-approval) is returned.
728
+ */
729
+ stream?: AgentLiveStreamReference;
730
+ /** The thread whose tool activity to observe. */
731
+ threadKey: string;
732
+ }
733
+ /**
734
+ * A single tool-lifecycle event for a thread. The durable arms
735
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
736
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
737
+ * stream and has no `seq`. Discriminate on `type`.
738
+ */
739
+ type AgentToolEvent = {
740
+ data: unknown;
741
+ toolCallId: string;
742
+ type: "progress";
743
+ } | {
744
+ input: unknown;
745
+ seq: number;
746
+ toolCallId: string;
747
+ toolName: string;
748
+ type: "call";
749
+ } | {
750
+ output: string;
751
+ seq: number;
752
+ status?: "approved" | "rejected";
753
+ toolCallId?: string;
754
+ toolName?: string;
755
+ type: "result";
756
+ } | {
757
+ seq: number;
758
+ toolCallId?: string;
759
+ toolName?: string;
760
+ type: "awaiting-approval";
761
+ };
762
+ interface UseAgentToolEventsResult {
763
+ /**
764
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
765
+ * followed by any in-flight ephemeral progress events. Rebuilt each render
766
+ * from the live subscription + stream — treat as derived, not identity-stable.
767
+ */
768
+ events: ReadonlyArray<AgentToolEvent>;
769
+ }
770
+ /**
771
+ * A focused view of a thread's tool activity: tool calls, their results,
772
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
773
+ * without the full chat message surface. Composes the existing primitives:
774
+ * `useSubscription(api.agents.agentMessages)` for the durable lifecycle and
775
+ * {@link useStream} over the optional app event stream for ephemeral progress.
776
+ *
777
+ * Progress events are live-only (the durable path never emits them): they ride
778
+ * the same sink as token deltas and are surfaced here, correlated to their tool
779
+ * call by `toolCallId`. For the conversational surface (messages + streaming
780
+ * text + approvals) use `useAgentChat`; this hook is the tool-observability slice.
781
+ */
782
+ declare const useAgentToolEvents: (options: UseAgentToolEventsOptions) => UseAgentToolEventsResult;
783
+ /**
784
+ * Token + identity plumbing. The token lives on the shared `LunoraClient`;
785
+ * `setToken(jwt)` after a sign-in makes subsequent RPC calls carry the
786
+ * `Authorization` header. `user` and `status` come from the framework-agnostic
787
+ * per-client identity store in `@lunora/client/auth` — the same store Vue,
788
+ * Solid, Svelte and Angular read, so all five agree on what "authenticated"
789
+ * means rather than each keeping a private copy of the resolve logic.
790
+ *
791
+ * `status` is the value to branch on: `user` is `null` both when signed out and
792
+ * when a held credential's identity endpoint could not be reached. See the
793
+ * contract documented on `AuthStatus`.
794
+ *
795
+ * Multiple `useAuth` instances stay in sync: token, user and status are all read
796
+ * through `useSyncExternalStore` over the shared client and its identity store,
797
+ * so a `setToken` from one component re-renders every mounted hook.
798
+ */
228
799
  declare const useAuth: () => UseAuthResult;
800
+ type Setter<T> = (value: T) => void;
229
801
  /**
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
- */
802
+ * Subscribe to a local-only {@link ClientQueryRef} and re-render when its
803
+ * value changes. Unlike `useQuery`, this never touches the network — the
804
+ * value lives in a reactive store on the `LunoraClient` instance and is shared
805
+ * across every consumer of the same ref.
806
+ *
807
+ * The initial render reads the store synchronously (via
808
+ * `useSyncExternalStore`), so there is never an "undefined flash" — the value
809
+ * is either the one most recently set or `ref.defaultValue`.
810
+ *
811
+ * Returns a `[value, setter]` tuple, matching the `useState` convention.
812
+ * @example
813
+ * ```tsx
814
+ * import { useClientQuery, createClientQuery } from "@lunora/react";
815
+ *
816
+ * const sidebarOpen = createClientQuery("sidebarOpen", true);
817
+ *
818
+ * function Sidebar() {
819
+ * const [open, setOpen] = useClientQuery(sidebarOpen);
820
+ * return <aside data-open={open}>…</aside>;
821
+ * }
822
+ * ```
823
+ */
824
+ declare const useClientQuery: <T extends unknown>(ref: ClientQueryRef<T>) => [T, Setter<T>];
825
+ /**
826
+ * Reactive view of the client's aggregate live-socket status across all shard
827
+ * connections. Re-renders on every transition (`idle` → `connecting` →
828
+ * `connected` → `offline`). Use it to drive a connection indicator so an
829
+ * operator can tell a healthy live channel from a silently-dropped socket.
830
+ */
235
831
  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
832
  /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
239
833
  type FlagValue = boolean | number | string | {
240
834
  [key: string]: unknown;
241
835
  } | unknown[] | null;
242
836
  /**
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;
837
+ * Subscribe to a single feature flag, live over Lunora's WebSocket.
838
+ *
839
+ * Returns `defaultValue` until the first evaluation lands, then the server's
840
+ * resolved value — re-pushed whenever the provider re-evaluates (e.g. a flag is
841
+ * toggled in Cloudflare Flagship). The flag's kind is inferred from
842
+ * `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean and
843
+ * `useFlag("hero", "control")` a string.
844
+ *
845
+ * The reactive channel is public, so the server evaluates every flag under the
846
+ * socket's own verified identity — the targeting key your `defineFlags({
847
+ * identify })` derives — and accepts no client-supplied targeting context. For
848
+ * evaluation under a context you compute, call `ctx.flags.*` inside a query,
849
+ * mutation, or action and return the resolved value.
850
+ *
851
+ * Evaluation runs through whatever OpenFeature provider the app wired in
852
+ * `lunora/flags.ts`; the read never throws — a provider error resolves the
853
+ * default (the same fail-open contract as server-side `ctx.flags`).
854
+ */
855
+ declare const useFlag: <T extends FlagValue>(key: string, defaultValue: T) => T;
856
+ /**
857
+ * Subscribe to several feature flags at once, live over Lunora's WebSocket.
858
+ *
859
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
860
+ * default, and the result is the same-shaped record with resolved values (the
861
+ * defaults until each evaluation lands). This is the batched form of
862
+ * {@link useFlag} — one effect manages one subscription per key, so it stays
863
+ * rules-of-hooks-safe even as the flag set changes between renders. Like
864
+ * {@link useFlag} it evaluates under the socket's server-verified identity only.
865
+ */
866
+ declare const useFlags: <T extends Record<string, FlagValue>>(flags: T) => T;
867
+ /** The lifecycle of a stream the hook is observing. */
868
+ type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
869
+ /**
870
+ * Result shape returned by {@link useHttpStream}.
871
+ * @experimental Part of the HTTP-SSE stream surface.
872
+ */
873
+ interface UseHttpStreamResult<T> {
874
+ /** Force-cancel the stream (aborts the fetch) and resolve the iterator. Safe to call multiple times. */
875
+ cancel: () => void;
876
+ /** Chunks the server has pushed so far, in arrival order. */
877
+ chunks: ReadonlyArray<T>;
878
+ error: Error | undefined;
879
+ status: UseStreamStatus;
880
+ }
881
+ /**
882
+ * Options accepted by {@link useHttpStream}.
883
+ * @experimental Part of the HTTP-SSE stream surface.
884
+ */
885
+ interface UseHttpStreamOptions {
886
+ /** Forwarded to `client.httpStream()` — caps the in-flight chunk buffer. */
887
+ maxBuffer?: number;
888
+ }
889
+ /**
890
+ * Consume an **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`) via
891
+ * `client.httpStream`. Distinct from `useStream`, which consumes the WS
892
+ * procedure stream (`kind: "stream"`). Returns the chunks received so far plus
893
+ * a lifecycle status and a cancel function. Changing the route or the
894
+ * serialized `args` resets the stream — the previous fetch is aborted (the
895
+ * server sees `request.signal`) and a fresh one opens with empty `chunks`.
896
+ * Unmount also aborts.
897
+ *
898
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
899
+ * (mirrors `useQuery` / `useStream`).
900
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
901
+ */
902
+ declare const useHttpStream: <Ref extends HttpStreamRef>(route: Ref, args: "skip" | HttpStreamArgsOf<Ref>, options?: UseHttpStreamOptions) => UseHttpStreamResult<HttpStreamChunkOf<Ref>>;
268
903
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
269
904
  type PaginatedArgs<F> = Omit<ArgsOf<F>, "paginationOpts">;
270
905
  /** The element type of the `page` array a paginated query returns. */
@@ -272,44 +907,54 @@ type PageItemOf<F> = ReturnOf<F> extends {
272
907
  page: (infer T)[];
273
908
  } ? T : unknown;
274
909
  /**
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
- */
910
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
911
+ *
912
+ * Pass `onError` (and read `error`) to see a page failure: without it the hook
913
+ * only reports `status`, and a first page that fails reads as an eternal
914
+ * `isLoading`.
915
+ *
916
+ * The query function must accept a `paginationOpts: { numItems, cursor,
917
+ * endCursor }` arg and return a `PaginationResult` (the shape
918
+ * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
919
+ * stable boundary cursors: each loaded page is a live subscription over a
920
+ * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
921
+ * Because boundaries are shared stable cursors, inserting or deleting a row in
922
+ * the middle of the list grows/shrinks the affected page in place without
923
+ * duplicating or skipping rows across page boundaries — the bug the legacy
924
+ * "first N after the previous page's last row" model suffered under live edits.
925
+ *
926
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
927
+ * it is a no-op unless `status === "CanLoadMore"`. Background split/join
928
+ * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
929
+ * `use-paginated-core.ts`).
930
+ *
931
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
932
+ * feed to its first page. The public return shape (`results` / `status` /
933
+ * `loadMore`) is unchanged from the legacy keyset implementation.
934
+ *
935
+ * There is no total-row count here, and deliberately not: `paginate()` never
936
+ * counts the tail, which is what keeps a page O(page) rather than O(table). For
937
+ * a "42 of 1,203" label, subscribe to a `ctx.db.<table>.count(where)` query with
938
+ * the same filter args via `useQuery` — it is live, so it moves with the
939
+ * list. See the pagination concept page.
940
+ */
296
941
  declare const usePaginatedQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UsePaginatedQueryOptions) => UsePaginatedQueryResult<PageItemOf<F>>;
297
942
  /**
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
- */
943
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
944
+ *
945
+ * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
946
+ * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
947
+ * inserted or deleted mid-list grows/shrinks the affected page without
948
+ * duplicating or skipping rows across boundaries — but keeps each page as its
949
+ * own inner array rather than flattening them, and adds the
950
+ * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
951
+ * shape. `fetchNextPage` appends the next page off the open-ended tail's
952
+ * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
953
+ *
954
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
955
+ * feed to its first page. The public return shape is unchanged from the legacy
956
+ * keyset implementation.
957
+ */
313
958
  declare const useInfiniteQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UseInfiniteQueryOptions) => UseInfiniteQueryResult<PageItemOf<F>>;
314
959
  type CallOptions<F extends FunctionReference> = UseMutationCallOptions<unknown, unknown, ArgsOf<F>>;
315
960
  interface MutationHook<F extends FunctionReference> {
@@ -325,34 +970,43 @@ interface MutationHook<F extends FunctionReference> {
325
970
  /** Clear the latest `data`/`error` back to idle. */
326
971
  reset: () => void;
327
972
  /**
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
- */
973
+ * Bind a Convex-parity multi-query optimistic update to this mutation.
974
+ * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
975
+ * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
976
+ * is supplied in the call options, which overrides the bound one.
977
+ */
333
978
  withOptimisticUpdate: (update: OptimisticUpdate<ArgsOf<F>>) => MutationHook<F>;
334
979
  }
335
980
  /**
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
- */
981
+ * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
982
+ * given mutation reference. Prefer destructuring at the call site so the React
983
+ * linter can track dependencies on each field independently.
984
+ *
985
+ * Not callable: `const send = useMutation(api.x.y); send({ … })` is a `TS2349`.
986
+ * Destructure the invoker — `const { mutate: send } = useMutation(api.x.y)`.
987
+ *
988
+ * Built on TanStack Query's mutation cache (the same cache the query hooks use),
989
+ * so it composes with Query Devtools and exposes the latest call's `data`/`error`
990
+ * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
991
+ * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
992
+ *
993
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance
994
+ * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
995
+ * `false` only once every concurrent call has settled — and a sibling component
996
+ * mutating the same function never affects it (TanStack's own `isPending` tracks
997
+ * just the latest invocation).
998
+ *
999
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
1000
+ * call options pass straight through to `client.mutation`, which applies and
1001
+ * rolls them back against the Lunora subscription cache (Convex parity) — not
1002
+ * through TanStack's `onMutate`.
1003
+ *
1004
+ * Offline, a write the client can queue reaches `client.mutation` at once,
1005
+ * which queues it (the offline queue or a durable outbox) and paints the
1006
+ * optimistic update. A write it cannot queue (before the shard's first connect,
1007
+ * or with no WebSocket) waits until the browser is online again, then sends.
1008
+ * TanStack never retries; the queue owns replays.
1009
+ */
356
1010
  declare const useMutation: <F extends FunctionReference>(function_: F) => MutationHook<F>;
357
1011
  interface MutatorHook<TArgs> {
358
1012
  /** The latest invocation's error, or `undefined`. */
@@ -367,86 +1021,104 @@ interface MutatorHook<TArgs> {
367
1021
  reset: () => void;
368
1022
  }
369
1023
  /**
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
- */
1024
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
1025
+ * custom-mutator handle from `@lunora/db`'s `bindMutators`. The optimistic
1026
+ * overlay and server-authoritative push are owned by the bound handle (and
1027
+ * TanStack DB's optimistic-transaction layer rebases pending overlays on every
1028
+ * sync tick) — this hook only surfaces React state for the in-flight/error
1029
+ * lifecycle. Reads stay on the existing `useLiveQuery`; no new query hook is
1030
+ * needed.
1031
+ *
1032
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance,
1033
+ * so it clears only once every concurrent call has settled.
1034
+ */
381
1035
  declare const useMutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHook<TArgs>;
382
1036
  /**
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
- */
1037
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
1038
+ * during SSR, then keep it live.
1039
+ *
1040
+ * The first render returns the preloaded value (TanStack's `initialData`),
1041
+ * so the server markup and the initial client markup match — no hydration
1042
+ * mismatch, no loading flash. After mount, a WS subscription attaches so
1043
+ * later server pushes update the value just like `useQuery`.
1044
+ *
1045
+ * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
1046
+ * full dehydrate/hydrate dance because the consumer hands us the resolved
1047
+ * value directly. Apps that want to share a pre-populated QueryClient across
1048
+ * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
1049
+ * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
1050
+ *
1051
+ * Pass `onError` to surface a subscription-scoped error the server pushes (a
1052
+ * session expiry, an RLS denial). Without it such an error is dropped and the
1053
+ * hook keeps rendering the SSR snapshot as if it were live.
1054
+ *
1055
+ * The preloaded value was read for whoever was signed in when the page loaded.
1056
+ * After a sign-out or user switch retires an identity (`client.identityEpoch()`
1057
+ * above `0`), every `usePreloadedQuery` on the client (mounted then or later)
1058
+ * stops using it and returns `undefined` until the live value arrives. So does
1059
+ * every one under a `LunoraProvider` whose `client` was swapped, mounted before
1060
+ * or after the swap — hence the `T | undefined` return type. A token
1061
+ * preloaded after the switch (a client-side navigation that preloads again) is
1062
+ * ignored too and costs a loading flash: the hook cannot tell which identity a
1063
+ * token was read under.
1064
+ */
1065
+ declare const usePreloadedQuery: <T>(preloaded: Preloaded<T>, options?: {
1066
+ onError?: SubscriptionErrorCallback;
1067
+ }) => T | undefined;
1068
+ /**
1069
+ * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
1070
+ * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
1071
+ * attaches a live WS subscription on mount. It is a thin alias of
1072
+ * {@link usePreloadedQuery} so the React adapter exposes the same
1073
+ * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
1074
+ * while existing callers of `usePreloadedQuery` keep working unchanged.
1075
+ *
1076
+ * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
1077
+ * call it like a hook — at the top level of a component, unconditionally.
1078
+ */
1079
+ declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, options?: {
1080
+ onError?: SubscriptionErrorCallback;
1081
+ }) => T | undefined;
1082
+ /**
1083
+ * `usePresence` — collaborative-awareness hook, the client half of the
1084
+ * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
1085
+ * parity).
1086
+ *
1087
+ * It drives the two presence functions the server component ships:
1088
+ *
1089
+ * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
1090
+ * whenever the tab becomes visible, to upsert the caller's presence row and
1091
+ * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
1092
+ * carries the latest `data` from a ref, so `setData` takes effect on the next
1093
+ * tick without re-subscribing or resetting the timer.
1094
+ * - **listPresent** (a query): subscribed to over the live-query WS, so the
1095
+ * present-list updates reactively. Because the server patches a single row per
1096
+ * heartbeat, the client's **per-row subscription delta merge** applies just that
1097
+ * row to the cached list instead of re-sending every member — the list stays
1098
+ * cheap even with many participants heart-beating.
1099
+ *
1100
+ * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
1101
+ * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
1102
+ * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
1103
+ * the hook needs no client-side reaping.
1104
+ *
1105
+ * The two `FunctionReference`s come from your generated `api` (e.g.
1106
+ * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
1107
+ * stays decoupled from any specific app schema.
1108
+ */
1109
+ /**
1110
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
1111
+ * `definePresence().functions.heartbeat` registers).
1112
+ */
441
1113
  type HeartbeatReference = FunctionReference<"mutation", {
442
1114
  data?: Record<string, unknown>;
443
1115
  roomId: string;
444
1116
  sessionId: string;
445
1117
  }>;
446
1118
  /**
447
- * A listPresent query reference: takes `{ roomId }` and returns the array of
448
- * present members.
449
- */
1119
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
1120
+ * present members.
1121
+ */
450
1122
  type ListPresentReference = FunctionReference<"query", {
451
1123
  roomId: string;
452
1124
  }>;
@@ -460,14 +1132,22 @@ interface UsePresenceOptions<H extends HeartbeatReference, L extends ListPresent
460
1132
  /** The `api.*` reference for the presence listPresent query. */
461
1133
  listPresent: L;
462
1134
  /**
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
- */
1135
+ * Called when the `listPresent` subscription reports an error (a session
1136
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
1137
+ * failure is invisible and `present` freezes at its last value.
1138
+ */
1139
+ onError?: SubscriptionErrorCallback;
1140
+ /**
1141
+ * Stable id for this presence row. Defaults to a fresh per-mount id (one row
1142
+ * per tab). Pass a user/connection id to control deduping.
1143
+ */
466
1144
  sessionId?: string;
467
1145
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
468
1146
  shardKey?: string;
469
1147
  }
470
1148
  interface UsePresenceResult<L extends ListPresentReference> {
1149
+ /** The `listPresent` subscription's last error, or `undefined`. */
1150
+ error: SubscriptionError | undefined;
471
1151
  /** The present members for the room, as `listPresent` returns them. `undefined` until the first push. */
472
1152
  present: ReturnOf<L> | undefined;
473
1153
  /** This mount's session id (generated when not supplied). */
@@ -477,25 +1157,36 @@ interface UsePresenceResult<L extends ListPresentReference> {
477
1157
  }
478
1158
  declare const usePresence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: UsePresenceOptions<H, L>) => UsePresenceResult<L>;
479
1159
  /**
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
- */
1160
+ * Subscribe to a server query.
1161
+ *
1162
+ * Returns `undefined` until the first response lands. Pass `"skip"` for
1163
+ * `args` to short-circuit the query (no network call, no subscription).
1164
+ *
1165
+ * When the `LunoraClient` was created with `hydrateOnStart: true` and a
1166
+ * `queryCache` adapter, the first **enabled** render waits for the durable
1167
+ * read cache to finish loading. If a cached value exists for this query it
1168
+ * is fed as `initialData` so the user sees it immediately — no undefined
1169
+ * flash before the socket round-trip.
1170
+ *
1171
+ * Internally this routes through TanStack Query: the queryKey is
1172
+ * `["lunora", fn.__lunoraRef, stableWireKey(args), shardKey]` (the args are
1173
+ * encoded key-order-independently, so an args object built in a different key
1174
+ * order still dedupes, and wire-typed args get distinct entries). The
1175
+ * subscription registry shares a single WS subscription across every consumer
1176
+ * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
1177
+ *
1178
+ * Pass `onError` to surface a subscription-scoped error the server pushes (an RLS
1179
+ * denial, a query that starts failing server-side). Without it such an error is
1180
+ * dropped and the returned value just freezes at its last good result.
1181
+ */
491
1182
  declare const useQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => ReturnOf<F> | undefined;
492
1183
  interface UseRateLimitOptions {
493
1184
  /** Clock injection for tests. Defaults to `Date.now`. */
494
1185
  now?: () => number;
495
1186
  /**
496
- * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
497
- * down and `disabled` flips back automatically. Defaults to `1000`.
498
- */
1187
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
1188
+ * down and `disabled` flips back automatically. Defaults to `1000`.
1189
+ */
499
1190
  tickMs?: number;
500
1191
  }
501
1192
  interface UseRateLimitResult {
@@ -513,17 +1204,15 @@ interface UseRateLimitResult {
513
1204
  retryAfter: number;
514
1205
  }
515
1206
  /**
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
- */
1207
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
1208
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
1209
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
1210
+ * authoritative check; the server remains the source of truth.
1211
+ *
1212
+ * `config` is read on every render; pass a stable reference (module constant or
1213
+ * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
1214
+ */
524
1215
  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
1216
  interface UseStreamResult<T> {
528
1217
  /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
529
1218
  cancel: () => void;
@@ -533,24 +1222,198 @@ interface UseStreamResult<T> {
533
1222
  status: UseStreamStatus;
534
1223
  }
535
1224
  interface UseStreamOptions {
1225
+ /**
1226
+ * Opt into resume-on-reconnect for a stream the server declared `durable`.
1227
+ * The hook keeps the chunks it already has and the socket re-attaches to the
1228
+ * same run, so a dropped connection mid-generation continues instead of
1229
+ * surfacing `STREAM_DISCONNECTED`. Has no effect on an ephemeral stream.
1230
+ */
1231
+ durable?: boolean;
536
1232
  /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
537
1233
  maxBuffer?: number;
538
1234
  shardKey?: string;
539
1235
  }
540
1236
  /**
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
- */
1237
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
1238
+ * lifecycle status and a cancel function. Changing `fn` or the serialized
1239
+ * `args` resets the stream — the previous iterator is cancelled and a fresh
1240
+ * one opens with empty `chunks`.
1241
+ *
1242
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
1243
+ * (mirrors `useQuery` / `useSubscription`).
1244
+ */
549
1245
  declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: "skip" | ArgsOf<F>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
550
1246
  /**
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
- */
1247
+ * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
1248
+ * hook does not issue an initial HTTP fetch — it only delivers values that
1249
+ * the server pushes over the WS.
1250
+ *
1251
+ * A server-pushed error lands on `error` as a `LunoraError` carrying the
1252
+ * server's `code` (a bare `Error` only when the server sent no code), so
1253
+ * consumers can branch on the error kind; `onError` receives the raw
1254
+ * `SubscriptionError` in addition.
1255
+ */
555
1256
  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 };
1257
+ /**
1258
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
1259
+ * capture and speaker playback implementations injected into the hook via its
1260
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
1261
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
1262
+ * hook's transport + React-state logic and remains mockable in a non-browser
1263
+ * test env.
1264
+ */
1265
+ /**
1266
+ * The negotiated audio format the voice DO streams back. Mirrors
1267
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1268
+ * imported) so this React package never pulls in the server-only `@lunora/agent`
1269
+ * module graph.
1270
+ */
1271
+ type VoiceAudioFormat = "mp3" | "wav";
1272
+ /** Captures microphone audio and reports level / turn boundaries back to the hook. */
1273
+ interface VoiceMicrophone {
1274
+ /** Mute/unmute the mic without tearing down the capture graph. */
1275
+ setMuted: (muted: boolean) => void;
1276
+ /** Stop capture and release the media stream + audio graph. */
1277
+ stop: () => void;
1278
+ }
1279
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1280
+ interface VoiceSpeaker {
1281
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1282
+ enqueue: (audio: Uint8Array) => void;
1283
+ /** Drop everything queued and stop the current chunk (barge-in). */
1284
+ interrupt: () => void;
1285
+ /** Release the playback audio context. */
1286
+ stop: () => void;
1287
+ }
1288
+ /** Config passed to a {@link CreateMicrophone} factory. */
1289
+ interface MicrophoneConfig {
1290
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1291
+ interruptChunks: number;
1292
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1293
+ interruptThreshold: number;
1294
+ /**
1295
+ * `true` from the moment a turn is committed until it completes — the whole
1296
+ * `thinking` + `speaking` window, not just the audible half.
1297
+ *
1298
+ * It gates BOTH branches below, and the wider span is the point. Gated only
1299
+ * on "audibly speaking", turn detection kept running through the entire
1300
+ * STT+LLM window after a `commit`: room noise at the (deliberately low)
1301
+ * `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
1302
+ * `commit`, and the DO refused it with "a turn is already in progress" —
1303
+ * a refusal that returns before draining the audio buffer, so the PCM
1304
+ * captured since the first commit leaked into the next utterance.
1305
+ *
1306
+ * A genuine barge-in still works in that window: it routes through the
1307
+ * `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
1308
+ * `interruptThreshold` — an order of magnitude above `silenceThreshold` —
1309
+ * and `interrupt` is exactly what the DO tells the client to send.
1310
+ */
1311
+ isTurnActive: () => boolean;
1312
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1313
+ onAudio: (pcm: Uint8Array) => void;
1314
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1315
+ onInterrupt: () => void;
1316
+ /** The current input RMS (0–1), for a level meter. */
1317
+ onLevel: (rms: number) => void;
1318
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1319
+ onSilence: () => void;
1320
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1321
+ silenceDurationMs: number;
1322
+ /** RMS below which audio counts as silence. */
1323
+ silenceThreshold: number;
1324
+ }
1325
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1326
+ type CreateSpeaker = (config: {
1327
+ audioFormat: VoiceAudioFormat;
1328
+ }) => VoiceSpeaker;
1329
+ /**
1330
+ * The `agents.<name>Voice` reference codegen emits for a voice-enabled agent — a
1331
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1332
+ * generated member, so passing `api.agents.<name>Voice` type-checks.
1333
+ */
1334
+ type VoiceReference = FunctionReference<"stream", {
1335
+ threadKey: string;
1336
+ }, Record<string, unknown>>;
1337
+ /** The lifecycle of a voice call, mirrored to the UI. */
1338
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1339
+ /** A minimal structural subset of the DOM `WebSocket` the hook drives. */
1340
+ interface VoiceSocket {
1341
+ binaryType: string;
1342
+ close: () => void;
1343
+ onclose: ((event: unknown) => void) | null;
1344
+ onerror: ((event: unknown) => void) | null;
1345
+ onmessage: ((event: {
1346
+ data: unknown;
1347
+ }) => void) | null;
1348
+ onopen: ((event: unknown) => void) | null;
1349
+ readonly readyState: number;
1350
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1351
+ }
1352
+ type CreateSocket = (url: string) => VoiceSocket;
1353
+ interface UseVoiceAgentOptions {
1354
+ /**
1355
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1356
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1357
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1358
+ */
1359
+ createMicrophone?: CreateMicrophone;
1360
+ /**
1361
+ * Advanced/test seam: open the transport. Defaults to the WebSocket
1362
+ * implementation the client was built with (`client.getWebSocketImpl()`),
1363
+ * NOT a raw `globalThis.WebSocket`.
1364
+ */
1365
+ createSocket?: CreateSocket;
1366
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1367
+ createSpeaker?: CreateSpeaker;
1368
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1369
+ interruptChunks?: number;
1370
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1371
+ interruptThreshold?: number;
1372
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1373
+ silenceDurationMs?: number;
1374
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1375
+ silenceThreshold?: number;
1376
+ /** The thread to converse on — shared with the agent's text turns. */
1377
+ threadKey: string;
1378
+ /** The generated `api.agents.<name>Voice` reference — identifies the voice DO endpoint. */
1379
+ voice: VoiceReference;
1380
+ }
1381
+ interface UseVoiceAgentResult {
1382
+ /** The current input RMS (0–1) — drive a mic level meter. */
1383
+ audioLevel: number;
1384
+ /** `true` once the WS `ready` handshake completed. */
1385
+ connected: boolean;
1386
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1387
+ endCall: () => void;
1388
+ /** The last transport/pipeline error, or `undefined`. */
1389
+ error: Error | undefined;
1390
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1391
+ interimTranscript: string;
1392
+ /** `true` while the mic is muted. */
1393
+ isMuted: boolean;
1394
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1395
+ sendText: (text: string) => void;
1396
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1397
+ startCall: () => Promise<void>;
1398
+ /** The current call lifecycle. */
1399
+ status: VoiceStatus;
1400
+ /** Mute/unmute the microphone. Returns the new muted state. */
1401
+ toggleMute: () => boolean;
1402
+ /** The last finalized user utterance (STT result). */
1403
+ transcript: string;
1404
+ }
1405
+ /**
1406
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1407
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1408
+ * streams the agent's synthesized speech back through the browser's audio output,
1409
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1410
+ * `audioLevel`) to React state. Pass the generated `api.agents.<name>Voice`
1411
+ * reference (never a string), matching `useAgentChat`'s reference-passing style.
1412
+ *
1413
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1414
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1415
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1416
+ * `createSocket`) so the hook is drivable outside a browser.
1417
+ */
1418
+ declare const useVoiceAgent: (options: UseVoiceAgentOptions) => UseVoiceAgentResult;
1419
+ 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 };