@lunora/vue 1.0.0-alpha.28 → 1.0.0-alpha.280

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +23 -16
  3. package/dist/index.d.mts +1153 -241
  4. package/dist/index.d.ts +1153 -241
  5. package/dist/index.mjs +1 -13
  6. package/dist/packem_shared/AuthLoading-ZXVgXos1.mjs +1 -0
  7. package/dist/packem_shared/LUNORA_INJECTION_KEY-Bct9tKCj.mjs +1 -0
  8. package/dist/packem_shared/hydratePreloaded-DicHNxhB.mjs +1 -0
  9. package/dist/packem_shared/is-browser-BEdfLJHK.mjs +1 -0
  10. package/dist/packem_shared/scope-dispose-Mq3k4nvP.mjs +1 -0
  11. package/dist/packem_shared/subscribeToQuery-BvnA8ErG.mjs +1 -0
  12. package/dist/packem_shared/useAction-C4VLsh4M.mjs +1 -0
  13. package/dist/packem_shared/useAgent-Bp5UEoEp.mjs +1 -0
  14. package/dist/packem_shared/useAgentChat-CVgX8Z-J.mjs +1 -0
  15. package/dist/packem_shared/useAgentState-DpFm2lH0.mjs +1 -0
  16. package/dist/packem_shared/useAgentToolEvents-CWHORsCT.mjs +1 -0
  17. package/dist/packem_shared/useAuth-QDllAwZL.mjs +1 -0
  18. package/dist/packem_shared/useConnectionStatus-CCUbKnj2.mjs +1 -0
  19. package/dist/packem_shared/useFlag-xVfWC_c6.mjs +1 -0
  20. package/dist/packem_shared/useInfiniteQuery-Clqt_MYU.mjs +1 -0
  21. package/dist/packem_shared/useLiveTopic-B0HA04MY.mjs +1 -0
  22. package/dist/packem_shared/useMutation-D6PkaNaE.mjs +1 -0
  23. package/dist/packem_shared/useMutator-CO7nXlRf.mjs +1 -0
  24. package/dist/packem_shared/usePresence-Dpnb4kjv.mjs +1 -0
  25. package/dist/packem_shared/useRateLimit-zoPsflSG.mjs +1 -0
  26. package/dist/packem_shared/useStream-COVzNdKq.mjs +1 -0
  27. package/dist/packem_shared/useSubscription-cTKyOIAv.mjs +1 -0
  28. package/dist/packem_shared/useVoiceAgent-Dz1t4xgi.mjs +1 -0
  29. package/dist/server.mjs +1 -1
  30. package/dist/upload.d.mts +2 -0
  31. package/dist/upload.d.ts +2 -0
  32. package/dist/upload.mjs +1 -0
  33. package/package.json +9 -8
  34. package/dist/packem_shared/AuthLoading-DKra8yfG.mjs +0 -29
  35. package/dist/packem_shared/LUNORA_INJECTION_KEY-DQM5MgsC.mjs +0 -26
  36. package/dist/packem_shared/hydratePreloaded-Cnd2GmG1.mjs +0 -14
  37. package/dist/packem_shared/subscribeToQuery-hVYyvgOD.mjs +0 -51
  38. package/dist/packem_shared/useAuth-yXaaF-ro.mjs +0 -28
  39. package/dist/packem_shared/useConnectionStatus-DM_TOaW5.mjs +0 -20
  40. package/dist/packem_shared/useFlag-Diuk30zd.mjs +0 -108
  41. package/dist/packem_shared/useInfiniteQuery-DZMfVEuL.mjs +0 -199
  42. package/dist/packem_shared/useMutation-BKIwT8Jk.mjs +0 -29
  43. package/dist/packem_shared/useMutator-B_Ahs_ZN.mjs +0 -19
  44. package/dist/packem_shared/usePresence-VXq5yGzE.mjs +0 -59
  45. package/dist/packem_shared/useRateLimit-DlPWjcX1.mjs +0 -67
  46. package/dist/packem_shared/useSubscription-DHoCEXNh.mjs +0 -47
  47. package/dist/worker.d.mts +0 -1
  48. package/dist/worker.d.ts +0 -1
  49. package/dist/worker.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,184 +1,793 @@
1
- import { Component, Ref, InjectionKey, App, DeepReadonly, MaybeRefOrGetter, ComputedRef, ShallowRef } from 'vue';
2
- import { Preloaded, LunoraClient, User, ConnectionStatus, FunctionReference, ReturnOf, ArgsOf, MutationCallOptions, MutatorHandle } from '@lunora/client';
3
- export type { ArgsOf, FunctionReference, LunoraClient, MutationCallOptions, MutatorHandle, MutatorTransaction, OptimisticLocalStore, OptimisticUpdate, Preloaded, ReturnOf, Unsubscribe, User } from '@lunora/client';
1
+ import { Component, Ref, InjectionKey, App, MaybeRefOrGetter, ComputedRef, DeepReadonly, ShallowRef } from 'vue';
2
+ import { Preloaded, SubscriptionErrorCallback, LunoraClient, FunctionReference, ArgsOf, ActionCallOptions, ReturnOf, User, ConnectionStatus, LiveTopicOptions, LiveStreamSubscribeError, LiveTopicRef, MutationCallOptions, OnlineOnlyOption, MutatorHandle, SubscriptionError } from '@lunora/client';
3
+ export type { ArgsOf, FunctionReference, LunoraClient, MutationCallOptions, MutatorHandle, MutatorTransaction, OptimisticLocalStore, OptimisticUpdate, Preloaded, ReturnOf, SubscriptionError, SubscriptionErrorCallback, Unsubscribe, User } from '@lunora/client';
4
+ import { AuthStatus } from '@lunora/client/auth';
4
5
  import { PaginationStatus } from '@lunora/client/pagination';
5
6
  export type { PaginationResult, PaginationStatus } from '@lunora/client/pagination';
6
7
  import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
7
8
  /**
8
- * Render the default slot only after auth has settled and a token + user are
9
- * both present. Hides the slot on first render and when signed out.
10
- */
9
+ * Render the default slot once authentication has settled in the caller's
10
+ * favour — a credential is held and nothing has contradicted it.
11
+ *
12
+ * Gated on {@link isAuthenticatedStatus}, the shared contract in
13
+ * `@lunora/client/auth`, not on `user !== null`: an unreachable identity
14
+ * endpoint leaves `user` at `null` while the credential is still perfectly
15
+ * valid, and requiring a user record there hid the whole app behind
16
+ * `AuthLoading` for the length of an offline session.
17
+ */
11
18
  declare const Authenticated: Component;
12
19
  /**
13
- * Render the default slot only when auth has settled and no token is present
14
- * (the signed-out state). Hidden while the user is still loading.
15
- */
20
+ * Render the default slot only when authentication has settled and there is no
21
+ * session — no credential, or the server answered that the credential has none.
22
+ */
16
23
  declare const Unauthenticated: Component;
17
24
  /**
18
- * Render the default slot while authentication is still in progress — token is
19
- * set but `getCurrentUser()` has not yet resolved.
20
- */
25
+ * Render the default slot while authentication is still in progress — a
26
+ * credential is held and the first identity resolve has not come back yet.
27
+ */
21
28
  declare const AuthLoading: Component;
22
29
  /**
23
- * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
24
- * during SSR, then keep it live — the Vue half of PLAN4's reactive-loader
25
- * handoff.
26
- *
27
- * The returned `ref` is seeded **synchronously** from `preloaded.value`, so the
28
- * very first read (during hydration) shows the server value: no loading flash,
29
- * no hydration mismatch. After seeding it opens a WebSocket subscription on the
30
- * same `(functionPath, args, shardKey)` the SSR loader used, so every later
31
- * server delta updates the ref exactly like `useQuery`.
32
- *
33
- * The subscription tears down with the surrounding effect scope (component
34
- * unmount or `effectScope().stop()`), inherited from `subscribeToQuery`.
35
- */
36
- declare const hydratePreloaded: <T>(preloaded: Preloaded<T>) => Ref<T | undefined>;
37
- /**
38
- * Injection key carrying the {@link LunoraClient} down the component tree.
39
- * Exported so advanced consumers can inject it by hand; most apps use
40
- * {@link createLunora} or {@link provideLunora}.
41
- */
30
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
31
+ * during SSR, then keep it live — the Vue half of PLAN4's reactive-loader
32
+ * handoff.
33
+ *
34
+ * The returned `ref` is seeded **synchronously** from `preloaded.value`, so the
35
+ * very first read (during hydration) shows the server value: no loading flash,
36
+ * no hydration mismatch. After seeding it opens a WebSocket subscription on the
37
+ * same `(functionPath, args, shardKey)` the SSR loader used, so every later
38
+ * server delta updates the ref exactly like `useQuery`.
39
+ *
40
+ * The subscription tears down with the surrounding effect scope (component
41
+ * unmount or `effectScope().stop()`), inherited from `subscribeToQuery`.
42
+ *
43
+ * Pass `onError` to surface a subscription-scoped error the server pushes (a
44
+ * session expiry, an RLS denial). Without it such an error is dropped and the
45
+ * ref keeps rendering the SSR snapshot as if it were live.
46
+ *
47
+ * The preloaded value was read for whoever was signed in when the page loaded.
48
+ * After a sign-out or user switch retires that identity
49
+ * (`client.identityEpoch() > 0`), every `hydratePreloaded` on the client (mounted
50
+ * then or later) stops using it and holds `undefined` until the live value
51
+ * arrives — matching `@lunora/react`'s `usePreloadedQuery`. The ref is typed
52
+ * `Ref<T | undefined>` like `useQuery`, so guard for that window.
53
+ */
54
+ declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, options?: {
55
+ onError?: SubscriptionErrorCallback;
56
+ }) => Ref<T | undefined>;
57
+ /**
58
+ * Injection key carrying the {@link LunoraClient} down the component tree.
59
+ * Exported so advanced consumers can inject it by hand; most apps use
60
+ * {@link createLunora} or {@link provideLunora}.
61
+ */
42
62
  declare const LUNORA_INJECTION_KEY: InjectionKey<LunoraClient>;
43
63
  /**
44
- * Vue plugin form: `app.use(createLunora(client))`. Mirrors the React
45
- * `LunoraProvider` — establishes the single app-wide client every composable
46
- * resolves through {@link useLunora}.
47
- *
48
- * The client is framework-neutral (`@lunora/client`): it owns the WebSocket
49
- * transport, subscription registry, offline queue, and delta-merge. This plugin
50
- * only wires it into Vue's `provide`/`inject` graph (read it with
51
- * {@link useLunora}); it adds no React, no store, and no extra reactivity layer.
52
- */
64
+ * Vue plugin form: `app.use(createLunora(client))`. Mirrors the React
65
+ * `LunoraProvider` — establishes the single app-wide client every composable
66
+ * resolves through {@link useLunora}.
67
+ *
68
+ * The client is framework-neutral (`@lunora/client`): it owns the WebSocket
69
+ * transport, subscription registry, offline queue, and delta-merge. This plugin
70
+ * only wires it into Vue's `provide`/`inject` graph (read it with
71
+ * {@link useLunora}); it adds no React, no store, and no extra reactivity layer.
72
+ */
53
73
  declare const createLunora: (client: LunoraClient) => {
54
74
  install: (app: App) => void;
55
75
  };
