@lunora/react 1.0.0-alpha.25 → 1.0.0-alpha.251

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