@lunora/react 1.0.0-alpha.3 → 1.0.0-alpha.300

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