56
76
  /**
57
- * Composition-API form: call inside a parent component's `setup()` to provide
58
- * the client to its subtree. The counterpart to `app.use(createLunora(client))`
59
- * when you'd rather scope the client to a subtree than the whole app. Must run
60
- * synchronously inside `setup()` (Vue's `provide` constraint).
61
- */
77
+ * Composition-API form: call inside a parent component's `setup()` to provide
78
+ * the client to its subtree. The counterpart to `app.use(createLunora(client))`
79
+ * when you'd rather scope the client to a subtree than the whole app. Must run
80
+ * synchronously inside `setup()` (Vue's `provide` constraint).
81
+ */
62
82
  declare const provideLunora: (client: LunoraClient) => void;
63
83
  /**
64
- * Read the {@link LunoraClient} from the nearest provider — the Vue counterpart
65
- * to `@lunora/react`/`@lunora/solid`'s `useLunora`. Throws with a clear message
66
- * when called outside a `createLunora`/`provideLunora` scope so the failure
67
- * points at the missing provider rather than a later `undefined` deref.
68
- */
84
+ * Read the {@link LunoraClient} from the nearest provider — the Vue counterpart
85
+ * to `@lunora/react`/`@lunora/solid`'s `useLunora`. Throws with a clear message
86
+ * when called outside a `createLunora`/`provideLunora` scope so the failure
87
+ * points at the missing provider rather than a later `undefined` deref.
88
+ */
69
89
  declare const useLunora: () => LunoraClient;
70
90
  /** Options shared by the live-query composables. */
71
91
  interface UseQueryOptions {
92
+ /**
93
+ * Called when the server pushes a subscription-scoped error (an RLS denial, a
94
+ * query that starts failing server-side). Without a handler such an error has
95
+ * nowhere to go and the ref simply freezes at its last good value.
96
+ */
97
+ onError?: SubscriptionErrorCallback;
72
98
  /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
73
99
  shardKey?: string;
74
100
  }
101
+ /**
102
+ * The reactive handle returned by {@link useAction} — the Vue counterpart to
103
+ * React's `useAction`, re-expressed with refs. The surface is identical across
104
+ * the Lunora adapters (`@lunora/solid`, `/svelte`): `data`/`error`/`pending`
105
+ * are refs you read in a template, and `call` is an awaitable that resolves with
106
+ * the server value (or rejects).
107
+ */
108
+ interface ActionHandle<F extends FunctionReference> {
109
+ /** Invoke the action. Resolves with the server value; rejects on failure. */
110
+ call: (args: ArgsOf<F>, options?: ActionCallOptions) => Promise<ReturnOf<F>>;
111
+ /** The latest invocation's resolved value, or `undefined` before the first success. */
112
+ data: Ref<ReturnOf<F> | undefined>;
113
+ /** The latest invocation's error, or `undefined`. */
114
+ error: Ref<Error | undefined>;
115
+ /** `true` while ANY invocation from this handle is in flight (ref-counted, so overlapping calls compose). */
116
+ pending: Ref<boolean>;
117
+ /** Clear the latest `data`/`error` back to idle. */
118
+ reset: () => void;
119
+ }
120
+ /**
121
+ * Returns a reactive {@link ActionHandle} for the given action reference — the
122
+ * Vue equivalent of React's `useAction`.
123
+ *
124
+ * Actions were the one procedure kind with no adapter hook: `useQuery` and
125
+ * `useMutation` shipped in every adapter and nothing covered actions, so each
126
+ * app re-derived the same pending/error wrapper by hand.
127
+ *
128
+ * **Narrower than `useMutation` on purpose:** there are no `optimistic` /
129
+ * `optimisticUpdate` call options. An optimistic update patches the subscription
130
+ * cache on the assumption a write will land; an action is not a write — it runs
131
+ * in the Worker, may call a third party, and has no declared effect on any
132
+ * query. Offering the option would imply a rollback guarantee nothing can
133
+ * honour.
134
+ *
135
+ * `pending` is ref-counted across overlapping invocations of THIS handle, so it
136
+ * flips back to `false` only once every concurrent call has settled. That
137
+ * orchestration is the shared `createCallRunner` from `@lunora/client`; only the
138
+ * refs are adapter-specific.
139
+ *
140
+ * `data`/`error` follow the adapter-wide contract: both track the LATEST
141
+ * invocation (an earlier call settling later cannot clobber a newer one), a
142
+ * success clears `error`, and a failure leaves the previous `data` in place so a
143
+ * transient error does not blank the view. `reset()` clears both; it does not
144
+ * cancel an in-flight call, whose result still lands.
145
+ */
146
+ declare const useAction: <F extends FunctionReference>(function_: F) => ActionHandle<F>;
147
+ /**
148
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
149
+ * `@lunora/agent`'s `AgentThreadStatus` — re-declared here (rather than imported)
150
+ * so this Vue entry never pulls in the server-only `@lunora/agent` module graph
151
+ * (the adapter stays Vue + `@lunora/client` only). Keep in sync with
152
+ * `packages/agent/src/types.ts`.
153
+ */
154
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
155
+ /**
156
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
157
+ * subset of the persisted thread row — every field beyond `status` is optional so
158
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
159
+ * `agent_threads` table in `packages/agent/src/component.ts`.
160
+ */
161
+ interface AgentThreadRecord {
162
+ createdAt?: number;
163
+ /**
164
+ * The failure message when `status === "error"`, `null` once a later run
165
+ * cleared it, absent on a thread that has never failed. Read it for
166
+ * truthiness — `null` and absent both mean "no error".
167
+ */
168
+ error?: null | string;
169
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
170
+ instanceId?: string;
171
+ messageCount?: number;
172
+ /** The verified thread owner, when the run was started with one. */
173
+ owner?: string;
174
+ status: AgentThreadStatus;
175
+ title?: string;
176
+ updatedAt?: number;
177
+ }
178
+ /**
179
+ * The `agents.agentThread` reference the composable subscribes to for live thread
180
+ * state (status + the in-flight `instanceId`). A structural subset of the
181
+ * generated `api.agents` surface, so the whole generated `api` object is
182
+ * assignable.
183
+ */
184
+ interface UseAgentApi {
185
+ agents: {
186
+ agentThread: FunctionReference<"query", {
187
+ key: string;
188
+ }, Record<string, unknown> | undefined>;
189
+ };
190
+ }
191
+ interface UseAgentOptions {
192
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
193
+ api: UseAgentApi;
194
+ /**
195
+ * Optional app mutation over the agent's cancel path
196
+ * (`ctx.agents.<name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
197
+ * When omitted (or no run is in flight) {@link UseAgentResult.cancel} is a
198
+ * no-op.
199
+ */
200
+ cancel?: FunctionReference<"mutation">;
201
+ /**
202
+ * Called when the live thread subscription reports an error (a session
203
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
204
+ * failure is invisible and `thread` / `status` are cleared until a later frame arrives.
205
+ */
206
+ onError?: SubscriptionErrorCallback;
207
+ /**
208
+ * The app mutation that starts (or continues) a run — a thin wrapper over
209
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
210
+ * {@link UseAgentOptions.runArgs} and the per-call args.
211
+ */
212
+ run: FunctionReference<"mutation">;
213
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
214
+ runArgs?: Record<string, unknown>;
215
+ /** The thread to observe and drive — may be a plain value, `ref`, or getter (a reactive source re-subscribes). */
216
+ threadKey: MaybeRefOrGetter<string>;
217
+ }
218
+ interface UseAgentResult {
219
+ /**
220
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
221
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
222
+ */
223
+ cancel: () => Promise<void>;
224
+ /** The live thread subscription's last error, or `undefined`. */
225
+ error: Ref<Error | undefined>;
226
+ /** `true` while a `run` invocation is in flight. */
227
+ pending: Readonly<Ref<boolean>>;
228
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
229
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
230
+ /** The live thread status, or `undefined` before the thread exists. */
231
+ status: ComputedRef<AgentThreadStatus | undefined>;
232
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
233
+ thread: ComputedRef<AgentThreadRecord | undefined>;
234
+ }
235
+ /**
236
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
237
+ * chat message surface. Composes `useSubscription(api.agents.agentThread)` for
238
+ * live state and `useMutation` for the run/cancel writes — the Vue counterpart to
239
+ * React's `useAgent`, re-expressed with refs. For the full conversation surface
240
+ * (durable history + streaming + approvals) use `useAgentChat`.
241
+ *
242
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
243
+ * `ctx.agents.<name>.run` / `.cancel`, so the composable hard-codes no function
244
+ * names beyond the `agents:*` surface. `threadKey` may be reactive — a changing
245
+ * key re-subscribes to the new thread.
246
+ */
247
+ declare const useAgent: (options: UseAgentOptions) => UseAgentResult;
248
+ /**
249
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
250
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
251
+ * re-declared here (rather than imported) so this Vue entry never pulls in the
252
+ * server-only `@lunora/agent` module graph. Keep in sync with the
253
+ * `agent_messages` table in `packages/agent/src/component.ts`.
254
+ */
255
+ interface AgentChatMessage {
256
+ content: string;
257
+ createdAt?: number;
258
+ /**
259
+ * `true` for a client-side optimistic user message not yet acknowledged by
260
+ * the server. Cleared once the durable history carries the matching user turn.
261
+ */
262
+ optimistic?: boolean;
263
+ role: "assistant" | "system" | "tool" | "user";
264
+ seq: number;
265
+ /** Approval or secret-request lifecycle marker on a human-in-the-loop tool message. */
266
+ status?: "approved" | "awaiting_approval" | "awaiting_secret" | "rejected";
267
+ toolCallId?: string;
268
+ toolCalls?: ReadonlyArray<{
269
+ id: string;
270
+ input: unknown;
271
+ name: string;
272
+ }>;
273
+ toolName?: string;
274
+ }
275
+ /**
276
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
277
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
278
+ * {@link UseAgentChatResult.streamingText} live and are never replayed; the
279
+ * persisted assistant message stays the single source of truth.
280
+ */
281
+ interface AgentTokenDelta {
282
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
283
+ kind?: "token";
284
+ /** The incremental text chunk the model just produced. */
285
+ text: string;
286
+ /** The thread this delta belongs to. */
287
+ threadKey: string;
288
+ /** The zero-based index of the turn producing the delta. */
289
+ turn: number;
290
+ }
291
+ /**
292
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
293
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
294
+ * surfaced by `useAgentToolEvents`, ignored by {@link UseAgentChatResult.streamingText}.
295
+ */
296
+ interface AgentProgressEvent {
297
+ /** The arbitrary, JSON-serializable payload the tool reported. */
298
+ data: unknown;
299
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
300
+ kind: "progress";
301
+ /** The thread this event belongs to. */
302
+ threadKey: string;
303
+ /** The tool call this progress belongs to. */
304
+ toolCallId: string;
305
+ }
306
+ /**
307
+ * A single event on the agent's live-only channel — a streamed token delta or a
308
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
309
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
310
+ * it unset).
311
+ */
312
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
313
+ /** The `agents:agentMessages` reference — live durable thread history. */
314
+ type AgentMessagesReference$1 = FunctionReference<"query", {
315
+ key: string;
316
+ limit?: number;
317
+ }, ReadonlyArray<Record<string, unknown>>>;
318
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
319
+ type AgentApprovalReference = FunctionReference<"mutation", {
320
+ decision: "approve" | "approve_for_thread" | "reject";
321
+ instanceId: string;
322
+ note?: string;
323
+ threadKey: string;
324
+ toolCallId: string;
325
+ }, {
326
+ resolved: boolean;
327
+ }>;
328
+ /** The `agents:agentSupplySecret` reference — stores a person's value for a paused `requestSecretTool` call. */
329
+ type AgentSupplySecretReference = FunctionReference<"mutation", {
330
+ secret: string;
331
+ threadKey: string;
332
+ toolCallId: string;
333
+ }, {
334
+ resolved: boolean;
335
+ }>;
336
+ /** The `agents:agentDeclineSecret` reference — refuses a paused `requestSecretTool` call. */
337
+ type AgentDeclineSecretReference = FunctionReference<"mutation", {
338
+ threadKey: string;
339
+ toolCallId: string;
340
+ }, {
341
+ resolved: boolean;
342
+ }>;
343
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
344
+ type AgentThreadReference = FunctionReference<"query", {
345
+ key: string;
346
+ }, Record<string, unknown> | undefined>;
347
+ /** A tool approved for the rest of a thread, as `agents:agentApprovalGrants` lists it. */
348
+ interface AgentApprovalGrant {
349
+ createdAt: number;
350
+ toolName: string;
351
+ }
352
+ /** The `agents:agentApprovalGrants` reference — live thread-scoped approval grants. */
353
+ type AgentApprovalGrantsReference = FunctionReference<"query", {
354
+ key: string;
355
+ }, ReadonlyArray<AgentApprovalGrant>>;
356
+ /** The `agents:agentRevokeApprovalGrant` reference — removes a thread-scoped approval grant. */
357
+ type AgentRevokeApprovalGrantReference = FunctionReference<"mutation", {
358
+ threadKey: string;
359
+ toolName: string;
360
+ }, {
361
+ revoked: boolean;
362
+ }>;
363
+ /**
364
+ * An app stream reference that tees the agent's in-flight live events, keyed by
365
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
366
+ * sink — tool progress events; this composable consumes only the token arm.
367
+ */
368
+ type AgentTokenStreamReference = FunctionReference<"stream", {
369
+ key: string;
370
+ }, AgentLiveEvent>;
371
+ /**
372
+ * The `agents.*` reference surface the chat composable reads. A structural subset
373
+ * of the generated `api.agents`, so the whole generated `api` object is
374
+ * assignable.
375
+ */
376
+ interface UseAgentChatApi {
377
+ agents: {
378
+ agentApprovalGrants: AgentApprovalGrantsReference;
379
+ agentDeclineSecret: AgentDeclineSecretReference;
380
+ agentMessages: AgentMessagesReference$1;
381
+ agentResolveApproval: AgentApprovalReference;
382
+ agentRevokeApprovalGrant: AgentRevokeApprovalGrantReference;
383
+ agentSupplySecret: AgentSupplySecretReference;
384
+ agentThread: AgentThreadReference;
385
+ };
386
+ }
387
+ interface UseAgentChatOptions {
388
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
389
+ api: UseAgentChatApi;
390
+ /**
391
+ * Optional app mutation over the agent's cancel path
392
+ * (`ctx.agents.<name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
393
+ * When omitted (or no run is in flight) {@link UseAgentChatResult.cancel} is a
394
+ * no-op.
395
+ */
396
+ cancel?: FunctionReference<"mutation">;
397
+ /** History depth forwarded to `agents:agentMessages`. */
398
+ limit?: number;
399
+ /**
400
+ * Called when the live history, thread, or grants subscription reports an error (a
401
+ * session expiry, an RLS denial). Without it — and without reading `error` —
402
+ * such a failure is invisible and `messages` / `status` are cleared until a later frame arrives.
403
+ */
404
+ onError?: SubscriptionErrorCallback;
405
+ /**
406
+ * The app mutation that starts (or continues) a run — a thin wrapper over
407
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
408
+ * {@link UseAgentChatOptions.sendArgs} and the per-call args.
409
+ */
410
+ send: FunctionReference<"mutation">;
411
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
412
+ sendArgs?: Record<string, unknown>;
413
+ /**
414
+ * Optional live token-delta stream — an app stream function that tees the
415
+ * agent's in-flight deltas. When omitted {@link UseAgentChatResult.streamingText}
416
+ * stays empty and the UI updates message-by-message from durable history.
417
+ */
418
+ stream?: AgentTokenStreamReference;
419
+ /** The thread to observe and continue — may be a plain value, `ref`, or getter (a reactive source re-subscribes). */
420
+ threadKey: MaybeRefOrGetter<string>;
421
+ }
422
+ interface UseAgentChatResult {
423
+ /** The tools approved for the rest of this thread, live. Empty until the grants subscription answers. */
424
+ approvalGrants: ComputedRef<ReadonlyArray<AgentApprovalGrant>>;
425
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
426
+ approve: (toolCallId: string, note?: string) => Promise<void>;
427
+ /**
428
+ * Approve a paused tool call and grant that tool for the rest of the thread, so
429
+ * later calls to it run without pausing. Undo with {@link UseAgentChatResult.revokeGrant}.
430
+ */
431
+ approveForThread: (toolCallId: string, note?: string) => Promise<void>;
432
+ /**
433
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
434
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
435
+ */
436
+ cancel: () => Promise<void>;
437
+ /** Refuse a paused `requestSecretTool` call: the run resumes with a "declined" result. */
438
+ declineSecret: (toolCallId: string) => Promise<void>;
439
+ /** The history, thread, or grants subscription's last error, or `undefined`. */
440
+ error: ComputedRef<Error | undefined>;
441
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
442
+ messages: ComputedRef<ReadonlyArray<AgentChatMessage>>;
443
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
444
+ reject: (toolCallId: string, note?: string) => Promise<void>;
445
+ /** Remove a thread-scoped approval grant so the tool's gate applies again to later calls. */
446
+ revokeGrant: (toolName: string) => Promise<void>;
447
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
448
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
449
+ /** The live thread status, or `undefined` before the thread exists. */
450
+ status: ComputedRef<AgentThreadStatus | undefined>;
451
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
452
+ streamingText: ComputedRef<string>;
453
+ /**
454
+ * Give a paused `requestSecretTool` call its value. Always sent online-only: the
455
+ * value is never queued, persisted or replayed, and the call rejects with
456
+ * `OFFLINE_NOT_QUEUED` while the connection is down. The composable keeps no copy;
457
+ * a failure rethrows the original error.
458
+ */
459
+ supplySecret: (toolCallId: string, secret: string) => Promise<void>;
460
+ }
461
+ /**
462
+ * A first-class agent chat surface: live durable history + in-flight token
463
+ * streaming + the send / approve / reject / secret / cancel writes, keyed by `threadKey` —
464
+ * the Vue counterpart to React's `useAgentChat`, re-expressed with refs.
465
+ *
466
+ * It composes the existing primitives rather than adding transport:
467
+ * `useSubscription(api.agents.agentMessages)` for durable history,
468
+ * `useSubscription(api.agents.agentThread)` for live status + the in-flight
469
+ * `instanceId`, {@link useStream} over an app token stream for in-flight deltas,
470
+ * and `useMutation` for the writes (`api.agents.agentResolveApproval` for
471
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*`
472
+ * surface is hard-coded — `send`/`cancel`/`stream` stay generic references.
473
+ *
474
+ * A `send` optimistically appends the user turn so it renders immediately; the
475
+ * optimistic row clears once the durable history carries the acknowledged turn.
476
+ * `streamingText` is live-only: it holds the current turn's streamed text and
477
+ * empties as soon as that turn's assistant message lands in `messages` (the
478
+ * persisted message is the source of truth), consistent with the loop's
479
+ * replay-safe, live-only delta design.
480
+ */
481
+ declare const useAgentChat: (options: UseAgentChatOptions) => UseAgentChatResult;
482
+ /**
483
+ * The `agents.agentState` reference the composable subscribes to for the thread's
484
+ * live synced state. A structural subset of the generated `api.agents` surface
485
+ * (like `UseAgentApi` for `agentThread`), so the whole generated `api` object is
486
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type is
487
+ * mirrored by the composable's generic `T`, since codegen pins the reference
488
+ * return as an optional record (it never evaluates agent config).
489
+ */
490
+ interface UseAgentStateApi {
491
+ agents: {
492
+ agentState: FunctionReference<"query", {
493
+ key: string;
494
+ }, Record<string, unknown> | undefined>;
495
+ };
496
+ }
497
+ interface UseAgentStateOptions {
498
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
499
+ api: UseAgentStateApi;
500
+ /** The thread whose synced state to observe — may be a plain value, `ref`, or getter (a reactive source re-subscribes). */
501
+ threadKey: MaybeRefOrGetter<string>;
502
+ }
503
+ interface UseAgentStateResult<T> {
504
+ /** The subscription error, if the live channel reported one. */
505
+ error: Ref<Error | undefined>;
506
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
507
+ state: ComputedRef<T | undefined>;
508
+ }
509
+ /**
510
+ * Subscribe to an agent thread's synced state — the `setState`-style value a tool
511
+ * writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`. A
512
+ * thin wrapper over `useSubscription(api.agents.agentState, { key })`: the server
513
+ * pushes a fresh frame whenever the state changes (the dedicated query's
514
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
515
+ * `state` updates only on a real `setState`. The Vue counterpart to React's
516
+ * `useAgentState`, re-expressed with refs.
517
+ *
518
+ * Generic over the app's state shape (`useAgentState` with a `SupportState` type
519
+ * argument, itself a record) — the reference is typed as an optional record
520
+ * because codegen cannot see the per-agent state type; the generic casts to `T`.
521
+ * The `extends` bound (not
522
+ * a bare unbounded type parameter) is required: this `.ts` file is parsed
523
+ * JSX-aware by the bundler, where an unbounded type-param arrow is ambiguous with
524
+ * a JSX element.
525
+ */
526
+ declare const useAgentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: UseAgentStateOptions) => UseAgentStateResult<T>;
527
+ /** The `agents:agentMessages` reference — live durable thread history. */
528
+ type AgentMessagesReference = FunctionReference<"query", {
529
+ key: string;
530
+ limit?: number;
531
+ }, ReadonlyArray<Record<string, unknown>>>;
532
+ /**
533
+ * An app stream reference that tees the agent's in-flight live events, keyed by
534
+ * thread. Carries token deltas and tool progress events; this composable consumes
535
+ * only the progress arm (`kind === "progress"`).
536
+ */
537
+ type AgentLiveStreamReference = FunctionReference<"stream", {
538
+ key: string;
539
+ }, AgentLiveEvent>;
540
+ /**
541
+ * The `agents.*` reference surface the tool-events composable reads. A structural
542
+ * subset of the generated `api.agents`, so the whole generated `api` object is
543
+ * assignable.
544
+ */
545
+ interface UseAgentToolEventsApi {
546
+ agents: {
547
+ agentMessages: AgentMessagesReference;
548
+ };
549
+ }
550
+ interface UseAgentToolEventsOptions {
551
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
552
+ api: UseAgentToolEventsApi;
553
+ /** History depth forwarded to `agents:agentMessages`. */
554
+ limit?: number;
555
+ /**
556
+ * Optional live event stream — the same app stream function `useAgentChat`
557
+ * uses. When supplied, ephemeral `ctx.reportProgress(...)` events for the
558
+ * thread are surfaced as `{ type: "progress" }` entries; when omitted only the
559
+ * durable lifecycle (call / result / awaiting-approval / awaiting-secret) is returned.
560
+ */
561
+ stream?: AgentLiveStreamReference;
562
+ /** The thread whose tool activity to observe — may be a plain value, `ref`, or getter (a reactive source re-subscribes). */
563
+ threadKey: MaybeRefOrGetter<string>;
564
+ }
565
+ /**
566
+ * A single tool-lifecycle event for a thread. The durable arms
567
+ * (`call`/`result`/`awaiting-approval`/`awaiting-secret`) are derived from `agents:agentMessages`
568
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
569
+ * stream and has no `seq`. Discriminate on `type`.
570
+ */
571
+ type AgentToolEvent = {
572
+ data: unknown;
573
+ toolCallId: string;
574
+ type: "progress";
575
+ } | {
576
+ input: unknown;
577
+ seq: number;
578
+ toolCallId: string;
579
+ toolName: string;
580
+ type: "call";
581
+ } | {
582
+ output: string;
583
+ seq: number;
584
+ status?: "approved" | "rejected";
585
+ toolCallId?: string;
586
+ toolName?: string;
587
+ type: "result";
588
+ } | {
589
+ seq: number;
590
+ toolCallId?: string;
591
+ toolName?: string;
592
+ type: "awaiting-approval";
593
+ } | {
594
+ seq: number;
595
+ toolCallId?: string;
596
+ toolName?: string;
597
+ type: "awaiting-secret";
598
+ };
599
+ interface UseAgentToolEventsResult {
600
+ /**
601
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
602
+ * followed by any in-flight ephemeral progress events, recomputed from the live
603
+ * subscription + stream. Treat as derived, not identity-stable.
604
+ */
605
+ events: ComputedRef<ReadonlyArray<AgentToolEvent>>;
606
+ }
607
+ /**
608
+ * A focused view of a thread's tool activity: tool calls, their results,
609
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
610
+ * without the full chat message surface. The Vue counterpart to React's
611
+ * `useAgentToolEvents`, re-expressed as a `computed`.
612
+ *
613
+ * It composes the existing primitives rather than adding transport:
614
+ * `useSubscription(api.agents.agentMessages)` for the durable lifecycle and
615
+ * {@link useStream} over the optional app event stream for ephemeral progress.
616
+ * Progress events are live-only (the durable path never emits them): they ride
617
+ * the same sink as token deltas and are surfaced here, correlated to their tool
618
+ * call by `toolCallId`. For the conversational surface (messages + streaming text
619
+ * + approvals) use `useAgentChat`; this composable is the tool-observability slice.
620
+ */
621
+ declare const useAgentToolEvents: (options: UseAgentToolEventsOptions) => UseAgentToolEventsResult;
75
622
  interface UseAuthResult {
76
623
  setToken: (token: string | null) => void;
624
+ /**
625
+ * The resolved auth state. Branch on this, not on `user === null` — see the
626
+ * contract in `@lunora/client/auth`; `user` is `null` both when signed out
627
+ * and when a held credential's identity could not be resolved.
628
+ */
629
+ status: DeepReadonly<Ref<AuthStatus>>;
77
630
  token: DeepReadonly<Ref<string | null>>;
78
631
  user: DeepReadonly<Ref<User | null>>;
79
632
  }
