@lunora/react 1.0.0-alpha.7 → 1.0.0-alpha.70

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