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