80
633
  /**
81
- * Token + identity plumbing for Vue. `token` is a readonly ref tracking the
82
- * client's auth token; `user` is a readonly ref resolved from `getCurrentUser()`
83
- * whenever the token changes. `setToken(jwt)` after sign-in makes subsequent
84
- * RPC calls carry the `Authorization` header.
85
- *
86
- * Multiple `useAuth` instances within the same effect scope share a single
87
- * per-client identity store (from `@lunora/client/auth`) — a `setToken` from
88
- * one component re-renders every watcher with the freshly-resolved user.
89
- */
634
+ * Token + identity plumbing for Vue. `token` is a readonly ref tracking the
635
+ * client's auth token; `user` is a readonly ref resolved from `getCurrentUser()`
636
+ * whenever the token changes. `setToken(jwt)` after sign-in makes subsequent
637
+ * RPC calls carry the `Authorization` header.
638
+ *
639
+ * Multiple `useAuth` instances within the same effect scope share a single
640
+ * per-client identity store (from `@lunora/client/auth`) — a `setToken` from
641
+ * one component re-renders every watcher with the freshly-resolved user.
642
+ *
643
+ * Both subscribes are client-only, for the same reason as `useFlags`: this
644
+ * runs synchronously inside `setup()` during `renderToString`, and that render
645
+ * scope is never stopped, so `onScopeDispose` never fires. For the identity
646
+ * subscribe that is not just a stray listener — the store kicks off
647
+ * `getCurrentUser()` on its first subscriber, so an unguarded server render
648
+ * issues a round-trip against a client whose URL does not resolve there. Both
649
+ * refs still hold the client's current values; live updates start at hydration.
650
+ */
90
651
  declare const useAuth: () => UseAuthResult;
