@lunora/vue 1.0.0-alpha.26 → 1.0.0-alpha.260

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