@lunora/react 1.0.0-alpha.24 → 1.0.0-alpha.241

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/README.md +28 -18
  2. package/dist/index.d.mts +1241 -358
  3. package/dist/index.d.ts +1241 -358
  4. package/dist/index.mjs +1 -19
  5. package/dist/packem_shared/AuthLoading-024-XH0I.mjs +2 -0
  6. package/dist/packem_shared/LunoraProvider-Cge6aAOa.mjs +1 -0
  7. package/dist/packem_shared/hydratePreloaded-qs8nspKB.mjs +2 -0
  8. package/dist/packem_shared/lunora-provider-_WqSuvf9.mjs +2 -0
  9. package/dist/packem_shared/lunoraQueryOptions-IJB_aFzi.mjs +1 -0
  10. package/dist/packem_shared/query-key-BysXrewF.mjs +1 -0
  11. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.mts +38 -0
  12. package/dist/packem_shared/query-options.d-CdgGQ9s4.d.ts +38 -0
  13. package/dist/packem_shared/stream-state-abygFxmy.mjs +1 -0
  14. package/dist/packem_shared/use-paginated-core-Bf9xLRSk.mjs +2 -0
  15. package/dist/packem_shared/useAction-jJl4KPEw.mjs +2 -0
  16. package/dist/packem_shared/useAgent-C2jMXz2-.mjs +2 -0
  17. package/dist/packem_shared/useAgentChat-DiBCl0Rr.mjs +2 -0
  18. package/dist/packem_shared/useAgentState-CDAO3aLL.mjs +2 -0
  19. package/dist/packem_shared/useAgentToolEvents-Bb94yV7R.mjs +2 -0
  20. package/dist/packem_shared/useAuth-CpGKVRsv.mjs +2 -0
  21. package/dist/packem_shared/useAuthSessions-jJWdw8Zw.mjs +2 -0
  22. package/dist/packem_shared/useAuthState-CqN1F2FM.mjs +2 -0
  23. package/dist/packem_shared/useClientQuery-DUEUAqPh.mjs +2 -0
  24. package/dist/packem_shared/useConnectionStatus-Dtx_OWez.mjs +2 -0
  25. package/dist/packem_shared/useFlag-A7XPHExt.mjs +2 -0
  26. package/dist/packem_shared/useHttpStream-CzryjxVH.mjs +2 -0
  27. package/dist/packem_shared/useInfiniteQuery-D_AG59dX.mjs +2 -0
  28. package/dist/packem_shared/useLiveTopic-C6a6nMn0.mjs +2 -0
  29. package/dist/packem_shared/useMutation-Bz9uwvGf.mjs +2 -0
  30. package/dist/packem_shared/useMutator-BtUd-xEA.mjs +2 -0
  31. package/dist/packem_shared/usePaginatedQuery-DhQAsxgX.mjs +2 -0
  32. package/dist/packem_shared/usePresence-X5Ax04Cf.mjs +2 -0
  33. package/dist/packem_shared/useQuery-CETQat99.mjs +2 -0
  34. package/dist/packem_shared/useRateLimit-Cckxi8m9.mjs +2 -0
  35. package/dist/packem_shared/useStream-D8GB__4j.mjs +2 -0
  36. package/dist/packem_shared/useSubscription-CwZgOrE4.mjs +2 -0
  37. package/dist/packem_shared/useVoiceAgent-DAh27XxD.mjs +2 -0
  38. package/dist/payment.d.mts +105 -0
  39. package/dist/payment.d.ts +105 -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 -4
  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-D1O_xfAe.mjs +0 -80
  52. package/dist/packem_shared/hydratePreloaded-uMDH_xA9.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-DafedU4l.mjs +0 -179
  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-C2Pkghli.mjs +0 -128
  63. package/dist/packem_shared/useInfiniteQuery-BeaehE9f.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-_6ETVUmf.mjs +0 -46
  67. package/dist/packem_shared/usePresence-Rnx1Fznc.mjs +0 -115
  68. package/dist/packem_shared/useQuery-D3_ZxMYs.mjs +0 -54
  69. package/dist/packem_shared/useRateLimit-DTEffQEi.mjs +0 -64
  70. package/dist/packem_shared/useStream-CGC26afa.mjs +0 -128
  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, SubscribeLiveTopicOptions, LiveStreamSubscribeError, 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,753 @@ 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