91
652
  /**
92
- * Reactive view of the client's aggregate live-socket status across all shard
93
- * connections, exposed as a read-only `ref`. The value transitions through
94
- * `idle` → `connecting` → `connected` → `offline` as sockets open and drop —
95
- * use it to drive a connection indicator so an operator can tell a healthy live
96
- * channel from a silently-dropped one. The Vue-idiomatic equivalent of
97
- * `@lunora/react`'s `useConnectionStatus`.
98
- *
99
- * Teardown is wired to the active effect scope (`onScopeDispose`), so the
100
- * status listener is released on component unmount (or `effectScope().stop()`).
101
- * Call inside `setup()` / an active effect scope.
102
- */
653
+ * Reactive view of the client's aggregate live-socket status across all shard
654
+ * connections, exposed as a read-only `ref`. The value transitions through
655
+ * `idle` → `connecting` → `connected` → `offline` as sockets open and drop —
656
+ * use it to drive a connection indicator so an operator can tell a healthy live
657
+ * channel from a silently-dropped one. The Vue-idiomatic equivalent of
658
+ * `@lunora/react`'s `useConnectionStatus`.
659
+ *
660
+ * Teardown is wired to the active effect scope (`onScopeDispose`), so the
661
+ * status listener is released on component unmount (or `effectScope().stop()`).
662
+ * Call inside `setup()` / an active effect scope.
663
+ *
664
+ * Client-only, for the same reason as `useFlags`: this runs synchronously
665
+ * inside `setup()` during `renderToString`, and that render scope is never
666
+ * stopped — `onScopeDispose` therefore never fires and an unguarded listener
667
+ * would stay registered on the client for the lifetime of the server process,
668
+ * one per rendered request. The ref still holds the client's current status,
669
+ * which is what the SSR HTML should show; live updates start at hydration.
670
+ */
103
671
  declare const useConnectionStatus: () => Readonly<Ref<ConnectionStatus>>;
104
- /** A targeting context merged on top of the app's default (`defineFlags({ identify })`). */
105
- type FlagContext = Record<string, unknown>;
106
672
  /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
107
673
  type FlagValue = boolean | number | string | {
108
674
  [key: string]: unknown;
109
675
  } | unknown[] | null;
