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