+ }
216
499
  /**
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
- */
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>;
564
+ /**
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;
801
+ /**
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>];
229
825
  /**
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
- */
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
+ */
872
+ interface UseHttpStreamResult<T> {
873
+ /** Force-cancel the stream (aborts the fetch) and resolve the iterator. Safe to call multiple times. */
874
+ cancel: () => void;
875
+ /** Chunks the server has pushed so far, in arrival order. */
876
+ chunks: ReadonlyArray<T>;
877
+ error: Error | undefined;
878
+ status: UseStreamStatus;
879
+ }
880
+ /**
881
+ * Options accepted by {@link useHttpStream}.
882
+ */
883
+ interface UseHttpStreamOptions {
884
+ /** Forwarded to `client.httpStream()` — caps the in-flight chunk buffer. */
885
+ maxBuffer?: number;
886
+ }
887
+ /**
888
+ * Consume an **HTTP-SSE route stream** (`httpRoute.<verb>(path).stream()`) via
889
+ * `client.httpStream`. Distinct from `useStream`, which consumes the WS
890
+ * procedure stream (`kind: "stream"`). Returns the chunks received so far plus
891
+ * a lifecycle status and a cancel function. Changing the route or the
892
+ * serialized `args` resets the stream — the previous fetch is aborted (the
893
+ * server sees `request.signal`) and a fresh one opens with empty `chunks`.
894
+ * Unmount also aborts.
895
+ *
896
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
897
+ * (mirrors `useQuery` / `useStream`).
898
+ */
899
+ declare const useHttpStream: <Ref extends HttpStreamRef>(route: Ref, args: "skip" | HttpStreamArgsOf<Ref>, options?: UseHttpStreamOptions) => UseHttpStreamResult<HttpStreamChunkOf<Ref>>;
268
900
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
269
901
  type PaginatedArgs<F> = Omit<ArgsOf<F>, "paginationOpts">;
270
902
  /** The element type of the `page` array a paginated query returns. */
@@ -272,45 +904,78 @@ type PageItemOf<F> = ReturnOf<F> extends {
272
904
  page: (infer T)[];
273
905
  } ? T : unknown;
274
906
  /**
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
- */
907
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
908
+ *
909
+ * Pass `onError` (and read `error`) to see a page failure: without it the hook
910
+ * only reports `status`, and a first page that fails reads as an eternal
911
+ * `isLoading`.
912
+ *
913
+ * The query function must accept a `paginationOpts: { numItems, cursor,
914
+ * endCursor }` arg and return a `PaginationResult` (the shape
915
+ * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
916
+ * stable boundary cursors: each loaded page is a live subscription over a
917
+ * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
918
+ * Because boundaries are shared stable cursors, inserting or deleting a row in
919
+ * the middle of the list grows/shrinks the affected page in place without
920
+ * duplicating or skipping rows across page boundaries — the bug the legacy
921
+ * "first N after the previous page's last row" model suffered under live edits.
922
+ *
923
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
924
+ * it is a no-op unless `status === "CanLoadMore"`. Background split/join
925
+ * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
926
+ * `use-paginated-core.ts`).
927
+ *
928
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
929
+ * feed to its first page. The public return shape (`results` / `status` /
930
+ * `loadMore`) is unchanged from the legacy keyset implementation.
931
+ *
932
+ * There is no total-row count here, and deliberately not: `paginate()` never
933
+ * counts the tail, which is what keeps a page O(page) rather than O(table). For
934
+ * a "42 of 1,203" label, subscribe to a `ctx.db.<table>.count(where)` query with
935
+ * the same filter args via `useQuery` — it is live, so it moves with the
936
+ * list. See the pagination concept page.
937
+ */
296
938
  declare const usePaginatedQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UsePaginatedQueryOptions) => UsePaginatedQueryResult<PageItemOf<F>>;
297
939
  /**
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
- */
940
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
941
+ *
942
+ * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
943
+ * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
944
+ * inserted or deleted mid-list grows/shrinks the affected page without
945
+ * duplicating or skipping rows across boundaries — but keeps each page as its
946
+ * own inner array rather than flattening them, and adds the
947
+ * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
948
+ * shape. `fetchNextPage` appends the next page off the open-ended tail's
949
+ * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
950
+ *
951
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
952
+ * feed to its first page. The public return shape is unchanged from the legacy
953
+ * keyset implementation.
954
+ */
313
955
  declare const useInfiniteQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UseInfiniteQueryOptions) => UseInfiniteQueryResult<PageItemOf<F>>;