110
676
  /**
111
- * Subscribe to a single feature flag, live over Lunora's WebSocket.
112
- *
113
- * The returned `ref` holds `defaultValue` until the first evaluation lands, then
114
- * the server's resolved value — re-pushed whenever the provider re-evaluates
115
- * (e.g. a flag is toggled in Cloudflare Flagship). The flag's kind is inferred
116
- * from `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean
117
- * and `useFlag("hero", "control")` a string.
118
- *
119
- * `key` and `context` may be plain values, `ref`s, or getters: passing a reactive
120
- * source makes the subscription reactive — when it changes the old subscription
121
- * is torn down and a fresh one opens. `context` supplies a per-call targeting
122
- * context merged on top of the app's default `identify` targeting key.
123
- *
124
- * Evaluation runs through whatever OpenFeature provider the app wired in
125
- * `lunora/flags.ts`; the read never throws — a provider error resolves the
126
- * default (the same fail-open contract as server-side `ctx.flags`). Call inside
127
- * `setup()` (or any active effect scope); the subscription tears down on unmount.
128
- */
129
- declare const useFlag: <T extends FlagValue>(key: MaybeRefOrGetter<string>, defaultValue: T, context?: MaybeRefOrGetter<FlagContext | undefined>) => Readonly<Ref<T>>;
130
- /**
131
- * Subscribe to several feature flags at once, live over Lunora's WebSocket.
132
- *
133
- * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
134
- * default, and the returned `ref` holds the same-shaped record with resolved
135
- * values (the defaults until each evaluation lands). A single `context` applies
136
- * to every flag and may be reactive. This is the batched form of {@link useFlag}
137
- * — one watcher manages one subscription per key.
138
- */
139
- declare const useFlags: <T extends Record<string, FlagValue>>(flags: T, context?: MaybeRefOrGetter<FlagContext | undefined>) => Readonly<Ref<T>>;
140
- /**
141
- * The reactive handle returned by {@link useMutation} — the Vue counterpart to
142
- * React's `useMutation`, re-expressed with refs. The surface is identical across
143
- * the Lunora adapters (`@lunora/solid`, `/svelte`): `data`/`error`/`pending` are
144
- * refs you read in a template, `mutate` is an awaitable that resolves with the
145
- * server value (or rejects). Per-call `optimistic` / `optimisticUpdate` options
146
- * pass straight through to `client.mutation`.
147
- */
677
+ * Subscribe to a single feature flag, live over Lunora's WebSocket.
678
+ *
679
+ * The returned `ref` holds `defaultValue` until the first evaluation lands, then
680
+ * the server's resolved value — re-pushed whenever the provider re-evaluates
681
+ * (e.g. a flag is toggled in Cloudflare Flagship). The flag's kind is inferred
682
+ * from `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean
683
+ * and `useFlag("hero", "control")` a string.
684
+ *
685
+ * `key` may be a plain value, a `ref`, or a getter: passing a reactive source
686
+ * makes the subscription reactive — when it changes the old subscription is torn
687
+ * down and a fresh one opens.
688
+ *
689
+ * The reactive channel is public, so the server evaluates every flag under the
690
+ * socket's own verified identity — the targeting key your `defineFlags({
691
+ * identify })` derives — and accepts no client-supplied targeting context. For
692
+ * evaluation under a context you compute, call `ctx.flags.*` inside a query,
693
+ * mutation, or action and return the resolved value.
694
+ *
695
+ * Evaluation runs through whatever OpenFeature provider the app wired in
696
+ * `lunora/flags.ts`; the read never throws — a provider error resolves the
697
+ * default (the same fail-open contract as server-side `ctx.flags`) — both an
698
+ * attach throw and a provider error pushed mid-session. Call inside `setup()`
699
+ * (or any active effect scope); the subscription tears down on unmount. During
700
+ * SSR no subscription opens at all and the ref stays at `defaultValue`.
701
+ */
702
+ declare const useFlag: <T extends FlagValue>(key: MaybeRefOrGetter<string>, defaultValue: T) => Readonly<Ref<T>>;
703
+ /**
704
+ * Subscribe to several feature flags at once, live over Lunora's WebSocket.
705
+ *
706
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
707
+ * default, and the returned `ref` holds the same-shaped record with resolved
708
+ * values (the defaults until each evaluation lands). This is the batched form of
709
+ * {@link useFlag} — one subscription per key, torn down together when the
710
+ * enclosing effect scope stops. Like {@link useFlag} it evaluates under the
711
+ * socket's server-verified identity only. The flag set is fixed for the
712
+ * composable's lifetime, so nothing here is reactive.
713
+ */
714
+ declare const useFlags: <T extends Record<string, FlagValue>>(flags: T) => Readonly<Ref<T>>;
715
+ /** The connection-level fields: every {@link LiveTopicOptions} field except the two callbacks. */
716
+ type ConnectionFields = Omit<LiveTopicOptions, "onError" | "onEvent">;
717
+ /**
718
+ * Options for {@link useLiveTopic}. Each connection field may be a plain value, a
719
+ * `ref`, or a getter, so a reactive `shardKey` or `headers` re-subscribes. The callbacks
720
+ * are plain functions: a getter would be called by `toValue`, so they are never wrapped.
721
+ */
722
+ type UseLiveTopicOptions<Payload = unknown> = Pick<LiveTopicOptions<Payload>, "onError" | "onEvent"> & { [K in keyof ConnectionFields]: MaybeRefOrGetter<ConnectionFields[K]>; };
723
+ interface UseLiveTopicResult<Payload = unknown> {
724
+ /** Set when the shard refuses the subscription (403, 409, 429 and similar). */
725
+ error: ShallowRef<LiveStreamSubscribeError | undefined>;
726
+ /** The last payload delivered on the topic, or `undefined` until the first event. */
727
+ lastEvent: ShallowRef<Payload | undefined>;
728
+ }
729
+ /**
730
+ * `useLiveTopic` — follow one live topic of a `defineLiveStream` for the life of
731
+ * the calling component's effect scope. Pass the reference `_generated/live.ts` hands
732
+ * out (`live.posts.post({ postId })`), as a value, a `ref` or a getter: the stream's
733
+ * route is resolved against the injected `LunoraClient`, and `lastEvent` and `onEvent`
734
+ * are typed by the payload the topic declares.
735
+ *
736
+ * A lifecycle wrapper over `subscribeLiveTopic`: the connection is shared by URL,
737
+ * so several composables on one page still open one stream. It subscribes on
738
+ * setup, unsubscribes when the scope disposes, and resubscribes when the reference
739
+ * or a reactive connection field changes. Callbacks are read at call time, so they
740
+ * never resubscribe.
741
+ *
742
+ * Client-only: nothing opens during SSR, and the refs stay at their initial values there.
743
+ */
744
+ declare const useLiveTopic: <Payload>(topic: MaybeRefOrGetter<LiveTopicRef<Payload>>, options?: UseLiveTopicOptions<Payload>) => UseLiveTopicResult<Payload>;
745
+ /**
746
+ * The reactive handle returned by {@link useMutation} — the Vue counterpart to
747
+ * React's `useMutation`, re-expressed with refs. The surface is identical across
748
+ * the Lunora adapters (`@lunora/solid`, `/svelte`): `data`/`error`/`pending` are
749
+ * refs you read in a template, `mutate` is an awaitable that resolves with the
750
+ * server value (or rejects). Per-call `optimistic` / `optimisticUpdate` options
751
+ * pass straight through to `client.mutation`.
752
+ */
148
753
  interface MutationHandle<F extends FunctionReference> {
149
754
  /** The latest invocation's resolved value, or `undefined` before the first success. */
150
755
  data: Ref<ReturnOf<F> | undefined>;
151
756
  /** The latest invocation's error, or `undefined`. */
152
757
  error: Ref<Error | undefined>;
153
758
  /** Invoke the mutation. Resolves with the server value; rejects on failure. */
154
- mutate: (args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>;
759
+ mutate: (args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>> & OnlineOnlyOption<F>) => Promise<ReturnOf<F>>;
155
760
  /** `true` while ANY invocation from this handle is in flight (ref-counted, so overlapping calls compose). */
156
761
  pending: Ref<boolean>;
157
762
  /** Clear the latest `data`/`error` back to idle. */
158
763
  reset: () => void;
159
764
  }
160
765
  /**
161
- * Returns a reactive {@link MutationHandle} for the given mutation reference —
162
- * the Vue equivalent of React's `useMutation`.
163
- *
164
- * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
165
- * call options pass straight through to `client.mutation`, which applies and
166
- * rolls them back against the Lunora subscription cache (Convex parity).
167
- *
168
- * `pending` is ref-counted across overlapping invocations of THIS handle, so it
169
- * flips back to `false` only once every concurrent call has settled. The
170
- * ref-counted pending + error-normalize orchestration is the shared
171
- * `createMutationRunner` from `@lunora/client`; only the refs are
172
- * adapter-specific.
173
- */
766
+ * Returns a reactive {@link MutationHandle} for the given mutation reference —
767
+ * the Vue equivalent of React's `useMutation`.
768
+ *
769
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
770
+ * call options pass straight through to `client.mutation`, which applies and
771
+ * rolls them back against the Lunora subscription cache (Convex parity).
772
+ *
773
+ * `pending` is ref-counted across overlapping invocations of THIS handle, so it
774
+ * flips back to `false` only once every concurrent call has settled. The
775
+ * ref-counted pending + error-normalize orchestration is the shared
776
+ * `createCallRunner` from `@lunora/client`; only the refs are adapter-specific.
777
+ *
778
+ * `data`/`error` follow the adapter-wide contract: both track the LATEST
779
+ * invocation (an earlier call settling later cannot clobber a newer one), a
780
+ * success clears `error`, and a failure leaves the previous `data` in place.
781
+ * `reset()` clears both; it does not cancel an in-flight call.
782
+ */
174
783
  declare const useMutation: <F extends FunctionReference>(function_: F) => MutationHandle<F>;
175
784
  /**
176
- * The reactive handle returned by {@link useMutator} — the Vue counterpart to
177
- * `@lunora/react`'s `useMutator`, re-expressed with refs. The surface is
178
- * identical across the Lunora adapters (`@lunora/solid`, `/svelte`):
179
- * `error`/`isError`/`pending` are refs you read in a template and `mutate` is an
180
- * awaitable that resolves once the write is persisted (or rejects).
181
- */
785
+ * The reactive handle returned by {@link useMutator} — the Vue counterpart to
786
+ * `@lunora/react`'s `useMutator`, re-expressed with refs. The surface is
787
+ * identical across the Lunora adapters (`@lunora/solid`, `/svelte`):
788
+ * `error`/`isError`/`pending` are refs you read in a template and `mutate` is an
789
+ * awaitable that resolves once the write is persisted (or rejects).
790
+ */
182
791
  interface MutatorHook<TArgs> {
183
792
  /** The latest invocation's error, or `undefined`. */
184
793
  error: Ref<Error | undefined>;
@@ -192,18 +801,18 @@ interface MutatorHook<TArgs> {
192
801
  reset: () => void;
193
802
  }
194
803
  /**
195
- * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
196
- * custom-mutator handle from `@lunora/db`'s `bindMutators` — the Vue equivalent
197
- * of `@lunora/react`'s `useMutator`. The optimistic overlay and
198
- * server-authoritative push are owned by the bound handle (and TanStack DB's
199
- * optimistic-transaction layer rebases pending overlays on every sync tick);
200
- * this composable only surfaces reactive state for the in-flight/error
201
- * lifecycle. Reads stay on the existing TanStack `useLiveQuery`; no new query
202
- * composable is needed.
203
- *
204
- * `pending` is ref-counted across overlapping invocations of THIS handle, so it
205
- * clears only once every concurrent call has settled.
206
- */
804
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
805
+ * custom-mutator handle from `@lunora/db`'s `bindMutators` — the Vue equivalent
806
+ * of `@lunora/react`'s `useMutator`. The optimistic overlay and
807
+ * server-authoritative push are owned by the bound handle (and TanStack DB's
808
+ * optimistic-transaction layer rebases pending overlays on every sync tick);
809
+ * this composable only surfaces reactive state for the in-flight/error
810
+ * lifecycle. Reads stay on the existing TanStack `useLiveQuery`; no new query
811
+ * composable is needed.
812
+ *
813
+ * `pending` is ref-counted across overlapping invocations of THIS handle, so it
814
+ * clears only once every concurrent call has settled.
815
+ */
207
816
  declare const useMutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHook<TArgs>;
208
817
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
209
818
  type PaginatedArgs<F extends FunctionReference> = Omit<ArgsOf<F>, "paginationOpts">;
@@ -214,9 +823,18 @@ type PageItemOf<F extends FunctionReference> = ReturnOf<F> extends {
214
823
  interface UsePaginatedQueryOptions {
215
824
  /** Page size for the first page (and the default for `loadMore`). */
216
825
  initialNumItems: number;
826
+ /** Called when a page subscription reports an error (also surfaced on the `error` ref). */
827
+ onError?: SubscriptionErrorCallback;
217
828
  shardKey?: string;
218
829
  }
219
830
  interface UsePaginatedQueryResult<T> {
831
+ /**
832
+ * The last page subscription error, or `undefined`. A tail page that fails
833
+ * before its first frame is dropped so `status` returns to `"CanLoadMore"`
834
+ * and `loadMore` can retry it; cleared by the next successful frame,
835
+ * `loadMore`, or an args change.
836
+ */
837
+ error: Ref<SubscriptionError | undefined>;
220
838
  /** `true` while the first page or a `loadMore` page is in flight. */
221
839
  isLoading: Ref<boolean>;
222
840
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
@@ -226,31 +844,35 @@ interface UsePaginatedQueryResult<T> {
226
844
  status: Ref<PaginationStatus>;
227
845
  }
228
846
  /**
229
- * Subscribe to a reactively-paginated query and grow the feed page by page.
230
- *
231
- * The query function must accept a `paginationOpts: { numItems, cursor,
232
- * endCursor }` arg and return a `PaginationResult`. Pages are tracked as an
233
- * ordered list of stable boundary cursors; each loaded page is a live
234
- * subscription over a FIXED `(lower, upper]` range. Inserting or deleting a row
235
- * grows/shrinks the affected page without duplicating or skipping rows across
236
- * boundaries.
237
- *
238
- * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
239
- * it is a no-op unless `status === "CanLoadMore"`. Background split/join
240
- * maintenance keeps page sizes near `initialNumItems` as edits accumulate.
241
- *
242
- * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
243
- * feed to its first page.
244
- *
245
- * Call inside `setup()` (or any active effect scope).
246
- */
847
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
848
+ *
849
+ * The query function must accept a `paginationOpts: { numItems, cursor,
850
+ * endCursor }` arg and return a `PaginationResult`. Pages are tracked as an
851
+ * ordered list of stable boundary cursors; each loaded page is a live
852
+ * subscription over a FIXED `(lower, upper]` range. Inserting or deleting a row
853
+ * grows/shrinks the affected page without duplicating or skipping rows across
854
+ * boundaries.
855
+ *
856
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
857
+ * it is a no-op unless `status === "CanLoadMore"`. Background split/join
858
+ * maintenance keeps page sizes near `initialNumItems` as edits accumulate.
859
+ *
860
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
861
+ * feed to its first page.
862
+ *
863
+ * Call inside `setup()` (or any active effect scope).
864
+ */
247
865
  declare const usePaginatedQuery: <F extends FunctionReference>(function_: F, args: MaybeRefOrGetter<"skip" | PaginatedArgs<F>>, options: UsePaginatedQueryOptions) => UsePaginatedQueryResult<PageItemOf<F>>;
248
866
  interface UseInfiniteQueryOptions {
249
867
  /** Page size for the first page (and the default for `fetchNextPage`). */
250
868
  initialNumItems: number;
869
+ /** Called when a page subscription reports an error (also surfaced on the `error` ref). */
870
+ onError?: SubscriptionErrorCallback;
251
871
  shardKey?: string;
252
872
  }
253
873
  interface UseInfiniteQueryResult<T> {
874
+ /** The last page subscription error, or `undefined` — see `UsePaginatedQueryResult.error`. */
875
+ error: Ref<SubscriptionError | undefined>;
254
876
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
255
877
  fetchNextPage: (numberItems?: number) => void;
256
878
  /** `true` when the loaded tail reports it can load another page. */
@@ -264,37 +886,37 @@ interface UseInfiniteQueryResult<T> {
264
886
  status: Ref<PaginationStatus>;
265
887
  }
266
888
  /**
267
- * Subscribe to a reactively-paginated query and expose its pages discretely.
268
- *
269
- * Shares `usePaginatedQuery`'s reactive-pagination engine but keeps each page
270
- * as its own inner array rather than flattening them, and adds the
271
- * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
272
- * shape.
273
- *
274
- * Call inside `setup()` (or any active effect scope).
275
- */
889
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
890
+ *
891
+ * Shares `usePaginatedQuery`'s reactive-pagination engine but keeps each page
892
+ * as its own inner array rather than flattening them, and adds the
893
+ * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
894
+ * shape.
895
+ *
896
+ * Call inside `setup()` (or any active effect scope).
897
+ */
276
898
  declare const useInfiniteQuery: <F extends FunctionReference>(function_: F, args: MaybeRefOrGetter<"skip" | PaginatedArgs<F>>, options: UseInfiniteQueryOptions) => UseInfiniteQueryResult<PageItemOf<F>>;
277
899
  /**
278
- * `usePresence` — collaborative-awareness composable, the client half of the
279
- * `@lunora/server` `definePresence` preset.
280
- *
281
- * Drives the heartbeat mutation (on mount, interval, and tab re-focus) and
282
- * subscribes to the live `listPresent` query for the given room.
283
- *
284
- * Call inside `setup()` (or any active effect scope).
285
- */
286
- /**
287
- * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }`.
288
- */
900
+ * `usePresence` — collaborative-awareness composable, the client half of the
901
+ * `@lunora/server` `definePresence` preset.
902
+ *
903
+ * Drives the heartbeat mutation (on mount, interval, and tab re-focus) and
904
+ * subscribes to the live `listPresent` query for the given room.
905
+ *
906
+ * Call inside `setup()` (or any active effect scope).
907
+ */
908
+ /**
909
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }`.
910
+ */
289
911
  type HeartbeatReference = FunctionReference<"mutation", {
290
912
  data?: Record<string, unknown>;
291
913
  roomId: string;
292
914
  sessionId: string;
293
915
  }>;
