@lunora/vue 1.0.0-alpha.15 → 1.0.0-alpha.151

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