956
+ /** Options for {@link useLiveTopic}: the `subscribeLiveTopic` options, with the callbacks read through a ref. */
957
+ type UseLiveTopicOptions = SubscribeLiveTopicOptions;
958
+ interface UseLiveTopicResult {
959
+ /** Set when the shard refuses the subscription (403, 409, 429 and similar). */
960
+ error: LiveStreamSubscribeError | undefined;
961
+ /** The last payload delivered on the topic, or `undefined` until the first event. */
962
+ lastEvent: unknown;
963
+ }
964
+ /**
965
+ * `useLiveTopic` — follow one live topic of a `defineLiveStream` for the life of
966
+ * the component.
967
+ *
968
+ * It is a lifecycle wrapper over `subscribeLiveTopic`: the connection itself is
969
+ * shared by URL, so mounting this hook ten times still opens one stream. It
970
+ * subscribes on mount, unsubscribes on unmount, and resubscribes only when the
971
+ * connection inputs (`url`, `topic`, credentials, headers, retry tuning) change.
972
+ * Changing `onEvent` or `onError` identity does not resubscribe — the latest
973
+ * callback is read through a ref.
974
+ *
975
+ * It is a no-op during SSR: effects do not run on the server, so the hook returns
976
+ * its initial values there.
977
+ */
978
+ declare const useLiveTopic: (options: UseLiveTopicOptions) => UseLiveTopicResult;
314
979
  type CallOptions<F extends FunctionReference> = UseMutationCallOptions<unknown, unknown, ArgsOf<F>>;