294
916
  /**
295
- * A listPresent query reference: takes `{ roomId }` and returns the array of
296
- * present members.
297
- */
917
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
918
+ * present members.
919
+ */
298
920
  type ListPresentReference = FunctionReference<"query", {
299
921
  roomId: string;
300
922
  }>;
@@ -308,14 +930,22 @@ interface UsePresenceOptions<H extends HeartbeatReference, L extends ListPresent
308
930
  /** The `api.*` reference for the presence listPresent query. */
309
931
  listPresent: L;
310
932
  /**
311
- * Stable id for this presence row. Defaults to a fresh per-mount id.
312
- * Pass a user/connection id to control deduping across tabs.
313
- */
933
+ * Called when the `listPresent` subscription reports an error (a session
934
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
935
+ * failure is invisible and `present` is cleared until a later frame arrives.
936
+ */
937
+ onError?: SubscriptionErrorCallback;
938
+ /**
939
+ * Stable id for this presence row. Defaults to a fresh per-mount id.
940
+ * Pass a user/connection id to control deduping across tabs.
941
+ */
314
942
  sessionId?: string;
315
943
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
316
944
  shardKey?: string;
317
945
  }
318
946
  interface UsePresenceResult<L extends ListPresentReference> {
947
+ /** The `listPresent` subscription's last error, or `undefined`. */
948
+ error: ShallowRef<SubscriptionError | undefined>;
319
949
  /** The present members for the room. `undefined` until the first push. */
320
950
  present: ShallowRef<ReturnOf<L> | undefined>;
321
951
  /** This mount's session id (generated when not supplied). */
@@ -325,51 +955,58 @@ interface UsePresenceResult<L extends ListPresentReference> {
325
955
  }
326
956
  declare const usePresence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: UsePresenceOptions<H, L>) => UsePresenceResult<L>;
327
957
  /**
328
- * Open a live subscription against `client` for FIXED args and stream its values
329
- * into a `ref`. The low-level primitive behind `hydratePreloaded` (whose args
330
- * come from an immutable `Preloaded` token and never change); {@link useQuery}
331
- * handles the reactive-args case separately.
332
- *
333
- * `client.subscribe` already dedupes by `(functionPath, args, shardKey)` and
334
- * replays the last value synchronously, so multiple consumers of the same query
335
- * ride one server-side registration. `seed` sets the ref's value synchronously
336
- * before the subscription attaches, so the first read shows the SSR value with
337
- * no loading flash.
338
- *
339
- * Teardown is wired to the active effect scope (`onScopeDispose`), so it fires
340
- * on component unmount or `effectScope().stop()`. Call it inside `setup()` / an
341
- * effect scope (as `hydratePreloaded` does); outside any scope there is nothing
342
- * to own the subscription, so it would leak until the process exits — the
343
- * `getCurrentScope` guard only avoids throwing, it does not auto-clean.
344
- */
958
+ * Open a live subscription against `client` for FIXED args and stream its values
959
+ * into a `ref`. The low-level primitive behind `hydratePreloaded` (whose args
960
+ * come from an immutable `Preloaded` token and never change); {@link useQuery}
961
+ * handles the reactive-args case separately.
962
+ *
963
+ * `client.subscribe` already dedupes by `(functionPath, args, shardKey)` and
964
+ * replays the last value synchronously, so multiple consumers of the same query
965
+ * ride one server-side registration. `seed` sets the ref's value synchronously
966
+ * before the subscription attaches, so the first read shows the SSR value with
967
+ * no loading flash. `onError` receives a subscription-scoped error the server
968
+ * pushes (a session expiry, an RLS denial); without it the ref keeps rendering
969
+ * the seed as if it were live.
970
+ *
971
+ * Teardown is wired to the active effect scope (`onScopeDispose`), so it fires
972
+ * on component unmount or `effectScope().stop()`. Call it inside `setup()` / an
973
+ * effect scope (as `hydratePreloaded` does); outside any scope there is nothing
974
+ * to own the subscription, so it would leak until the process exits — the
975
+ * `getCurrentScope` guard only avoids throwing, it does not auto-clean.
976
+ */
345
977
  declare const subscribeToQuery: <F extends FunctionReference, T = ReturnOf<F>>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: {
978
+ onError?: SubscriptionErrorCallback;
346
979
  seed?: T;
347
980
  shardKey?: string;
348
981
  }) => Ref<T | undefined>;
