@lunora/react 1.0.0-alpha.27 → 1.0.0-alpha.271

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