315
980
  interface MutationHook<F extends FunctionReference> {
316
981
  /** The latest invocation's resolved value, or `undefined` before the first success. */
@@ -325,34 +990,43 @@ interface MutationHook<F extends FunctionReference> {
325
990
  /** Clear the latest `data`/`error` back to idle. */
326
991
  reset: () => void;
327
992
  /**
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
- */
993
+ * Bind a Convex-parity multi-query optimistic update to this mutation.
994
+ * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
995
+ * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
996
+ * is supplied in the call options, which overrides the bound one.
997
+ */
333
998
  withOptimisticUpdate: (update: OptimisticUpdate<ArgsOf<F>>) => MutationHook<F>;
334
999
  }
335
1000
  /**
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
- */
1001
+ * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
1002
+ * given mutation reference. Prefer destructuring at the call site so the React
1003
+ * linter can track dependencies on each field independently.
1004
+ *
1005
+ * Not callable: `const send = useMutation(api.x.y); send({ … })` is a `TS2349`.
1006
+ * Destructure the invoker — `const { mutate: send } = useMutation(api.x.y)`.
1007
+ *
1008
+ * Built on TanStack Query's mutation cache (the same cache the query hooks use),
1009
+ * so it composes with Query Devtools and exposes the latest call's `data`/`error`
1010
+ * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
1011
+ * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
1012
+ *
1013
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance
1014
+ * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
1015
+ * `false` only once every concurrent call has settled — and a sibling component
1016
+ * mutating the same function never affects it (TanStack's own `isPending` tracks
1017
+ * just the latest invocation).
1018
+ *
1019
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
1020
+ * call options pass straight through to `client.mutation`, which applies and
1021
+ * rolls them back against the Lunora subscription cache (Convex parity) — not
1022
+ * through TanStack's `onMutate`.
1023
+ *
1024
+ * Offline, a write the client can queue reaches `client.mutation` at once,
1025
+ * which queues it (the offline queue or a durable outbox) and paints the
1026
+ * optimistic update. A write it cannot queue (before the shard's first connect,
1027
+ * or with no WebSocket) waits until the browser is online again, then sends.
1028
+ * TanStack never retries; the queue owns replays.
1029
+ */
356
1030
  declare const useMutation: <F extends FunctionReference>(function_: F) => MutationHook<F>;
357
1031
  interface MutatorHook<TArgs> {
358
1032
  /** The latest invocation's error, or `undefined`. */
@@ -367,86 +1041,104 @@ interface MutatorHook<TArgs> {
367
1041
  reset: () => void;
368
1042
  }
369
1043
  /**
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
- */
1044
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
1045
+ * custom-mutator handle from `@lunora/db`'s `bindMutators`. The optimistic
1046
+ * overlay and server-authoritative push are owned by the bound handle (and
1047
+ * TanStack DB's optimistic-transaction layer rebases pending overlays on every
1048
+ * sync tick) — this hook only surfaces React state for the in-flight/error
1049
+ * lifecycle. Reads stay on the existing `useLiveQuery`; no new query hook is
1050
+ * needed.
1051
+ *
1052
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance,
1053
+ * so it clears only once every concurrent call has settled.
1054
+ */
381
1055
  declare const useMutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHook<TArgs>;
382
1056
  /**
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
- */
1057
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
1058
+ * during SSR, then keep it live.
1059
+ *
1060
+ * The first render returns the preloaded value (TanStack's `initialData`),
1061
+ * so the server markup and the initial client markup match — no hydration
1062
+ * mismatch, no loading flash. After mount, a WS subscription attaches so
1063
+ * later server pushes update the value just like `useQuery`.
1064
+ *
1065
+ * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
1066
+ * full dehydrate/hydrate dance because the consumer hands us the resolved
1067
+ * value directly. Apps that want to share a pre-populated QueryClient across
1068
+ * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
1069
+ * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
1070
+ *
1071
+ * Pass `onError` to surface a subscription-scoped error the server pushes (a
1072
+ * session expiry, an RLS denial). Without it such an error is dropped and the
1073
+ * hook keeps rendering the SSR snapshot as if it were live.
1074
+ *
1075
+ * The preloaded value was read for whoever was signed in when the page loaded.
1076
+ * After a sign-out or user switch retires an identity (`client.identityEpoch()`
1077
+ * above `0`), every `usePreloadedQuery` on the client (mounted then or later)
1078
+ * stops using it and returns `undefined` until the live value arrives. So does
1079
+ * every one under a `LunoraProvider` whose `client` was swapped, mounted before
1080
+ * or after the swap — hence the `T | undefined` return type. A token
1081
+ * preloaded after the switch (a client-side navigation that preloads again) is
1082
+ * ignored too and costs a loading flash: the hook cannot tell which identity a
1083
+ * token was read under.
1084
+ */
1085
+ declare const usePreloadedQuery: <T>(preloaded: Preloaded<T>, options?: {
1086
+ onError?: SubscriptionErrorCallback;
1087
+ }) => T | undefined;
1088
+ /**
1089
+ * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
1090
+ * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
1091
+ * attaches a live WS subscription on mount. It is a thin alias of
1092
+ * {@link usePreloadedQuery} so the React adapter exposes the same
1093
+ * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
1094
+ * while existing callers of `usePreloadedQuery` keep working unchanged.
1095
+ *
1096
+ * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
1097
+ * call it like a hook — at the top level of a component, unconditionally.
1098
+ */
1099
+ declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, options?: {
1100
+ onError?: SubscriptionErrorCallback;
1101
+ }) => T | undefined;
1102
+ /**
1103
+ * `usePresence` — collaborative-awareness hook, the client half of the
1104
+ * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
1105
+ * parity).
1106
+ *
1107
+ * It drives the two presence functions the server component ships:
1108
+ *
1109
+ * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
1110
+ * whenever the tab becomes visible, to upsert the caller's presence row and
1111
+ * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
1112
+ * carries the latest `data` from a ref, so `setData` takes effect on the next
1113
+ * tick without re-subscribing or resetting the timer.
1114
+ * - **listPresent** (a query): subscribed to over the live-query WS, so the
1115
+ * present-list updates reactively. Because the server patches a single row per
1116
+ * heartbeat, the client's **per-row subscription delta merge** applies just that
1117
+ * row to the cached list instead of re-sending every member — the list stays
1118
+ * cheap even with many participants heart-beating.
1119
+ *
1120
+ * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
1121
+ * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
1122
+ * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
1123
+ * the hook needs no client-side reaping.
1124
+ *
1125
+ * The two `FunctionReference`s come from your generated `api` (e.g.
1126
+ * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
1127
+ * stays decoupled from any specific app schema.
1128
+ */
1129
+ /**
1130
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
1131
+ * `definePresence().functions.heartbeat` registers).
1132
+ */
441
1133
  type HeartbeatReference = FunctionReference<"mutation", {
442
1134
  data?: Record<string, unknown>;
443
1135
  roomId: string;
444
1136
  sessionId: string;
445
1137
  }>;
446
1138
  /**
447
- * A listPresent query reference: takes `{ roomId }` and returns the array of
448
- * present members.
449
- */
1139
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
1140
+ * present members.
1141
+ */
450
1142
  type ListPresentReference = FunctionReference<"query", {
451
1143
  roomId: string;
452
1144
  }>;
@@ -460,14 +1152,22 @@ interface UsePresenceOptions<H extends HeartbeatReference, L extends ListPresent
460
1152
  /** The `api.*` reference for the presence listPresent query. */
461
1153
  listPresent: L;
462
1154
  /**
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
- */
1155
+ * Called when the `listPresent` subscription reports an error (a session
1156
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
1157
+ * failure is invisible and `present` freezes at its last value.
1158
+ */
1159
+ onError?: SubscriptionErrorCallback;
1160
+ /**
1161
+ * Stable id for this presence row. Defaults to a fresh per-mount id (one row
1162
+ * per tab). Pass a user/connection id to control deduping.
1163
+ */
466
1164
  sessionId?: string;
467
1165
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
468
1166
  shardKey?: string;
469
1167
  }
470
1168
  interface UsePresenceResult<L extends ListPresentReference> {
1169
+ /** The `listPresent` subscription's last error, or `undefined`. */
1170
+ error: SubscriptionError | undefined;
471
1171
  /** The present members for the room, as `listPresent` returns them. `undefined` until the first push. */
472
1172
  present: ReturnOf<L> | undefined;
473
1173
  /** This mount's session id (generated when not supplied). */
@@ -477,25 +1177,36 @@ interface UsePresenceResult<L extends ListPresentReference> {
477
1177
  }
478
1178
  declare const usePresence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: UsePresenceOptions<H, L>) => UsePresenceResult<L>;
479
1179
  /**
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
- */
1180
+ * Subscribe to a server query.
1181
+ *
1182
+ * Returns `undefined` until the first response lands. Pass `"skip"` for
1183
+ * `args` to short-circuit the query (no network call, no subscription).
1184
+ *
1185
+ * When the `LunoraClient` was created with `hydrateOnStart: true` and a
1186
+ * `queryCache` adapter, the first **enabled** render waits for the durable
1187
+ * read cache to finish loading. If a cached value exists for this query it
1188
+ * is fed as `initialData` so the user sees it immediately — no undefined
1189
+ * flash before the socket round-trip.
1190
+ *
1191
+ * Internally this routes through TanStack Query: the queryKey is
1192
+ * `["lunora", fn.__lunoraRef, stableWireKey(args), shardKey]` (the args are
1193
+ * encoded key-order-independently, so an args object built in a different key
1194
+ * order still dedupes, and wire-typed args get distinct entries). The
1195
+ * subscription registry shares a single WS subscription across every consumer
1196
+ * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
1197
+ *
1198
+ * Pass `onError` to surface a subscription-scoped error the server pushes (an RLS
1199
+ * denial, a query that starts failing server-side). Without it such an error is
1200
+ * dropped and the returned value just freezes at its last good result.
1201
+ */
491
1202
  declare const useQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => ReturnOf<F> | undefined;
492
1203
  interface UseRateLimitOptions {
493
1204
  /** Clock injection for tests. Defaults to `Date.now`. */
494
1205
  now?: () => number;
495
1206
  /**
496
- * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
497
- * down and `disabled` flips back automatically. Defaults to `1000`.
498
- */
1207
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
1208
+ * down and `disabled` flips back automatically. Defaults to `1000`.
1209
+ */
499
1210
  tickMs?: number;
500
1211
  }
501
1212
  interface UseRateLimitResult {
@@ -513,17 +1224,15 @@ interface UseRateLimitResult {
513
1224
  retryAfter: number;
514
1225
  }
515
1226
  /**
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
- */
1227
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
1228
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
1229
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
1230
+ * authoritative check; the server remains the source of truth.
1231
+ *
1232
+ * `config` is read on every render; pass a stable reference (module constant or
1233
+ * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
1234
+ */
524
1235
  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
1236
  interface UseStreamResult<T> {
528
1237
  /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
529
1238
  cancel: () => void;
@@ -533,24 +1242,198 @@ interface UseStreamResult<T> {
533
1242
  status: UseStreamStatus;
534
1243
  }
535
1244
  interface UseStreamOptions {
1245
+ /**
1246
+ * Opt into resume-on-reconnect for a stream the server declared `durable`.
1247
+ * The hook keeps the chunks it already has and the socket re-attaches to the
1248
+ * same run, so a dropped connection mid-generation continues instead of
1249
+ * surfacing `STREAM_DISCONNECTED`. Has no effect on an ephemeral stream.
1250
+ */
1251
+ durable?: boolean;
536
1252
  /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
537
1253
  maxBuffer?: number;
538
1254
  shardKey?: string;
539
1255
  }
540
1256
  /**
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
- */
1257
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
1258
+ * lifecycle status and a cancel function. Changing `fn` or the serialized
1259
+ * `args` resets the stream — the previous iterator is cancelled and a fresh
1260
+ * one opens with empty `chunks`.
1261
+ *
1262
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
1263
+ * (mirrors `useQuery` / `useSubscription`).
1264
+ */
549
1265
  declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: "skip" | ArgsOf<F>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
550
1266
  /**
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
- */
1267
+ * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
1268
+ * hook does not issue an initial HTTP fetch — it only delivers values that
1269
+ * the server pushes over the WS.
1270
+ *
1271
+ * A server-pushed error lands on `error` as a `LunoraError` carrying the
1272
+ * server's `code` (a bare `Error` only when the server sent no code), so
1273
+ * consumers can branch on the error kind; `onError` receives the raw
1274
+ * `SubscriptionError` in addition.
1275
+ */
555
1276
  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 };
1277
+ /**
1278
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
1279
+ * capture and speaker playback implementations injected into the hook via its
1280
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
1281
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
1282
+ * hook's transport + React-state logic and remains mockable in a non-browser
1283
+ * test env.
1284
+ */
1285
+ /**
1286
+ * The negotiated audio format the voice DO streams back. Mirrors
1287
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1288
+ * imported) so this React package never pulls in the server-only `@lunora/agent`
1289
+ * module graph.
1290
+ */
1291
+ type VoiceAudioFormat = "mp3" | "wav";
1292
+ /** Captures microphone audio and reports level / turn boundaries back to the hook. */
1293
+ interface VoiceMicrophone {
1294
+ /** Mute/unmute the mic without tearing down the capture graph. */
1295
+ setMuted: (muted: boolean) => void;
1296
+ /** Stop capture and release the media stream + audio graph. */
1297
+ stop: () => void;
1298
+ }
1299
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1300
+ interface VoiceSpeaker {
1301
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1302
+ enqueue: (audio: Uint8Array) => void;
1303
+ /** Drop everything queued and stop the current chunk (barge-in). */
1304
+ interrupt: () => void;
1305
+ /** Release the playback audio context. */
1306
+ stop: () => void;
1307
+ }
1308
+ /** Config passed to a {@link CreateMicrophone} factory. */
1309
+ interface MicrophoneConfig {
1310
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1311
+ interruptChunks: number;
1312
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1313
+ interruptThreshold: number;
1314
+ /**
1315
+ * `true` from the moment a turn is committed until it completes — the whole
1316
+ * `thinking` + `speaking` window, not just the audible half.
1317
+ *
1318
+ * It gates BOTH branches below, and the wider span is the point. Gated only
1319
+ * on "audibly speaking", turn detection kept running through the entire
1320
+ * STT+LLM window after a `commit`: room noise at the (deliberately low)
1321
+ * `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
1322
+ * `commit`, and the DO refused it with "a turn is already in progress" —
1323
+ * a refusal that returns before draining the audio buffer, so the PCM
1324
+ * captured since the first commit leaked into the next utterance.
1325
+ *
1326
+ * A genuine barge-in still works in that window: it routes through the
1327
+ * `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
1328
+ * `interruptThreshold` — an order of magnitude above `silenceThreshold` —
1329
+ * and `interrupt` is exactly what the DO tells the client to send.
1330
+ */
1331
+ isTurnActive: () => boolean;
1332
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1333
+ onAudio: (pcm: Uint8Array) => void;
1334
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1335
+ onInterrupt: () => void;
1336
+ /** The current input RMS (0–1), for a level meter. */
1337
+ onLevel: (rms: number) => void;
1338
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1339
+ onSilence: () => void;
1340
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1341
+ silenceDurationMs: number;
1342
+ /** RMS below which audio counts as silence. */
1343
+ silenceThreshold: number;
1344
+ }
1345
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1346
+ type CreateSpeaker = (config: {
1347
+ audioFormat: VoiceAudioFormat;
1348
+ }) => VoiceSpeaker;
1349
+ /**
1350
+ * The `agents.<name>Voice` reference codegen emits for a voice-enabled agent — a
1351
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1352
+ * generated member, so passing `api.agents.<name>Voice` type-checks.
1353
+ */
1354
+ type VoiceReference = FunctionReference<"stream", {
1355
+ threadKey: string;
1356
+ }, Record<string, unknown>>;
1357
+ /** The lifecycle of a voice call, mirrored to the UI. */
1358
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1359
+ /** A minimal structural subset of the DOM `WebSocket` the hook drives. */
1360
+ interface VoiceSocket {
1361
+ binaryType: string;
1362
+ close: () => void;
1363
+ onclose: ((event: unknown) => void) | null;
1364
+ onerror: ((event: unknown) => void) | null;
1365
+ onmessage: ((event: {
1366
+ data: unknown;
1367
+ }) => void) | null;
1368
+ onopen: ((event: unknown) => void) | null;
1369
+ readonly readyState: number;
1370
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1371
+ }
1372
+ type CreateSocket = (url: string) => VoiceSocket;
1373
+ interface UseVoiceAgentOptions {
1374
+ /**
1375
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1376
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1377
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1378
+ */
1379
+ createMicrophone?: CreateMicrophone;
1380
+ /**
1381
+ * Advanced/test seam: open the transport. Defaults to the WebSocket
1382
+ * implementation the client was built with (`client.getWebSocketImpl()`),
1383
+ * NOT a raw `globalThis.WebSocket`.
1384
+ */
1385
+ createSocket?: CreateSocket;
1386
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1387
+ createSpeaker?: CreateSpeaker;
1388
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1389
+ interruptChunks?: number;
1390
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1391
+ interruptThreshold?: number;
1392
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1393
+ silenceDurationMs?: number;
1394
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1395
+ silenceThreshold?: number;
1396
+ /** The thread to converse on — shared with the agent's text turns. */
1397
+ threadKey: string;
1398
+ /** The generated `api.agents.<name>Voice` reference — identifies the voice DO endpoint. */
1399
+ voice: VoiceReference;
1400
+ }
1401
+ interface UseVoiceAgentResult {
1402
+ /** The current input RMS (0–1) — drive a mic level meter. */
1403
+ audioLevel: number;
1404
+ /** `true` once the WS `ready` handshake completed. */
1405
+ connected: boolean;
1406
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1407
+ endCall: () => void;
1408
+ /** The last transport/pipeline error, or `undefined`. */
1409
+ error: Error | undefined;
1410
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1411
+ interimTranscript: string;
1412
+ /** `true` while the mic is muted. */
1413
+ isMuted: boolean;
1414
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1415
+ sendText: (text: string) => void;
1416
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1417
+ startCall: () => Promise<void>;
1418
+ /** The current call lifecycle. */
1419
+ status: VoiceStatus;
1420
+ /** Mute/unmute the microphone. Returns the new muted state. */
1421
+ toggleMute: () => boolean;
1422
+ /** The last finalized user utterance (STT result). */
1423
+ transcript: string;
1424
+ }
1425
+ /**
1426
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1427
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1428
+ * streams the agent's synthesized speech back through the browser's audio output,
1429
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1430
+ * `audioLevel`) to React state. Pass the generated `api.agents.<name>Voice`
1431
+ * reference (never a string), matching `useAgentChat`'s reference-passing style.
1432
+ *
1433
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1434
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1435
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1436
+ * `createSocket`) so the hook is drivable outside a browser.
1437
+ */
1438
+ declare const useVoiceAgent: (options: UseVoiceAgentOptions) => UseVoiceAgentResult;
1439
+ 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 UseLiveTopicOptions, type UseLiveTopicResult, 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, useLiveTopic, useLunora, useMutation, useMutator, useOrganizations, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useSignUpInvitations, useStream, useSubscription, useVoiceAgent };