349
982
  /**
350
- * Subscribe to a server query and expose its latest value as a `ref`.
351
- *
352
- * The returned ref is `undefined` until the first server response lands, then
353
- * updates on every delta the server pushes — the Vue-idiomatic equivalent of
354
- * React's `useQuery`. `args` may be a plain value, a `ref`, or a getter: passing
355
- * a reactive source makes the subscription reactive — when the args change the
356
- * old subscription is torn down and a fresh one opens for the new args (matching
357
- * `@lunora/react`/`@lunora/solid`). Pass `"skip"` (or a source resolving to
358
- * `"skip"`) to short-circuit: no network call, no socket. The subscription tears
359
- * down automatically when the owning component unmounts (or the effect scope
360
- * stops).
361
- *
362
- * Call inside `setup()` (or any active effect scope). For SSR seeding with no
363
- * loading flash, use `hydratePreloaded` instead.
364
- */
983
+ * Subscribe to a server query and expose its latest value as a `ref`.
984
+ *
985
+ * The returned ref is `undefined` until the first server response lands, then
986
+ * updates on every delta the server pushes — the Vue-idiomatic equivalent of
987
+ * React's `useQuery`. `args` may be a plain value, a `ref`, or a getter: passing
988
+ * a reactive source makes the subscription reactive — when the args change the
989
+ * old subscription is torn down, the ref resets to `undefined`, and a fresh one
990
+ * opens for the new args (matching `@lunora/react`/`@lunora/solid`). Pass `"skip"` (or a source resolving to
991
+ * `"skip"`) to short-circuit: no network call, no socket. The subscription tears
992
+ * down automatically when the owning component unmounts (or the effect scope
993
+ * stops).
994
+ *
995
+ * Call inside `setup()` (or any active effect scope). For SSR seeding with no
996
+ * loading flash, use `hydratePreloaded` instead.
997
+ *
998
+ * Pass `onError` to surface a subscription-scoped error the server pushes (an RLS
999
+ * denial, a query that starts failing server-side). Without it such an error is
1000
+ * dropped and the ref just freezes at its last good value.
1001
+ */
365
1002
  declare const useQuery: <F extends FunctionReference>(function_: F, args: MaybeRefOrGetter<ArgsOf<F> | "skip">, options?: UseQueryOptions) => Ref<ReturnOf<F> | undefined>;
366
1003
  interface UseRateLimitOptions {
367
1004
  /** Clock injection for tests. Defaults to `Date.now`. */
368
1005
  now?: () => number;
369
1006
  /**
370
- * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
371
- * down and `disabled` flips back automatically. Defaults to `1000`.
372
- */
1007
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
1008
+ * down and `disabled` flips back automatically. Defaults to `1000`.
1009
+ */
373
1010
  tickMs?: number;
374
1011
  }
375
1012
  interface UseRateLimitResult {
@@ -387,31 +1024,306 @@ interface UseRateLimitResult {
387
1024
  retryAfter: ComputedRef<number>;
388
1025
  }
389
1026
  /**
390
- * Client-side mirror of a rate limit for instant UX — disable a button or show
391
- * a countdown without a round-trip. It runs the same token-bucket / fixed-window
392
- * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
393
- * authoritative check; the server remains the source of truth.
394
- *
395
- * `config` accepts a plain object, a `ref`, or a getter (`MaybeRefOrGetter`).
396
- * When you pass a ref/getter it is tracked reactively — changing the config
397
- * re-derives `status` (and the `ok` / `disabled` / `retryAfter` views) on the
398
- * fly. A plain object keeps working unchanged; pass a stable reference (module
399
- * constant) so the reactive derived values stay settled.
400
- */
1027
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
1028
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
1029
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
1030
+ * authoritative check; the server remains the source of truth.
1031
+ *
1032
+ * `config` accepts a plain object, a `ref`, or a getter (`MaybeRefOrGetter`).
1033
+ * When you pass a ref/getter it is tracked reactively — changing the config
1034
+ * re-derives `status` (and the `ok` / `disabled` / `retryAfter` views) on the
1035
+ * fly. A plain object keeps working unchanged; pass a stable reference (module
1036
+ * constant) so the reactive derived values stay settled.
1037
+ */
401
1038
  declare const useRateLimit: (config: MaybeRefOrGetter<RateLimitConfig>, options?: UseRateLimitOptions) => UseRateLimitResult;
1039
+ /** The lifecycle of a stream the composable is observing. */
1040
+ type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
1041
+ interface UseStreamResult<T> {
1042
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
1043
+ cancel: () => void;
1044
+ /** Chunks the server has pushed so far, in arrival order. */
1045
+ chunks: Ref<ReadonlyArray<T>>;
1046
+ error: Ref<Error | undefined>;
1047
+ status: Ref<UseStreamStatus>;
1048
+ }
1049
+ interface UseStreamOptions {
1050
+ /**
1051
+ * Opt into resume-on-reconnect for a stream the server declared `durable`.
1052
+ * The chunks already received are kept and the socket re-attaches to the same
1053
+ * run, so a dropped connection mid-generation continues instead of surfacing
1054
+ * `STREAM_DISCONNECTED`. Has no effect on an ephemeral stream.
1055
+ */
1056
+ durable?: boolean;
1057
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
1058
+ maxBuffer?: number;
1059
+ shardKey?: string;
1060
+ }
1061
+ /**
1062
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
1063
+ * lifecycle status and a cancel function, all as refs. Changing the resolved
1064
+ * `args` resets the stream — the previous iterator is cancelled and a fresh one
1065
+ * opens with empty `chunks`.
1066
+ *
1067
+ * `args` may be a plain value, `ref`, or getter; resolving it to `"skip"` keeps
1068
+ * the composable mounted without opening a stream (mirrors `useSubscription`).
1069
+ * Nothing opens during SSR either — the stream attaches after hydration.
1070
+ * The Vue counterpart to React's `useStream`, re-expressed with refs.
1071
+ */
1072
+ declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: MaybeRefOrGetter<"skip" | ArgsOf<F>>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
402
1073
  interface UseSubscriptionResult<T> {
403
1074
  data: Ref<T | undefined>;
404
1075
  error: Ref<Error | undefined>;
405
1076
  }
406
1077
  /**
407
- * Subscribe to a reactive server push stream. Returns `{ data, error }` refs
408
- * that update whenever the server emits a new value. Passing `"skip"` as `args`
409
- * (or a ref/getter that resolves to `"skip"`) tears down the subscription
410
- * without unmounting.
411
- *
412
- * Unlike `useQuery`, which tracks the full reactive cache, `useSubscription`
413
- * owns a single lightweight subscription and is suitable for ephemeral,
414
- * high-frequency streams.
415
- */
1078
+ * Subscribe to a reactive server push stream. Returns `{ data, error }` refs
1079
+ * that update whenever the server emits a new value. Passing `"skip"` as `args`
1080
+ * (or a ref/getter that resolves to `"skip"`) tears down the subscription
1081
+ * without unmounting.
1082
+ *
1083
+ * Unlike `useQuery`, which tracks the full reactive cache, `useSubscription`
1084
+ * owns a single lightweight subscription and is suitable for ephemeral,
1085
+ * high-frequency streams.
1086
+ */
416
1087
  declare const useSubscription: <F extends FunctionReference>(function_: F, args: MaybeRefOrGetter<ArgsOf<F> | "skip">, options?: UseQueryOptions) => UseSubscriptionResult<ReturnOf<F>>;
417
- export { AuthLoading, Authenticated, type FlagContext, type FlagValue, type HeartbeatReference, LUNORA_INJECTION_KEY, type ListPresentReference, type MutationHandle, type MutatorHook, type PageItemOf, type PaginatedArgs, Unauthenticated, type UseAuthResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UsePaginatedQueryOptions, type UsePaginatedQueryResult, type UsePresenceOptions, type UsePresenceResult, type UseQueryOptions, type UseRateLimitOptions, type UseRateLimitResult, type UseSubscriptionResult, createLunora, hydratePreloaded, provideLunora, subscribeToQuery, useAuth, useConnectionStatus, useFlag, useFlags, useInfiniteQuery, useLunora, useMutation, useMutator, usePaginatedQuery, usePresence, useQuery, useRateLimit, useSubscription };
1088
+ /**
1089
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
1090
+ * capture and speaker playback implementations injected into the composable via
1091
+ * its `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
1092
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
1093
+ * composable's transport + reactive-state logic and remains mockable in a
1094
+ * non-browser test env.
1095
+ */
1096
+ /**
1097
+ * The negotiated audio format the voice DO streams back. Mirrors
1098
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1099
+ * imported) so this Vue package never pulls in the server-only `@lunora/agent`
1100
+ * module graph.
1101
+ */
1102
+ type VoiceAudioFormat = "mp3" | "wav";
1103
+ /** Captures microphone audio and reports level / turn boundaries back to the composable. */
1104
+ interface VoiceMicrophone {
1105
+ /** Mute/unmute the mic without tearing down the capture graph. */
1106
+ setMuted: (muted: boolean) => void;
1107
+ /** Stop capture and release the media stream + audio graph. */
1108
+ stop: () => void;
1109
+ }
1110
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1111
+ interface VoiceSpeaker {
1112
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1113
+ enqueue: (audio: Uint8Array) => void;
1114
+ /** Drop everything queued and stop the current chunk (barge-in). */
1115
+ interrupt: () => void;
1116
+ /** Release the playback audio context. */
1117
+ stop: () => void;
1118
+ }
1119
+ /** Config passed to a {@link CreateMicrophone} factory. */
1120
+ interface MicrophoneConfig {
1121
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1122
+ interruptChunks: number;
1123
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1124
+ interruptThreshold: number;
1125
+ /**
1126
+ * `true` from the moment a turn is committed until it completes — the whole
1127
+ * `thinking` + `speaking` window, not just the audible half.
1128
+ *
1129
+ * It gates BOTH branches below, and the wider span is the point. Gated only
1130
+ * on "audibly speaking", turn detection kept running through the entire
1131
+ * STT+LLM window after a `commit`: room noise at the (deliberately low)
1132
+ * `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
1133
+ * `commit`, and the DO refused it with "a turn is already in progress" —
1134
+ * a refusal that returns before draining the audio buffer, so the PCM
1135
+ * captured since the first commit leaked into the next utterance.
1136
+ *
1137
+ * A genuine barge-in still works in that window: it routes through the
1138
+ * `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
1139
+ * `interruptThreshold` — an order of magnitude above `silenceThreshold` —
1140
+ * and `interrupt` is exactly what the DO tells the client to send.
1141
+ */
1142
+ isTurnActive: () => boolean;
1143
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1144
+ onAudio: (pcm: Uint8Array) => void;
1145
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1146
+ onInterrupt: () => void;
1147
+ /** The current input RMS (0–1), for a level meter. */
1148
+ onLevel: (rms: number) => void;
1149
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1150
+ onSilence: () => void;
1151
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1152
+ silenceDurationMs: number;
1153
+ /** RMS below which audio counts as silence. */
1154
+ silenceThreshold: number;
1155
+ }
1156
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1157
+ type CreateSpeaker = (config: {
1158
+ audioFormat: VoiceAudioFormat;
1159
+ }) => VoiceSpeaker;
1160
+ /**
1161
+ * The `agents.<name>Voice` reference codegen emits for a voice-enabled agent — a
1162
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1163
+ * generated member, so passing `api.agents.<name>Voice` type-checks.
1164
+ */
1165
+ type VoiceReference = FunctionReference<"stream", {
1166
+ threadKey: string;
1167
+ }, Record<string, unknown>>;
1168
+ /** The lifecycle of a voice call, mirrored to the UI. */
1169
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1170
+ /** A minimal structural subset of the DOM `WebSocket` the composable drives. */
1171
+ interface VoiceSocket {
1172
+ binaryType: string;
1173
+ close: () => void;
1174
+ onclose: ((event: unknown) => void) | null;
1175
+ onerror: ((event: unknown) => void) | null;
1176
+ onmessage: ((event: {
1177
+ data: unknown;
1178
+ }) => void) | null;
1179
+ onopen: ((event: unknown) => void) | null;
1180
+ readonly readyState: number;
1181
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1182
+ }
1183
+ type CreateSocket = (url: string) => VoiceSocket;
1184
+ interface UseVoiceAgentOptions {
1185
+ /**
1186
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1187
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1188
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1189
+ */
1190
+ createMicrophone?: CreateMicrophone;
1191
+ /**
1192
+ * Advanced/test seam: open the transport. Defaults to the WebSocket
1193
+ * implementation the client was built with (`client.getWebSocketImpl()`),
1194
+ * NOT a raw `globalThis.WebSocket`.
1195
+ */
1196
+ createSocket?: CreateSocket;
1197
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1198
+ createSpeaker?: CreateSpeaker;
1199
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1200
+ interruptChunks?: number;
1201
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1202
+ interruptThreshold?: number;
1203
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1204
+ silenceDurationMs?: number;
1205
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1206
+ silenceThreshold?: number;
1207
+ /** The thread to converse on — shared with the agent's text turns. May be a plain value, `ref`, or getter (resolved when the call opens). */
1208
+ threadKey: MaybeRefOrGetter<string>;
1209
+ /** The generated `api.agents.<name>Voice` reference — identifies the voice DO endpoint. */
1210
+ voice: VoiceReference;
1211
+ }
1212
+ interface UseVoiceAgentResult {
1213
+ /** The current input RMS (0–1) — drive a mic level meter. */
1214
+ audioLevel: Readonly<Ref<number>>;
1215
+ /** `true` once the WS `ready` handshake completed. */
1216
+ connected: Readonly<Ref<boolean>>;
1217
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1218
+ endCall: () => void;
1219
+ /** The last transport/pipeline error, or `undefined`. */
1220
+ error: Readonly<Ref<Error | undefined>>;
1221
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1222
+ interimTranscript: Readonly<Ref<string>>;
1223
+ /** `true` while the mic is muted. */
1224
+ isMuted: Readonly<Ref<boolean>>;
1225
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1226
+ sendText: (text: string) => void;
1227
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1228
+ startCall: () => Promise<void>;
1229
+ /** The current call lifecycle. */
1230
+ status: Readonly<Ref<VoiceStatus>>;
1231
+ /** Mute/unmute the microphone. Returns the new muted state. */
1232
+ toggleMute: () => boolean;
1233
+ /** The last finalized user utterance (STT result). */
1234
+ transcript: Readonly<Ref<string>>;
1235
+ }
1236
+ /**
1237
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1238
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1239
+ * streams the agent's synthesized speech back through the browser's audio output,
1240
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1241
+ * `audioLevel`) to Vue refs. Pass the generated `api.agents.<name>Voice`
1242
+ * reference (never a string), matching `useAgentChat`'s reference-passing style.
1243
+ * The Vue counterpart to React's `useVoiceAgent`, re-expressed with refs; the
1244
+ * per-call connection lives in a closure variable (a composable runs once per
1245
+ * component, so no `ref`-of-ref indirection is needed).
1246
+ *
1247
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1248
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1249
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1250
+ * `createSocket`) so the composable is drivable outside a browser.
1251
+ */
1252
+ declare const useVoiceAgent: (options: UseVoiceAgentOptions) => UseVoiceAgentResult;
1253
+ export { type ActionHandle, type AgentApprovalGrant, type AgentChatMessage, type AgentLiveEvent, type AgentProgressEvent, type AgentThreadRecord, type AgentThreadStatus, type AgentTokenDelta, type AgentToolEvent, AuthLoading, Authenticated, type FlagValue, type HeartbeatReference,
1254
+ /**
1255
+ * `@lunora/vue` — the Vue adapter for Lunora.
1256
+ *
1257
+ * Thin, idiomatic glue over the framework-neutral `@lunora/client` (which owns
1258
+ * the WebSocket transport, subscription registry, offline queue, and
1259
+ * delta-merge — zero React, zero Vue). This package re-expresses that contract
1260
+ * as Vue composables:
1261
+ *
1262
+ * - `createLunora` / `provideLunora` / `useLunora` — provide/inject the client.
1263
+ * - `useQuery` — a live `ref` that opens a WS subscription and updates on deltas (reactive args re-subscribe).
1264
+ * - `useMutation` — an optimistic mutation handle (refs + awaitable `mutate`).
1265
+ * - `hydratePreloaded` — seed a `ref` synchronously from an SSR `Preloaded` token (no loading flash), then attach the live subscription.
1266
+ *
1267
+ * Server-side preload helpers live in the socket-free `@lunora/vue/server`
1268
+ * entry (`createServerClient`, `preloadQuery`). Nuxt's single-worker
1269
+ * composition (Lunora mounted inside Nitro) is `@lunora/nuxt`, not this
1270
+ * package — see [Bring your framework](/docs/frameworks/bring-your-framework).
1271
+ */
1272
+ LUNORA_INJECTION_KEY, type ListPresentReference, type MutationHandle, type MutatorHook, type PageItemOf, type PaginatedArgs, Unauthenticated, type UseAgentApi, type UseAgentChatApi, type UseAgentChatOptions, type UseAgentChatResult, type UseAgentOptions, type UseAgentResult, type UseAgentStateApi, type UseAgentStateOptions, type UseAgentStateResult, type UseAgentToolEventsApi, type UseAgentToolEventsOptions, type UseAgentToolEventsResult, type UseAuthResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseLiveTopicOptions, type UseLiveTopicResult, type UsePaginatedQueryOptions, type UsePaginatedQueryResult, type UsePresenceOptions, type UsePresenceResult, type UseQueryOptions, type UseRateLimitOptions, type UseRateLimitResult, type UseStreamOptions, type UseStreamResult, type UseStreamStatus, type UseSubscriptionResult, type UseVoiceAgentOptions, type UseVoiceAgentResult, type VoiceAudioFormat, type VoiceReference, type VoiceStatus,
1273
+ /**
1274
+ * `@lunora/vue` — the Vue adapter for Lunora.
1275
+ *
1276
+ * Thin, idiomatic glue over the framework-neutral `@lunora/client` (which owns
1277
+ * the WebSocket transport, subscription registry, offline queue, and
1278
+ * delta-merge — zero React, zero Vue). This package re-expresses that contract
1279
+ * as Vue composables:
1280
+ *
1281
+ * - `createLunora` / `provideLunora` / `useLunora` — provide/inject the client.
1282
+ * - `useQuery` — a live `ref` that opens a WS subscription and updates on deltas (reactive args re-subscribe).
1283
+ * - `useMutation` — an optimistic mutation handle (refs + awaitable `mutate`).
1284
+ * - `hydratePreloaded` — seed a `ref` synchronously from an SSR `Preloaded` token (no loading flash), then attach the live subscription.
1285
+ *
1286
+ * Server-side preload helpers live in the socket-free `@lunora/vue/server`
1287
+ * entry (`createServerClient`, `preloadQuery`). Nuxt's single-worker
1288
+ * composition (Lunora mounted inside Nitro) is `@lunora/nuxt`, not this
1289
+ * package — see [Bring your framework](/docs/frameworks/bring-your-framework).
1290
+ */
1291
+ createLunora, hydratePreloaded,
1292
+ /**
1293
+ * `@lunora/vue` — the Vue adapter for Lunora.
1294
+ *
1295
+ * Thin, idiomatic glue over the framework-neutral `@lunora/client` (which owns
1296
+ * the WebSocket transport, subscription registry, offline queue, and
1297
+ * delta-merge — zero React, zero Vue). This package re-expresses that contract
1298
+ * as Vue composables:
1299
+ *
1300
+ * - `createLunora` / `provideLunora` / `useLunora` — provide/inject the client.
1301
+ * - `useQuery` — a live `ref` that opens a WS subscription and updates on deltas (reactive args re-subscribe).
1302
+ * - `useMutation` — an optimistic mutation handle (refs + awaitable `mutate`).
1303
+ * - `hydratePreloaded` — seed a `ref` synchronously from an SSR `Preloaded` token (no loading flash), then attach the live subscription.
1304
+ *
1305
+ * Server-side preload helpers live in the socket-free `@lunora/vue/server`
1306
+ * entry (`createServerClient`, `preloadQuery`). Nuxt's single-worker
1307
+ * composition (Lunora mounted inside Nitro) is `@lunora/nuxt`, not this
1308
+ * package — see [Bring your framework](/docs/frameworks/bring-your-framework).
1309
+ */
1310
+ provideLunora, subscribeToQuery, useAction, useAgent, useAgentChat, useAgentState, useAgentToolEvents, useAuth, useConnectionStatus, useFlag, useFlags, useInfiniteQuery, useLiveTopic,
1311
+ /**
1312
+ * `@lunora/vue` — the Vue adapter for Lunora.
1313
+ *
1314
+ * Thin, idiomatic glue over the framework-neutral `@lunora/client` (which owns
1315
+ * the WebSocket transport, subscription registry, offline queue, and
1316
+ * delta-merge — zero React, zero Vue). This package re-expresses that contract
1317
+ * as Vue composables:
1318
+ *
1319
+ * - `createLunora` / `provideLunora` / `useLunora` — provide/inject the client.
1320
+ * - `useQuery` — a live `ref` that opens a WS subscription and updates on deltas (reactive args re-subscribe).
1321
+ * - `useMutation` — an optimistic mutation handle (refs + awaitable `mutate`).
1322
+ * - `hydratePreloaded` — seed a `ref` synchronously from an SSR `Preloaded` token (no loading flash), then attach the live subscription.
1323
+ *
1324
+ * Server-side preload helpers live in the socket-free `@lunora/vue/server`
1325
+ * entry (`createServerClient`, `preloadQuery`). Nuxt's single-worker
1326
+ * composition (Lunora mounted inside Nitro) is `@lunora/nuxt`, not this
1327
+ * package — see [Bring your framework](/docs/frameworks/bring-your-framework).
1328
+ */
1329
+ useLunora, useMutation, useMutator, usePaginatedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription, useVoiceAgent };