@lunora/svelte 1.0.0-alpha.13 → 1.0.0-alpha.131

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 +5 -1
  3. package/dist/index.d.mts +1085 -225
  4. package/dist/index.d.ts +1085 -225
  5. package/dist/index.mjs +1 -12
  6. package/dist/packem_shared/action-SjeZUGhX.mjs +1 -0
  7. package/dist/packem_shared/agent-WMVWf1Ks.mjs +1 -0
  8. package/dist/packem_shared/agentChat-CX6dTMoY.mjs +1 -0
  9. package/dist/packem_shared/agentState-CS3hHD6A.mjs +1 -0
  10. package/dist/packem_shared/agentToolEvents-DlVpngzv.mjs +1 -0
  11. package/dist/packem_shared/auth-BrLyP-oa.mjs +1 -0
  12. package/dist/packem_shared/connectionStatus-DMx3BE5Q.mjs +1 -0
  13. package/dist/packem_shared/flag-Csh9LBiO.mjs +1 -0
  14. package/dist/packem_shared/getLunoraClient-DU7BmZy1.mjs +1 -0
  15. package/dist/packem_shared/hydratePreloaded-BiEJ5Jt2.mjs +1 -0
  16. package/dist/packem_shared/infiniteQuery-CSXXv5DY.mjs +1 -0
  17. package/dist/packem_shared/is-browser-BEdfLJHK.mjs +1 -0
  18. package/dist/packem_shared/is-function-reference-abFdrAae.mjs +1 -0
  19. package/dist/packem_shared/mutation-DLBr5Op1.mjs +1 -0
  20. package/dist/packem_shared/mutator-DECDuo94.mjs +1 -0
  21. package/dist/packem_shared/presence-Ybhe8so-.mjs +1 -0
  22. package/dist/packem_shared/query-VzaOi1pv.mjs +1 -0
  23. package/dist/packem_shared/rateLimit-Cli38qWO.mjs +1 -0
  24. package/dist/packem_shared/stream-Cxl8guzh.mjs +1 -0
  25. package/dist/packem_shared/subscribe-reactive-args-DYKqoWhw.mjs +1 -0
  26. package/dist/packem_shared/subscription-NVRm3LD-.mjs +1 -0
  27. package/dist/packem_shared/voiceAgent-KSChAXsW.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 +8 -7
  33. package/dist/packem_shared/auth-DLPf_bK9.mjs +0 -28
  34. package/dist/packem_shared/connectionStatus-CRsOMeYl.mjs +0 -14
  35. package/dist/packem_shared/flag-19nEeKPT.mjs +0 -56
  36. package/dist/packem_shared/getLunoraClient--bwSz7F6.mjs +0 -16
  37. package/dist/packem_shared/hydratePreloaded-D5rUJdXy.mjs +0 -21
  38. package/dist/packem_shared/infiniteQuery-jPMQw8Vz.mjs +0 -196
  39. package/dist/packem_shared/is-function-reference-ycLAcI79.mjs +0 -3
  40. package/dist/packem_shared/mutation-CnDkAaLH.mjs +0 -31
  41. package/dist/packem_shared/mutator-B5LchgMS.mjs +0 -19
  42. package/dist/packem_shared/presence-BQWixJ2T.mjs +0 -66
  43. package/dist/packem_shared/query-D8Pct9Qe.mjs +0 -36
  44. package/dist/packem_shared/rateLimit-Cdw1kp8t.mjs +0 -66
  45. package/dist/packem_shared/subscription-twuBT_Wb.mjs +0 -46
  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,29 +1,520 @@
1
- import { LunoraClient, User, ConnectionStatus, Preloaded, FunctionReference, ReturnOf, ArgsOf, MutationCallOptions, MutatorHandle, SubscriptionErrorCallback } from '@lunora/client';
1
+ import { FunctionReference, ArgsOf, ActionCallOptions, ReturnOf, LunoraClient, SubscriptionErrorCallback, User, ConnectionStatus, Preloaded, MutationCallOptions, MutatorHandle, SubscriptionError } from '@lunora/client';
2
2
  export type { ArgsOf, ConnectionStatus, FunctionReference, LunoraClient, MutationCallOptions, MutatorHandle, MutatorTransaction, Preloaded, ReturnOf } from '@lunora/client';
3
3
  import { Readable } from 'svelte/store';
4
4
  import { PaginationStatus } from '@lunora/client/pagination';
5
5
  import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
6
6
  /**
7
- * Publish a {@link LunoraClient} on the Svelte component context so that
8
- * descendant components can read it with {@link getLunoraClient} (or implicitly,
9
- * via the default-client lookups inside `query`/`mutation`/`hydratePreloaded`).
10
- *
11
- * Call this once, high in the tree (typically your root `+layout.svelte` or
12
- * `App.svelte`), during component initialisation — `setContext` must run while
13
- * the component is being constructed, exactly like React's provider mounts once.
14
- * This is the Svelte analogue of mounting `LunoraProvider`.
15
- */
7
+ * The reactive handle returned by {@link action} — the Svelte counterpart to
8
+ * React's `useAction`, re-expressed as stores you read with `$`. The surface is
9
+ * identical across the Lunora adapters (`@lunora/solid`, `/vue`).
10
+ */
11
+ interface ActionHandle<F extends FunctionReference> {
12
+ /**
13
+ * Run the action. Resolves with the server result and rejects on failure
14
+ * (errors propagate — there is no swallowing).
15
+ */
16
+ call: (args: ArgsOf<F>, options?: ActionCallOptions) => Promise<ReturnOf<F>>;
17
+ /** The latest invocation's resolved value, or `undefined` before the first success. */
18
+ data: Readable<ReturnOf<F> | undefined>;
19
+ /** The latest invocation's error, or `undefined`. */
20
+ error: Readable<Error | undefined>;
21
+ /**
22
+ * `true` while any invocation from this handle is in flight. Ref-counted, so
23
+ * overlapping calls compose and it only flips back to `false` once the last
24
+ * one settles. Read it with `$pending` in a component to disable a button.
25
+ */
26
+ pending: Readable<boolean>;
27
+ /** Clear `data`/`error` back to idle. */
28
+ reset: () => void;
29
+ }
30
+ /**
31
+ * Create an {@link ActionHandle} for an action reference. The Svelte
32
+ * counterpart to React's `useAction`: returns `{ data, error, pending, call,
33
+ * reset }` of readable stores plus an awaitable `call`.
34
+ *
35
+ * **Narrower than `mutation` on purpose:** no `optimistic` /
36
+ * `optimisticUpdate`. An optimistic update patches the subscription cache on the
37
+ * assumption a write will land; an action is not a write — it runs in the
38
+ * Worker, may call a third party, and has no declared effect on any query.
39
+ *
40
+ * `data`/`error` follow the adapter-wide contract: both track the LATEST
41
+ * invocation (an earlier call settling later cannot clobber a newer one), a
42
+ * success clears `error`, and a failure leaves the previous `data` in place.
43
+ * `reset()` clears both; it does not cancel an in-flight call.
44
+ *
45
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
46
+ * by `setLunoraClient`.
47
+ */
48
+ declare function action<F extends FunctionReference>(function_: F): ActionHandle<F>;
49
+ declare function action<F extends FunctionReference>(client: LunoraClient, function_: F): ActionHandle<F>;
50
+ /**
51
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
52
+ * `@lunora/agent`'s `AgentThreadStatus` — re-declared here (rather than imported)
53
+ * so this Svelte entry never pulls in the server-only `@lunora/agent` module graph
54
+ * (the adapter stays Svelte + `@lunora/client` only). Keep in sync with
55
+ * `packages/agent/src/types.ts`.
56
+ */
57
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
58
+ /**
59
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
60
+ * subset of the persisted thread row — every field beyond `status` is optional so
61
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
62
+ * `agent_threads` table in `packages/agent/src/component.ts`.
63
+ */
64
+ interface AgentThreadRecord {
65
+ createdAt?: number;
66
+ /** The failure message when `status === "error"`. */
67
+ error?: string;
68
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
69
+ instanceId?: string;
70
+ messageCount?: number;
71
+ /** The verified thread owner, when the run was started with one. */
72
+ owner?: string;
73
+ status: AgentThreadStatus;
74
+ title?: string;
75
+ updatedAt?: number;
76
+ }
77
+ /**
78
+ * The `agents.agentThread` reference the handle subscribes to for live thread
79
+ * state (status + the in-flight `instanceId`). A structural subset of the
80
+ * generated `api.agents` surface, so the whole generated `api` object is
81
+ * assignable.
82
+ */
83
+ interface AgentApi {
84
+ agents: {
85
+ agentThread: FunctionReference<"query", {
86
+ key: string;
87
+ }, Record<string, unknown> | undefined>;
88
+ };
89
+ }
90
+ interface AgentOptions {
91
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
92
+ api: AgentApi;
93
+ /**
94
+ * Optional app mutation over the agent's cancel path
95
+ * (`ctx.agents[name].cancel(id)`). Called with `{ instanceId, threadKey }`.
96
+ * When omitted (or no run is in flight) {@link AgentHandle.cancel} is a no-op.
97
+ */
98
+ cancel?: FunctionReference<"mutation">;
99
+ /**
100
+ * Called when the live thread subscription reports an error (a session
101
+ * expiry, an RLS denial). Without it such an error is dropped and `thread` /
102
+ * `status` freeze at their last value — unlike the React, Angular, Solid and Vue
103
+ * ports, this one leaves the value store untouched on error.
104
+ */
105
+ onError?: SubscriptionErrorCallback;
106
+ /**
107
+ * The app mutation that starts (or continues) a run — a thin wrapper over
108
+ * `ctx.agents[name].run(...)`. Called with `{ threadKey, input }` merged with
109
+ * {@link AgentOptions.runArgs} and the per-call args.
110
+ */
111
+ run: FunctionReference<"mutation">;
112
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
113
+ runArgs?: Record<string, unknown>;
114
+ /** The thread to observe and drive. */
115
+ threadKey: string;
116
+ }
117
+ interface AgentHandle {
118
+ /**
119
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
120
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
121
+ */
122
+ cancel: () => Promise<void>;
123
+ /** `true` while a `run` invocation is in flight. Read with `$pending`. */
124
+ pending: Readable<boolean>;
125
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
126
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
127
+ /** The live thread status, or `undefined` before the thread exists. Read with `$status`. */
128
+ status: Readable<AgentThreadStatus | undefined>;
129
+ /**
130
+ * Stop the live thread subscription. Call in `onDestroy`
131
+ * (`onDestroy(handle.teardown)`).
132
+ */
133
+ teardown: () => void;
134
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. Read with `$thread`. */
135
+ thread: Readable<AgentThreadRecord | undefined>;
136
+ }
137
+ /**
138
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
139
+ * chat message surface — the Svelte counterpart to React's `useAgent`,
140
+ * re-expressed as stores you read with `$`. Composes `client.subscribe` for live
141
+ * thread state and {@link mutation} for the run/cancel writes. For the full
142
+ * conversation surface (durable history + approvals) use `agentChat`.
143
+ *
144
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
145
+ * `ctx.agents[name].run` / `.cancel`, so the handle hard-codes no function names
146
+ * beyond the `agents:*` surface. The subscription opens eagerly on the call and
147
+ * runs until {@link AgentHandle.teardown} — call `onDestroy(handle.teardown)`.
148
+ *
149
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
150
+ * `setLunoraClient`.
151
+ */
152
+ declare function agent(options: AgentOptions): AgentHandle;
153
+ declare function agent(client: LunoraClient, options: AgentOptions): AgentHandle;
154
+ /**
155
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
156
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
157
+ * re-declared here (rather than imported) so this Svelte entry never pulls in the
158
+ * server-only `@lunora/agent` module graph. Keep in sync with the
159
+ * `agent_messages` table in `packages/agent/src/component.ts`.
160
+ */
161
+ interface AgentChatMessage {
162
+ content: string;
163
+ createdAt?: number;
164
+ /**
165
+ * `true` for a client-side optimistic user message not yet acknowledged by
166
+ * the server. Cleared once the durable history carries the matching user turn.
167
+ */
168
+ optimistic?: boolean;
169
+ role: "assistant" | "system" | "tool" | "user";
170
+ seq: number;
171
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
172
+ status?: "approved" | "awaiting_approval" | "rejected";
173
+ toolCallId?: string;
174
+ toolCalls?: ReadonlyArray<{
175
+ id: string;
176
+ input: unknown;
177
+ name: string;
178
+ }>;
179
+ toolName?: string;
180
+ }
181
+ /**
182
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
183
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
184
+ * {@link AgentChatHandle.streamingText} live and are never replayed; the
185
+ * persisted assistant message stays the single source of truth.
186
+ */
187
+ interface AgentTokenDelta {
188
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
189
+ kind?: "token";
190
+ /** The incremental text chunk the model just produced. */
191
+ text: string;
192
+ /** The thread this delta belongs to. */
193
+ threadKey: string;
194
+ /** The zero-based index of the turn producing the delta. */
195
+ turn: number;
196
+ }
197
+ /**
198
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
199
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
200
+ * surfaced by `agentToolEvents`, ignored by {@link AgentChatHandle.streamingText}.
201
+ */
202
+ interface AgentProgressEvent {
203
+ /** The arbitrary, JSON-serializable payload the tool reported. */
204
+ data: unknown;
205
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
206
+ kind: "progress";
207
+ /** The thread this event belongs to. */
208
+ threadKey: string;
209
+ /** The tool call this progress belongs to. */
210
+ toolCallId: string;
211
+ }
212
+ /**
213
+ * A single event on the agent's live-only channel — a streamed token delta or a
214
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
215
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
216
+ * it unset).
217
+ */
218
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
219
+ /** The `agents:agentMessages` reference — live durable thread history. */
220
+ type AgentMessagesReference$1 = FunctionReference<"query", {
221
+ key: string;
222
+ limit?: number;
223
+ }, ReadonlyArray<Record<string, unknown>>>;
224
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
225
+ type AgentApprovalReference = FunctionReference<"mutation", {
226
+ decision: "approve" | "reject";
227
+ instanceId: string;
228
+ note?: string;
229
+ threadKey: string;
230
+ toolCallId: string;
231
+ }, {
232
+ resolved: boolean;
233
+ }>;
234
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
235
+ type AgentThreadReference = FunctionReference<"query", {
236
+ key: string;
237
+ }, Record<string, unknown> | undefined>;
238
+ /**
239
+ * An app stream reference that tees the agent's in-flight live events, keyed by
240
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
241
+ * sink — tool progress events; this handle consumes only the token arm.
242
+ */
243
+ type AgentTokenStreamReference = FunctionReference<"stream", {
244
+ key: string;
245
+ }, AgentLiveEvent>;
246
+ /**
247
+ * The `agents.*` reference surface the chat handle reads. A structural subset of
248
+ * the generated `api.agents`, so the whole generated `api` object is assignable.
249
+ */
250
+ interface AgentChatApi {
251
+ agents: {
252
+ agentMessages: AgentMessagesReference$1;
253
+ agentResolveApproval: AgentApprovalReference;
254
+ agentThread: AgentThreadReference;
255
+ };
256
+ }
257
+ interface AgentChatOptions {
258
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
259
+ api: AgentChatApi;
260
+ /**
261
+ * Optional app mutation over the agent's cancel path
262
+ * (`ctx.agents[name].cancel(id)`). Called with `{ instanceId, threadKey }`.
263
+ * When omitted (or no run is in flight) {@link AgentChatHandle.cancel} is a
264
+ * no-op.
265
+ */
266
+ cancel?: FunctionReference<"mutation">;
267
+ /** History depth forwarded to `agents:agentMessages`. */
268
+ limit?: number;
269
+ /**
270
+ * Called when the live history or thread subscription reports an error (a
271
+ * session expiry, an RLS denial). Without it such an error is dropped and
272
+ * `messages` / `status` freeze at their last value — unlike the React, Angular,
273
+ * Solid and Vue ports, this one leaves the value store untouched on error.
274
+ */
275
+ onError?: SubscriptionErrorCallback;
276
+ /**
277
+ * The app mutation that starts (or continues) a run — a thin wrapper over
278
+ * `ctx.agents[name].run(...)`. Called with `{ threadKey, input }` merged with
279
+ * {@link AgentChatOptions.sendArgs} and the per-call args.
280
+ */
281
+ send: FunctionReference<"mutation">;
282
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
283
+ sendArgs?: Record<string, unknown>;
284
+ /**
285
+ * Optional live token-delta stream — an app stream function that tees the
286
+ * agent's in-flight deltas. When omitted {@link AgentChatHandle.streamingText}
287
+ * stays empty and the UI updates message-by-message from durable history.
288
+ */
289
+ stream?: AgentTokenStreamReference;
290
+ /** The thread to observe and continue. */
291
+ threadKey: string;
292
+ }
293
+ interface AgentChatHandle {
294
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
295
+ approve: (toolCallId: string, note?: string) => Promise<void>;
296
+ /**
297
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
298
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
299
+ */
300
+ cancel: () => Promise<void>;
301
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. Read with `$messages`. */
302
+ messages: Readable<ReadonlyArray<AgentChatMessage>>;
303
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
304
+ reject: (toolCallId: string, note?: string) => Promise<void>;
305
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
306
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
307
+ /** The live thread status, or `undefined` before the thread exists. Read with `$status`. */
308
+ status: Readable<AgentThreadStatus | undefined>;
309
+ /**
310
+ * The in-flight turn's streamed text — live-only, `""` once the turn persists
311
+ * to `messages`. Populated when a `stream` reference is supplied (via the
312
+ * {@link stream} primitive); with no reference it stays `""` and the UI advances
313
+ * message-by-message from durable history. Read with `$streamingText`.
314
+ */
315
+ streamingText: Readable<string>;
316
+ /**
317
+ * Stop the live history + thread subscriptions (and the token stream, if any).
318
+ * Call in `onDestroy` (`onDestroy(handle.teardown)`).
319
+ */
320
+ teardown: () => void;
321
+ }
322
+ /**
323
+ * A first-class agent chat surface: live durable history + in-flight token
324
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey` —
325
+ * the Svelte counterpart to React's `useAgentChat`, re-expressed as stores you
326
+ * read with `$`.
327
+ *
328
+ * It composes the existing primitives rather than adding transport:
329
+ * `client.subscribe(api.agents.agentMessages)` for durable history,
330
+ * `client.subscribe(api.agents.agentThread)` for live status + the in-flight
331
+ * `instanceId`, {@link stream} over an app token stream for in-flight deltas, and
332
+ * {@link mutation} for the writes (`api.agents.agentResolveApproval` for approvals;
333
+ * app-defined wrappers for `send`/`cancel`). Only the `agents:*` surface is
334
+ * hard-coded — `send`/`cancel`/`stream` stay generic references.
335
+ *
336
+ * A `send` optimistically appends the user turn so it renders immediately; the
337
+ * optimistic row clears once the durable history carries the acknowledged turn.
338
+ * `streamingText` is live-only: it holds the current turn's streamed text and
339
+ * empties as soon as that turn's assistant message lands in `messages` (the
340
+ * persisted message is the source of truth); with no `stream` reference it stays
341
+ * `""` and the UI advances message-by-message from durable history. The
342
+ * subscriptions (and the token stream, if any) open eagerly and run until
343
+ * {@link AgentChatHandle.teardown} — call `onDestroy(handle.teardown)`.
344
+ *
345
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
346
+ * `setLunoraClient`.
347
+ */
348
+ declare function agentChat(options: AgentChatOptions): AgentChatHandle;
349
+ declare function agentChat(client: LunoraClient, options: AgentChatOptions): AgentChatHandle;
350
+ /**
351
+ * The `agents.agentState` reference the handle subscribes to for the thread's live
352
+ * synced state. A structural subset of the generated `api.agents` surface (like
353
+ * `AgentApi` for `agentThread`), so the whole generated `api` object is
354
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type is
355
+ * mirrored by the handle's generic `T`, since codegen pins the reference return as
356
+ * an optional record (it never evaluates agent config).
357
+ */
358
+ interface AgentStateApi {
359
+ agents: {
360
+ agentState: FunctionReference<"query", {
361
+ key: string;
362
+ }, Record<string, unknown> | undefined>;
363
+ };
364
+ }
365
+ interface AgentStateOptions {
366
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
367
+ api: AgentStateApi;
368
+ /** The thread whose synced state to observe. */
369
+ threadKey: string;
370
+ }
371
+ interface AgentStateHandle<T> {
372
+ /** Svelte readable store of the subscription error, if the live channel reported one. Read with `$error`. */
373
+ error: Readable<Error | undefined>;
374
+ /** Svelte readable store of the live synced state, or `undefined` before it is seeded/first pushed. Read with `$state`. */
375
+ state: Readable<T | undefined>;
376
+ }
377
+ /**
378
+ * Subscribe to an agent thread's synced state — the `setState`-style value a tool
379
+ * writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`. A
380
+ * thin wrapper over {@link subscription} against `api.agents.agentState`: the
381
+ * server pushes a fresh frame whenever the state changes (the dedicated query's
382
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
383
+ * `state` updates only on a real `setState`. The Svelte counterpart to React's
384
+ * `useAgentState`, re-expressed as stores you read with `$`.
385
+ *
386
+ * Generic over the app's state shape (`agentState<SupportState>(...)`, itself a
387
+ * record) — the reference is typed as an optional record because codegen cannot
388
+ * see the per-agent state type; the generic casts to `T`. The `state`/`error`
389
+ * stores are lazy, so the subscription opens on the first subscriber to `state`
390
+ * and tears down when the last one leaves — there is no `teardown` to call.
391
+ *
392
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
393
+ * `setLunoraClient`.
394
+ */
395
+ declare function agentState<T extends Record<string, unknown> = Record<string, unknown>>(options: AgentStateOptions): AgentStateHandle<T>;
396
+ declare function agentState<T extends Record<string, unknown> = Record<string, unknown>>(client: LunoraClient, options: AgentStateOptions): AgentStateHandle<T>;
397
+ /** The `agents:agentMessages` reference — live durable thread history. */
398
+ type AgentMessagesReference = FunctionReference<"query", {
399
+ key: string;
400
+ limit?: number;
401
+ }, ReadonlyArray<Record<string, unknown>>>;
402
+ /**
403
+ * An app stream reference that tees the agent's in-flight live events, keyed by
404
+ * thread. Carries token deltas and tool progress events; this handle consumes only
405
+ * the progress arm (`kind === "progress"`).
406
+ */
407
+ type AgentLiveStreamReference = FunctionReference<"stream", {
408
+ key: string;
409
+ }, AgentLiveEvent>;
410
+ /**
411
+ * The `agents.*` reference surface the tool-events handle reads. A structural
412
+ * subset of the generated `api.agents`, so the whole generated `api` object is
413
+ * assignable.
414
+ */
415
+ interface AgentToolEventsApi {
416
+ agents: {
417
+ agentMessages: AgentMessagesReference;
418
+ };
419
+ }
420
+ interface AgentToolEventsOptions {
421
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
422
+ api: AgentToolEventsApi;
423
+ /** History depth forwarded to `agents:agentMessages`. */
424
+ limit?: number;
425
+ /**
426
+ * Optional live event stream — the same app stream function `agentChat` uses.
427
+ * When supplied, ephemeral `ctx.reportProgress(...)` events for the thread are
428
+ * surfaced as `{ type: "progress" }` entries; when omitted only the durable
429
+ * lifecycle (call / result / awaiting-approval) is returned.
430
+ */
431
+ stream?: AgentLiveStreamReference;
432
+ /** The thread whose tool activity to observe. */
433
+ threadKey: string;
434
+ }
435
+ /**
436
+ * A single tool-lifecycle event for a thread. The durable arms
437
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
438
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
439
+ * stream and has no `seq`. Discriminate on `type`.
440
+ */
441
+ type AgentToolEvent = {
442
+ data: unknown;
443
+ toolCallId: string;
444
+ type: "progress";
445
+ } | {
446
+ input: unknown;
447
+ seq: number;
448
+ toolCallId: string;
449
+ toolName: string;
450
+ type: "call";
451
+ } | {
452
+ output: string;
453
+ seq: number;
454
+ status?: "approved" | "rejected";
455
+ toolCallId?: string;
456
+ toolName?: string;
457
+ type: "result";
458
+ } | {
459
+ seq: number;
460
+ toolCallId?: string;
461
+ toolName?: string;
462
+ type: "awaiting-approval";
463
+ };
464
+ interface AgentToolEventsHandle {
465
+ /**
466
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
467
+ * followed by any in-flight ephemeral progress events, recomputed from the live
468
+ * subscription + stream. Read with `$events`. With no `stream` reference only
469
+ * the durable lifecycle is surfaced. Treat as derived, not identity-stable.
470
+ */
471
+ events: Readable<ReadonlyArray<AgentToolEvent>>;
472
+ }
473
+ /**
474
+ * A focused view of a thread's tool activity: tool calls, their results,
475
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
476
+ * without the full chat message surface. The Svelte counterpart to React's
477
+ * `useAgentToolEvents`, re-expressed as a readable store you read with `$`.
478
+ *
479
+ * It composes the existing primitives rather than adding transport:
480
+ * {@link subscription} over `api.agents.agentMessages` for the durable lifecycle
481
+ * and {@link stream} over the optional app event stream for ephemeral progress,
482
+ * combined through `derived`. Progress events are live-only (the durable path never
483
+ * emits them): they ride the same sink as token deltas and are surfaced here,
484
+ * correlated to their tool call by `toolCallId`. For the conversational surface
485
+ * (messages + streaming text + approvals) use `agentChat`; this handle is the
486
+ * tool-observability slice.
487
+ *
488
+ * The underlying subscription and stream are lazy — they open when `events` gains
489
+ * its first subscriber and tear down when the last one leaves — so there is no
490
+ * `teardown` to call (unlike the write-bearing `agentChat`).
491
+ *
492
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
493
+ * `setLunoraClient`.
494
+ */
495
+ declare function agentToolEvents(options: AgentToolEventsOptions): AgentToolEventsHandle;
496
+ declare function agentToolEvents(client: LunoraClient, options: AgentToolEventsOptions): AgentToolEventsHandle;
497
+ /**
498
+ * Publish a {@link LunoraClient} on the Svelte component context so that
499
+ * descendant components can read it with {@link getLunoraClient} (or implicitly,
500
+ * via the default-client lookups inside `query`/`mutation`/`hydratePreloaded`).
501
+ *
502
+ * Call this once, high in the tree (typically your root `+layout.svelte` or
503
+ * `App.svelte`), during component initialisation — `setContext` must run while
504
+ * the component is being constructed, exactly like React's provider mounts once.
505
+ * This is the Svelte analogue of mounting `LunoraProvider`.
506
+ */
16
507
  declare const setLunoraClient: (client: LunoraClient) => LunoraClient;
17
508
  /**
18
- * Read the {@link LunoraClient} published by {@link setLunoraClient} from the
19
- * nearest ancestor. Throws if no provider is mounted, mirroring `useLunora`'s
20
- * "must be used inside a LunoraProvider" guard so the failure is loud and
21
- * early rather than a confusing `undefined` deref later.
22
- *
23
- * Must be called during component initialisation (Svelte's `getContext`
24
- * constraint); the live stores returned by `query`/`hydratePreloaded` resolve
25
- * the client eagerly at call time for exactly this reason.
26
- */
509
+ * Read the {@link LunoraClient} published by {@link setLunoraClient} from the
510
+ * nearest ancestor. Throws if no provider is mounted, mirroring `useLunora`'s
511
+ * "must be used inside a LunoraProvider" guard so the failure is loud and
512
+ * early rather than a confusing `undefined` deref later.
513
+ *
514
+ * Must be called during component initialisation (Svelte's `getContext`
515
+ * constraint); the live stores returned by `query`/`hydratePreloaded` resolve
516
+ * the client eagerly at call time for exactly this reason.
517
+ */
27
518
  declare const getLunoraClient: () => LunoraClient;
28
519
  interface AuthStore {
29
520
  /** Set the auth token on the underlying `LunoraClient`. */
@@ -34,138 +525,191 @@ interface AuthStore {
34
525
  user: Readable<User | null>;
35
526
  }
36
527
  /**
37
- * Create a pair of Svelte readable stores tracking the auth token and the
38
- * resolved user identity. The stores are lazy: subscriptions open on the first
39
- * reader and close when the last unsubscribes. Calling `setToken(jwt)` after
40
- * sign-in refreshes both stores.
41
- *
42
- * Pass an explicit client to bypass the ambient context (useful in tests).
43
- */
528
+ * Create a pair of Svelte readable stores tracking the auth token and the
529
+ * resolved user identity. The stores are lazy: subscriptions open on the first
530
+ * reader and close when the last unsubscribes. Calling `setToken(jwt)` after
531
+ * sign-in refreshes both stores.
532
+ *
533
+ * Both subscribes are client-only, like every other subscribing primitive here:
534
+ * `$token` / `$user` in a template subscribe during `renderToString`. For the
535
+ * user store that is not just a stray listener — the identity store kicks off
536
+ * `getCurrentUser()` on its first subscriber, so an unguarded server render
537
+ * issues a round-trip against a client whose URL does not resolve there. Both
538
+ * stores still report the client's current values on the server; only the live
539
+ * updates are withheld, until hydration.
540
+ *
541
+ * Pass an explicit client to bypass the ambient context (useful in tests).
542
+ */
44
543
  declare const auth: (explicitClient?: ReturnType<typeof getLunoraClient>) => AuthStore;
544
+ /** Derived auth-gate stores for template gating (`{#if $isAuthenticated}`), built on {@link auth}. */
545
+ interface AuthGateStore {
546
+ /** Readable store, `true` once a token is set and the user has resolved. */
547
+ isAuthenticated: Readable<boolean>;
548
+ /** Readable store, `true` while a token is set but the user hasn't resolved yet. */
549
+ isLoading: Readable<boolean>;
550
+ }
551
+ /**
552
+ * Derived auth-gate stores built on {@link auth}. Svelte has no JSX-style
553
+ * `Authenticated` slot component the way React/Vue/Solid do (this package is
554
+ * plain `.ts` over stores — no `.svelte` component compiler required), so this
555
+ * exposes the same three-state logic as two boolean stores instead: a token
556
+ * with no resolved user yet is `isLoading`; a token with a resolved user is
557
+ * `isAuthenticated`; no token is neither (the signed-out state a template
558
+ * checks for with a plain `{:else}`).
559
+ *
560
+ * ```ts
561
+ * import { authGate } from "@lunora/svelte";
562
+ * const { isAuthenticated, isLoading } = authGate();
563
+ * // markup: {#if $isAuthenticated} signed in {:else if $isLoading} loading… {:else} signed out {/if}
564
+ * ```
565
+ *
566
+ * Pass an explicit client to bypass the ambient context (useful in tests).
567
+ */
568
+ declare const authGate: (explicitClient?: ReturnType<typeof getLunoraClient>) => AuthGateStore;
45
569
  /** The shape held by a {@link connectionStatus} store: the latest aggregate live-socket status. */
46
570
  type ConnectionStatusStore = Readable<ConnectionStatus>;
47
571
  /**
48
- * Expose the client's aggregate live-socket status as a Svelte readable store.
49
- * Read it with the `$store` idiom (`{$status}`) and it stays current: the value
50
- * transitions through `idle` → `connecting` → `connected` → `offline` as
51
- * sockets open and drop — the Svelte equivalent of `@lunora/react`'s
52
- * `useConnectionStatus`. Use it to drive a connection indicator.
53
- *
54
- * The status listener attaches inside `readable`'s start callback (on the first
55
- * `$`-read / `.subscribe()`) and is released by the returned stop function when
56
- * the last subscriber goes away, so a store that's never read attaches nothing.
57
- *
58
- * Pass `client` explicitly, or omit it to resolve the ambient client published
59
- * by `setLunoraClient` (which must therefore be called during component init,
60
- * before this runs).
61
- */
572
+ * Expose the client's aggregate live-socket status as a Svelte readable store.
573
+ * Read it with the `$store` idiom (`{$status}`) and it stays current: the value
574
+ * transitions through `idle` → `connecting` → `connected` → `offline` as
575
+ * sockets open and drop — the Svelte equivalent of `@lunora/react`'s
576
+ * `useConnectionStatus`. Use it to drive a connection indicator.
577
+ *
578
+ * The status listener attaches inside `readable`'s start callback (on the first
579
+ * `$`-read / `.subscribe()`) and is released by the returned stop function when
580
+ * the last subscriber goes away, so a store that's never read attaches nothing.
581
+ *
582
+ * Client-only, like every other subscribing primitive here: `$status` in a
583
+ * template subscribes during `renderToString`, so an unguarded start callback
584
+ * registers a listener per server render. The store still reports the client's
585
+ * current status on the server — that value is a plain read, and nothing
586
+ * transitions during a render.
587
+ *
588
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
589
+ * by `setLunoraClient` (which must therefore be called during component init,
590
+ * before this runs).
591
+ */
62
592
  declare const connectionStatus: (client?: LunoraClient) => ConnectionStatusStore;
63
- /** A targeting context merged on top of the app's default (`defineFlags({ identify })`). */
64
- type FlagContext = Record<string, unknown>;
65
593
  /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
66
594
  type FlagValue = boolean | number | string | {
67
595
  [key: string]: unknown;
68
596
  } | unknown[] | null;
69
597
  /**
70
- * Open a single feature flag as a Svelte readable store, live over Lunora's
71
- * WebSocket. Read it with the `$store` idiom (`{$darkMode}`).
72
- *
73
- * The store holds `defaultValue` until the first evaluation lands, then the
74
- * server's resolved value — re-emitted whenever the provider re-evaluates (e.g. a
75
- * flag is toggled in Cloudflare Flagship). The flag's kind is inferred from
76
- * `defaultValue`'s runtime type, so `flag("dark", false)` reads a boolean and
77
- * `flag("hero", "control")` a string. `context` supplies a per-call targeting
78
- * context merged on top of the app's default `identify` targeting key.
79
- *
80
- * The subscription opens lazily on the first `$`-read and tears down when the
81
- * last subscriber detaches. Pass `client` explicitly, or omit it to resolve the
82
- * ambient client published by `setLunoraClient`. Evaluation never throws — a
83
- * provider error resolves the default (the same fail-open contract as `ctx.flags`).
84
- */
85
- declare function flag<T extends FlagValue>(key: string, defaultValue: T, context?: FlagContext): Readable<T>;
86
- declare function flag<T extends FlagValue>(client: LunoraClient, key: string, defaultValue: T, context?: FlagContext): Readable<T>;
87
- /**
88
- * Open several feature flags at once as a single Svelte readable store of the
89
- * resolved record, live over Lunora's WebSocket.
90
- *
91
- * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
92
- * default, and the store holds the same-shaped record with resolved values (the
93
- * defaults until each evaluation lands). A single `context` applies to every
94
- * flag. This is the batched form of {@link flag} — one store, one subscription
95
- * per key, torn down together when the last subscriber detaches.
96
- *
97
- * Pass `client` explicitly, or omit it to resolve the ambient client published
98
- * by `setLunoraClient`.
99
- */
100
- declare function flags<T extends Record<string, FlagValue>>(flagDefaults: T, context?: FlagContext): Readable<T>;
101
- declare function flags<T extends Record<string, FlagValue>>(client: LunoraClient, flagDefaults: T, context?: FlagContext): Readable<T>;
102
- /**
103
- * Hydrate a query store from a {@link Preloaded} token produced by
104
- * `preloadQuery` during SSR, then keep it live — the reactive-loader handoff.
105
- *
106
- * The store is seeded **synchronously** with `preloaded.value`, so the very
107
- * first read (`$store` during hydration) returns the server value with no
108
- * loading flash and no hydration mismatch — there is no `undefined` window and
109
- * no refetch. When the store gains its first subscriber on the client, a live
110
- * WS subscription attaches and every subsequent delta re-emits, exactly like a
111
- * plain `query` store. This is the Svelte equivalent of React's
112
- * `usePreloadedQuery`.
113
- *
114
- * Pass `client` explicitly, or omit it to resolve the ambient client published
115
- * by `setLunoraClient`.
116
- *
117
- * Note on SSR: `readable`'s start callback only runs when the store is actually
118
- * subscribed (the browser), so on the server the store simply holds the seeded
119
- * value and opens no socket. The token's `value` is the single source of truth
120
- * for the first paint either way.
121
- */
122
- declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, client?: LunoraClient) => Readable<T>;
123
- /**
124
- * The reactive handle returned by {@link mutation} — the Svelte counterpart to
125
- * React's `useMutation`, re-expressed as stores you read with `$`. The surface
126
- * is identical across the Lunora adapters (`@lunora/solid`, `/vue`):
127
- * `data`/`error`/`pending` are readable stores and `mutate` is an awaitable.
128
- */
598
+ * Open a single feature flag as a Svelte readable store, live over Lunora's
599
+ * WebSocket. Read it with the `$store` idiom (`{$darkMode}`).
600
+ *
601
+ * The store holds `defaultValue` until the first evaluation lands, then the
602
+ * server's resolved value — re-emitted whenever the provider re-evaluates (e.g. a
603
+ * flag is toggled in Cloudflare Flagship). The flag's kind is inferred from
604
+ * `defaultValue`'s runtime type, so `flag("dark", false)` reads a boolean and
605
+ * `flag("hero", "control")` a string.
606
+ *
607
+ * The reactive channel is public, so the server evaluates every flag under the
608
+ * socket's own verified identity — the targeting key your `defineFlags({
609
+ * identify })` derives — and accepts no client-supplied targeting context. For
610
+ * evaluation under a context you compute, call `ctx.flags.*` inside a query,
611
+ * mutation, or action and return the resolved value.
612
+ *
613
+ * The subscription opens lazily on the first `$`-read and tears down when the
614
+ * last subscriber detaches. Pass `client` explicitly, or omit it to resolve the
615
+ * ambient client published by `setLunoraClient`. Evaluation never throws — a
616
+ * provider error resolves the default (the same fail-open contract as `ctx.flags`).
617
+ */
618
+ declare function flag<T extends FlagValue>(key: string, defaultValue: T): Readable<T>;
619
+ declare function flag<T extends FlagValue>(client: LunoraClient, key: string, defaultValue: T): Readable<T>;
620
+ /**
621
+ * Open several feature flags at once as a single Svelte readable store of the
622
+ * resolved record, live over Lunora's WebSocket.
623
+ *
624
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
625
+ * default, and the store holds the same-shaped record with resolved values (the
626
+ * defaults until each evaluation lands). This is the batched form of {@link flag}
627
+ * — one store, one subscription per key, torn down together when the last
628
+ * subscriber detaches. Like {@link flag} it evaluates under the socket's
629
+ * server-verified identity only.
630
+ *
631
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
632
+ * by `setLunoraClient`.
633
+ */
634
+ declare function flags<T extends Record<string, FlagValue>>(flagDefaults: T): Readable<T>;
635
+ declare function flags<T extends Record<string, FlagValue>>(client: LunoraClient, flagDefaults: T): Readable<T>;
636
+ /**
637
+ * Hydrate a query store from a {@link Preloaded} token produced by
638
+ * `preloadQuery` during SSR, then keep it live — the reactive-loader handoff.
639
+ *
640
+ * The store is seeded **synchronously** with `preloaded.value`, so the very
641
+ * first read (`$store` during hydration) returns the server value with no
642
+ * loading flash and no hydration mismatch — there is no `undefined` window and
643
+ * no refetch. When the store gains its first subscriber on the client, a live
644
+ * WS subscription attaches and every subsequent delta re-emits, exactly like a
645
+ * plain `query` store. This is the Svelte equivalent of React's
646
+ * `usePreloadedQuery`.
647
+ *
648
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
649
+ * by `setLunoraClient`. Pass `onError` to surface a subscription-scoped error the
650
+ * server pushes (a session expiry, an RLS denial); without it such an error is
651
+ * dropped and the store keeps rendering the SSR snapshot as if it were live.
652
+ *
653
+ * Note on SSR: `readable`'s start callback DOES run on the server — svelte's
654
+ * server runtime resolves `{$store}` by subscribing to it — so the socket is
655
+ * opened behind an explicit `isBrowser()` guard rather than left to the store's
656
+ * laziness. On the server the store simply holds the seeded value. The token's
657
+ * `value` is the single source of truth for the first paint either way.
658
+ */
659
+ declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, client?: LunoraClient, options?: {
660
+ onError?: SubscriptionErrorCallback;
661
+ }) => Readable<T>;
662
+ /**
663
+ * The reactive handle returned by {@link mutation} — the Svelte counterpart to
664
+ * React's `useMutation`, re-expressed as stores you read with `$`. The surface
665
+ * is identical across the Lunora adapters (`@lunora/solid`, `/vue`):
666
+ * `data`/`error`/`pending` are readable stores and `mutate` is an awaitable.
667
+ */
129
668
  interface MutationHandle<F extends FunctionReference> {
130
669
  /** The latest invocation's resolved value, or `undefined` before the first success. */
131
670
  data: Readable<ReturnOf<F> | undefined>;
132
671
  /** The latest invocation's error, or `undefined`. */
133
672
  error: Readable<Error | undefined>;
134
673
  /**
135
- * Run the mutation. Resolves with the server result and rejects on failure
136
- * (errors propagate — there is no swallowing). Optimistic updates passed in
137
- * `options` are applied and rolled back by the client against the live query
138
- * subscriptions, exactly as in the React adapter.
139
- */
674
+ * Run the mutation. Resolves with the server result and rejects on failure
675
+ * (errors propagate — there is no swallowing). Optimistic updates passed in
676
+ * `options` are applied and rolled back by the client against the live query
677
+ * subscriptions, exactly as in the React adapter.
678
+ */
140
679
  mutate: (args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>;
141
680
  /**
142
- * `true` while any invocation from this handle is in flight. Ref-counted, so
143
- * overlapping calls compose and it only flips back to `false` once the last
144
- * one settles. Read it with `$pending` in a component to disable a button.
145
- */
681
+ * `true` while any invocation from this handle is in flight. Ref-counted, so
682
+ * overlapping calls compose and it only flips back to `false` once the last
683
+ * one settles. Read it with `$pending` in a component to disable a button.
684
+ */
146
685
  pending: Readable<boolean>;
147
686
  /** Clear `data`/`error` back to idle. */
148
687
  reset: () => void;
149
688
  }
150
689
  /**
151
- * Create an optimistic {@link MutationHandle} for a mutation reference. The
152
- * Svelte counterpart to React's `useMutation`: returns
153
- * `{ data, error, pending, mutate, reset }` of readable stores plus an awaitable
154
- * `mutate`. The ref-counted pending + error-normalize orchestration is the
155
- * shared `createMutationRunner` from `@lunora/client`; only the stores are
156
- * adapter-specific.
157
- *
158
- * Pass `client` explicitly, or omit it to resolve the ambient client published
159
- * by `setLunoraClient`.
160
- */
690
+ * Create an optimistic {@link MutationHandle} for a mutation reference. The
691
+ * Svelte counterpart to React's `useMutation`: returns
692
+ * `{ data, error, pending, mutate, reset }` of readable stores plus an awaitable
693
+ * `mutate`. The ref-counted pending + error-normalize orchestration is the
694
+ * shared `createCallRunner` from `@lunora/client`; only the stores are
695
+ * adapter-specific.
696
+ *
697
+ * `data`/`error` follow the adapter-wide contract: both track the LATEST
698
+ * invocation (an earlier call settling later cannot clobber a newer one), a
699
+ * success clears `error`, and a failure leaves the previous `data` in place.
700
+ * `reset()` clears both; it does not cancel an in-flight call.
701
+ *
702
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
703
+ * by `setLunoraClient`.
704
+ */
161
705
  declare function mutation<F extends FunctionReference>(function_: F): MutationHandle<F>;
162
706
  declare function mutation<F extends FunctionReference>(client: LunoraClient, function_: F): MutationHandle<F>;
163
707
  /**
164
- * The reactive handle returned by {@link mutator} — the Svelte counterpart to
165
- * `@lunora/react`'s `useMutator`, re-expressed as stores you read with `$`.
166
- * `error`/`isError`/`pending` are readable stores and `mutate` is an awaitable
167
- * that resolves once the write is persisted (or rejects).
168
- */
708
+ * The reactive handle returned by {@link mutator} — the Svelte counterpart to
709
+ * `@lunora/react`'s `useMutator`, re-expressed as stores you read with `$`.
710
+ * `error`/`isError`/`pending` are readable stores and `mutate` is an awaitable
711
+ * that resolves once the write is persisted (or rejects).
712
+ */
169
713
  interface MutatorHandleStore<TArgs> {
170
714
  /** The latest invocation's error, or `undefined`. */
171
715
  error: Readable<Error | undefined>;
@@ -179,20 +723,22 @@ interface MutatorHandleStore<TArgs> {
179
723
  reset: () => void;
180
724
  }
181
725
  /**
182
- * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
183
- * custom-mutator handle from `@lunora/db`'s `bindMutators` — the Svelte
184
- * equivalent of `@lunora/react`'s `useMutator`. The optimistic overlay and
185
- * server-authoritative push are owned by the bound handle (and TanStack DB's
186
- * optimistic-transaction layer rebases pending overlays on every sync tick);
187
- * this helper only surfaces store state for the in-flight/error lifecycle. Reads
188
- * stay on the existing TanStack `useLiveQuery`; no new query store is needed.
189
- *
190
- * `pending` is ref-counted across overlapping invocations of THIS handle, so it
191
- * clears only once every concurrent call has settled.
192
- */
726
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
727
+ * custom-mutator handle from `@lunora/db`'s `bindMutators` — the Svelte
728
+ * equivalent of `@lunora/react`'s `useMutator`. The optimistic overlay and
729
+ * server-authoritative push are owned by the bound handle (and TanStack DB's
730
+ * optimistic-transaction layer rebases pending overlays on every sync tick);
731
+ * this helper only surfaces store state for the in-flight/error lifecycle. Reads
732
+ * stay on the existing TanStack `useLiveQuery`; no new query store is needed.
733
+ *
734
+ * `pending` is ref-counted across overlapping invocations of THIS handle, so it
735
+ * clears only once every concurrent call has settled.
736
+ */
193
737
  declare const mutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHandleStore<TArgs>;
194
738
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
195
739
  type PaginatedArgs<F extends FunctionReference> = Omit<ArgsOf<F>, "paginationOpts">;
740
+ /** Paginated args, the skip sentinel, or a reactive (`Readable`) source of either. */
741
+ type ReactivePaginatedArgs<F extends FunctionReference> = "skip" | PaginatedArgs<F> | Readable<"skip" | PaginatedArgs<F>>;
196
742
  /** The element type of the `page` array a paginated query returns. */
197
743
  type PageItemOf<F extends FunctionReference> = ReturnOf<F> extends {
198
744
  page: (infer T)[];
@@ -200,9 +746,18 @@ type PageItemOf<F extends FunctionReference> = ReturnOf<F> extends {
200
746
  interface PaginatedQueryOptions {
201
747
  /** Page size for the first page (and the default for `loadMore`). */
202
748
  initialNumItems: number;
749
+ /** Called when a page subscription reports an error (also surfaced on the `error` store). */
750
+ onError?: SubscriptionErrorCallback;
203
751
  shardKey?: string;
204
752
  }
205
753
  interface PaginatedQueryHandle<T> {
754
+ /**
755
+ * The last page subscription error, or `undefined`. A tail page that fails
756
+ * before its first frame is dropped so `status` returns to `"CanLoadMore"`
757
+ * and `loadMore` can retry it; cleared by the next successful frame,
758
+ * `loadMore`, or an args emission.
759
+ */
760
+ error: Readable<SubscriptionError | undefined>;
206
761
  /** `true` while the first page or a `loadMore` page is in flight. */
207
762
  isLoading: Readable<boolean>;
208
763
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
@@ -214,9 +769,13 @@ interface PaginatedQueryHandle<T> {
214
769
  interface InfiniteQueryOptions {
215
770
  /** Page size for the first page (and the default for `fetchNextPage`). */
216
771
  initialNumItems: number;
772
+ /** Called when a page subscription reports an error (also surfaced on the `error` store). */
773
+ onError?: SubscriptionErrorCallback;
217
774
  shardKey?: string;
218
775
  }
219
776
  interface InfiniteQueryHandle<T> {
777
+ /** The last page subscription error, or `undefined` — see `PaginatedQueryHandle.error`. */
778
+ error: Readable<SubscriptionError | undefined>;
220
779
  /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
221
780
  fetchNextPage: (numberItems?: number) => void;
222
781
  /** `true` when the loaded tail reports it can load another page. */
@@ -230,46 +789,50 @@ interface InfiniteQueryHandle<T> {
230
789
  status: Readable<PaginationStatus>;
231
790
  }
232
791
  /**
233
- * Open a live paginated query as Svelte stores. The first page opens when
234
- * called; call `loadMore(n)` to append the next page. Results are flattened
235
- * across all loaded pages.
236
- *
237
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
238
- * Svelte context.
239
- */
240
- declare function paginatedQuery<F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: PaginatedQueryOptions): PaginatedQueryHandle<PageItemOf<F>>;
241
- declare function paginatedQuery<F extends FunctionReference>(client: LunoraClient, function_: F, args: "skip" | PaginatedArgs<F>, options: PaginatedQueryOptions): PaginatedQueryHandle<PageItemOf<F>>;
242
- /**
243
- * Open a live paginated query as Svelte stores, keeping each page as its own
244
- * inner array (TanStack-Query-style `fetchNextPage` / `hasNextPage` shape).
245
- *
246
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
247
- * Svelte context.
248
- */
792
+ * Open a live paginated query as Svelte stores. The first page opens when
793
+ * called; call `loadMore(n)` to append the next page. Results are flattened
794
+ * across all loaded pages.
795
+ *
796
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
797
+ * Svelte context.
798
+ *
799
+ * `args` may also be a `Readable` store: each emission tears the engine down
800
+ * and rebuilds it against the new args (pagination resets to the first page);
801
+ * a `"skip"` emission tears down without re-opening.
802
+ */
803
+ declare function paginatedQuery<F extends FunctionReference>(function_: F, args: ReactivePaginatedArgs<F>, options: PaginatedQueryOptions): PaginatedQueryHandle<PageItemOf<F>>;
804
+ declare function paginatedQuery<F extends FunctionReference>(client: LunoraClient, function_: F, args: ReactivePaginatedArgs<F>, options: PaginatedQueryOptions): PaginatedQueryHandle<PageItemOf<F>>;
805
+ /**
806
+ * Open a live paginated query as Svelte stores, keeping each page as its own
807
+ * inner array (TanStack-Query-style `fetchNextPage` / `hasNextPage` shape).
808
+ *
809
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
810
+ * Svelte context.
811
+ */
249
812
  declare function infiniteQuery<F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: InfiniteQueryOptions): InfiniteQueryHandle<PageItemOf<F>>;
250
813
  declare function infiniteQuery<F extends FunctionReference>(client: LunoraClient, function_: F, args: "skip" | PaginatedArgs<F>, options: InfiniteQueryOptions): InfiniteQueryHandle<PageItemOf<F>>;
251
814
  /**
252
- * `presence` — collaborative-awareness stores, the client half of the
253
- * `@lunora/server` `definePresence` preset.
254
- *
255
- * Drives the heartbeat mutation (on call, interval, and tab re-focus) and
256
- * subscribes to the live `listPresent` query for the given room.
257
- *
258
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
259
- * Svelte context.
260
- */
261
- /**
262
- * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }`.
263
- */
815
+ * `presence` — collaborative-awareness stores, the client half of the
816
+ * `@lunora/server` `definePresence` preset.
817
+ *
818
+ * Drives the heartbeat mutation (on call, interval, and tab re-focus) and
819
+ * subscribes to the live `listPresent` query for the given room.
820
+ *
821
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
822
+ * Svelte context.
823
+ */
824
+ /**
825
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }`.
826
+ */
264
827
  type HeartbeatReference = FunctionReference<"mutation", {
265
828
  data?: Record<string, unknown>;
266
829
  roomId: string;
267
830
  sessionId: string;
268
831
  }>;
269
832
  /**
270
- * A listPresent query reference: takes `{ roomId }` and returns the array of
271
- * present members.
272
- */
833
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
834
+ * present members.
835
+ */
273
836
  type ListPresentReference = FunctionReference<"query", {
274
837
  roomId: string;
275
838
  }>;
@@ -283,14 +846,22 @@ interface PresenceOptions<H extends HeartbeatReference, L extends ListPresentRef
283
846
  /** The `api.*` reference for the presence listPresent query. */
284
847
  listPresent: L;
285
848
  /**
286
- * Stable id for this presence row. Defaults to a fresh per-mount id.
287
- * Pass a user/connection id to control deduping across tabs.
288
- */
849
+ * Called when the `listPresent` subscription reports an error (a session
850
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
851
+ * failure is invisible and `present` freezes at its last value.
852
+ */
853
+ onError?: SubscriptionErrorCallback;
854
+ /**
855
+ * Stable id for this presence row. Defaults to a fresh per-mount id.
856
+ * Pass a user/connection id to control deduping across tabs.
857
+ */
289
858
  sessionId?: string;
290
859
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
291
860
  shardKey?: string;
292
861
  }
293
862
  interface PresenceHandle<L extends ListPresentReference> {
863
+ /** The `listPresent` subscription's last error, or `undefined`. */
864
+ error: Readable<SubscriptionError | undefined>;
294
865
  /** The present members for the room. `undefined` until the first push. */
295
866
  present: Readable<ReturnOf<L> | undefined>;
296
867
  /** This handle's session id. */
@@ -301,17 +872,22 @@ interface PresenceHandle<L extends ListPresentReference> {
301
872
  teardown: () => void;
302
873
  }
303
874
  /**
304
- * Open a live presence handle.
305
- *
306
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
307
- * Svelte context (requires calling inside a component's `&lt;script>` block or
308
- * inside a function called during component initialisation).
309
- *
310
- * Call `teardown()` when the component is destroyed to stop heartbeats and
311
- * remove the visibility listener (`onDestroy(handle.teardown)`).
312
- */
875
+ * Open a live presence handle.
876
+ *
877
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
878
+ * Svelte context (requires calling inside a component's `<script>` block or
879
+ * inside a function called during component initialisation).
880
+ *
881
+ * Teardown (stop heartbeats, remove the visibility listener, release the
882
+ * connection context) is wired automatically to the component's `onDestroy`
883
+ * when called during component initialisation. Outside a component call
884
+ * `handle.teardown()` yourself. `teardown()` is idempotent, so an explicit
885
+ * `onDestroy(handle.teardown)` on top of the auto-wiring is safe.
886
+ */
313
887
  declare function presence<H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: PresenceOptions<H, L>): PresenceHandle<L>;
314
888
  declare function presence<H extends HeartbeatReference, L extends ListPresentReference>(client: LunoraClient, roomId: string, options: PresenceOptions<H, L>): PresenceHandle<L>;
889
+ /** Query args, the skip sentinel, or a reactive (`Readable`) source of either. */
890
+ type ReactiveArgs<F extends FunctionReference> = ArgsOf<F> | "skip" | Readable<ArgsOf<F> | "skip">;
315
891
  /** Options accepted by {@link query}. */
316
892
  interface QueryStoreOptions {
317
893
  /** Called when the underlying subscription reports an error. */
@@ -320,36 +896,48 @@ interface QueryStoreOptions {
320
896
  shardKey?: string;
321
897
  }
322
898
  /**
323
- * The shape held by a {@link query} store: the latest server value (`undefined`
324
- * until the first response lands, mirroring React's `useQuery`).
325
- */
899
+ * The shape held by a {@link query} store: the latest server value (`undefined`
900
+ * until the first response lands, mirroring React's `useQuery`).
901
+ */
326
902
  type QueryStore<F extends FunctionReference> = Readable<ReturnOf<F> | undefined>;
327
903
  /**
328
- * Open a live query as a Svelte readable store. Read it with the `$store`
329
- * idiom in a component (`{$messages}`) and it stays current: a WS subscription
330
- * attaches the moment the store gains its first subscriber and the value
331
- * re-emits on every server delta — the Svelte equivalent of React's `useQuery`.
332
- *
333
- * The subscription is opened lazily (inside `readable`'s start callback, on the
334
- * first `$`-read / `.subscribe()`) and torn down by the returned stop function
335
- * when the last subscriber goes away — so a store that's never read opens no
336
- * socket, and a component that unmounts releases its subscription. Sharing one
337
- * store across several components shares a single underlying subscription
338
- * (the `LunoraClient` de-dupes by `(fn, args, shardKey)`).
339
- *
340
- * Pass `client` explicitly, or omit it to resolve the ambient client published
341
- * by `setLunoraClient` (which must therefore be called during component init,
342
- * before this runs).
343
- */
344
- declare function query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: QueryStoreOptions): QueryStore<F>;
345
- declare function query<F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: QueryStoreOptions): QueryStore<F>;
904
+ * Open a live query as a Svelte readable store. Read it with the `$store`
905
+ * idiom in a component (`{$messages}`) and it stays current: a WS subscription
906
+ * attaches the moment the store gains its first subscriber and the value
907
+ * re-emits on every server delta — the Svelte equivalent of React's `useQuery`.
908
+ *
909
+ * The subscription is opened lazily (inside `readable`'s start callback, on the
910
+ * first `$`-read / `.subscribe()`) and only in the browser — a server render
911
+ * reads the store's `undefined` seed and opens nothing. It is torn down by the
912
+ * returned stop function when the last subscriber goes away — so a store that's
913
+ * never read opens no socket, and a component that unmounts releases its
914
+ * subscription. Sharing one
915
+ * store across several components shares a single underlying subscription
916
+ * (the `LunoraClient` de-dupes by `(fn, args, shardKey)`).
917
+ *
918
+ * Pass `"skip"` as `args` to keep the store connected but the subscription
919
+ * dormant (the value stays `undefined`, no socket opens) — useful for a query
920
+ * gated on auth or a route param, matching React/Vue/Solid's `useQuery`.
921
+ *
922
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
923
+ * by `setLunoraClient` (which must therefore be called during component init,
924
+ * before this runs).
925
+ *
926
+ * `args` may also be a `Readable` store (wrap runes state with `toStore` or
927
+ * `derived`): each emission tears down the previous subscription, resets the
928
+ * value to `undefined`, and opens a fresh one against the new args — the Svelte
929
+ * counterpart of Vue's `MaybeRefOrGetter` args. An emission of `"skip"` tears down without
930
+ * re-opening and resets the value to `undefined`.
931
+ */
932
+ declare function query<F extends FunctionReference>(function_: F, args: ReactiveArgs<F>, options?: QueryStoreOptions): QueryStore<F>;
933
+ declare function query<F extends FunctionReference>(client: LunoraClient, function_: F, args: ReactiveArgs<F>, options?: QueryStoreOptions): QueryStore<F>;
346
934
  interface RateLimitOptions {
347
935
  /** Clock injection for tests. Defaults to `Date.now`. */
348
936
  now?: () => number;
349
937
  /**
350
- * Re-evaluation cadence in milliseconds while throttled, so `retryAfter`
351
- * ticks down and `disabled` flips back automatically. Defaults to `1000`.
352
- */
938
+ * Re-evaluation cadence in milliseconds while throttled, so `retryAfter`
939
+ * ticks down and `disabled` flips back automatically. Defaults to `1000`.
940
+ */
353
941
  tickMs?: number;
354
942
  }
355
943
  interface RateLimitHandle {
@@ -369,17 +957,65 @@ interface RateLimitHandle {
369
957
  teardown: () => void;
370
958
  }
371
959
  /**
372
- * Client-side mirror of a rate limit for instant UX — disable a button or show
373
- * a countdown without a round-trip. It runs the same token-bucket / fixed-window
374
- * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
375
- * authoritative check; the server remains the source of truth.
376
- *
377
- * `config` is read on every call; pass a stable reference (module constant).
378
- *
379
- * Call `teardown()` when the component is destroyed to stop the auto-tick
380
- * interval (`onDestroy(handle.teardown)`).
381
- */
960
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
961
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
962
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
963
+ * authoritative check; the server remains the source of truth.
964
+ *
965
+ * `config` is read on every call; pass a stable reference (module constant).
966
+ *
967
+ * Call `teardown()` when the component is destroyed to stop the auto-tick
968
+ * interval (`onDestroy(handle.teardown)`).
969
+ */
382
970
  declare const rateLimit: (config: RateLimitConfig, options?: RateLimitOptions) => RateLimitHandle;
971
+ /** The lifecycle of a stream the store is observing. */
972
+ type StreamStatus = "complete" | "error" | "idle" | "streaming";
973
+ interface StreamStoreOptions {
974
+ /**
975
+ * Opt into resume-on-reconnect for a stream the server declared `durable`.
976
+ * The chunks already received are kept and the socket re-attaches to the same
977
+ * run, so a dropped connection mid-generation continues instead of surfacing
978
+ * `STREAM_DISCONNECTED`. Has no effect on an ephemeral stream.
979
+ */
980
+ durable?: boolean;
981
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
982
+ maxBuffer?: number;
983
+ shardKey?: string;
984
+ }
985
+ interface StreamHandle<T> {
986
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
987
+ cancel: () => void;
988
+ /** Svelte readable store of the chunks the server has pushed so far, in arrival order. */
989
+ chunks: Readable<ReadonlyArray<T>>;
990
+ /** Svelte readable store of the last stream error (`undefined` when healthy). */
991
+ error: Readable<Error | undefined>;
992
+ /** Svelte readable store of the stream lifecycle status. */
993
+ status: Readable<StreamStatus>;
994
+ /**
995
+ * Stop the stream and release the iterator. Call in `onDestroy`
996
+ * (`onDestroy(handle.teardown)`) when you consume `chunks` eagerly; when you
997
+ * read `chunks` with `$` the store tears itself down as the last subscriber
998
+ * leaves.
999
+ */
1000
+ teardown: () => void;
1001
+ }
1002
+ /**
1003
+ * Open a streaming query and expose its chunks, lifecycle status, and last error
1004
+ * as Svelte readable stores. The `chunks` store is lazy: the stream opens on the
1005
+ * first browser-side subscriber to `chunks` and is cancelled when the last one
1006
+ * leaves (its chunks reset on the next open); a server render opens nothing.
1007
+ * `status` and `error` mirror that same stream.
1008
+ *
1009
+ * Passing `"skip"` as `args` keeps the stores connected but the stream dormant
1010
+ * (`chunks` stays empty, `status` stays `"idle"`). The Svelte counterpart to
1011
+ * React's `useStream`, re-expressed as stores you read with `$`.
1012
+ *
1013
+ * Pass an explicit `client` as the first argument to bypass the ambient context
1014
+ * (useful in tests), or omit it to resolve the client published by
1015
+ * `setLunoraClient`.
1016
+ */
1017
+ declare function stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F> | "skip", options?: StreamStoreOptions): StreamHandle<ReturnOf<F>>;
1018
+ declare function stream<F extends FunctionReference<"stream">>(client: LunoraClient, function_: F, args: ArgsOf<F> | "skip", options?: StreamStoreOptions): StreamHandle<ReturnOf<F>>;
383
1019
  interface SubscriptionStoreOptions {
384
1020
  onError?: (error: Error) => void;
385
1021
  shardKey?: string;
@@ -391,15 +1027,239 @@ interface SubscriptionHandle<T> {
391
1027
  error: Readable<Error | undefined>;
392
1028
  }
393
1029
  /**
394
- * Create a pair of Svelte readable stores that open a live subscription
395
- * against the Lunora backend. `data` updates on every server push; `error`
396
- * captures the last subscription error. Both stores are lazy: the subscription
397
- * opens on the first subscriber to `data` and tears down when it stops.
398
- *
399
- * Passing `"skip"` as `args` keeps the stores connected but the subscription
400
- * dormant (`data` stays `undefined`). Pass an explicit `client` as the first
401
- * argument to bypass the ambient context (useful in tests).
402
- */
403
- declare function subscription<F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: SubscriptionStoreOptions): SubscriptionHandle<ReturnOf<F>>;
404
- declare function subscription<F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F> | "skip", options?: SubscriptionStoreOptions): SubscriptionHandle<ReturnOf<F>>;
405
- export { type AuthStore, type ConnectionStatusStore, type FlagContext, type FlagValue, type HeartbeatReference, type InfiniteQueryHandle, type InfiniteQueryOptions, type ListPresentReference, type MutationHandle, type MutatorHandleStore, type PageItemOf, type PaginatedArgs, type PaginatedQueryHandle, type PaginatedQueryOptions, type PresenceHandle, type PresenceOptions, type QueryStore, type QueryStoreOptions, type RateLimitHandle, type RateLimitOptions, type SubscriptionHandle, type SubscriptionStoreOptions, auth, connectionStatus, flag, flags, getLunoraClient, hydratePreloaded, infiniteQuery, mutation, mutator, paginatedQuery, presence, query, rateLimit, setLunoraClient, subscription };
1030
+ * Create a pair of Svelte readable stores that open a live subscription
1031
+ * against the Lunora backend. `data` updates on every server push; `error`
1032
+ * captures the last subscription error. Both stores are lazy: the
1033
+ * subscription opens on the first browser-side subscriber to `data` and tears
1034
+ * down when it stops. A server render subscribes too (svelte resolves `{$store}`
1035
+ * that way) and opens nothing.
1036
+ *
1037
+ * Passing `"skip"` as `args` keeps the stores connected but the subscription
1038
+ * dormant (`data` stays `undefined`). Pass an explicit `client` as the first
1039
+ * argument to bypass the ambient context (useful in tests).
1040
+ *
1041
+ * `args` may also be a `Readable` store: each emission tears down the previous
1042
+ * subscription, resets `data` to `undefined`, and opens a fresh one; a `"skip"`
1043
+ * emission tears down without re-opening.
1044
+ */
1045
+ declare function subscription<F extends FunctionReference>(function_: F, args: ReactiveArgs<F>, options?: SubscriptionStoreOptions): SubscriptionHandle<ReturnOf<F>>;
1046
+ declare function subscription<F extends FunctionReference>(client: LunoraClient, function_: F, args: ReactiveArgs<F>, options?: SubscriptionStoreOptions): SubscriptionHandle<ReturnOf<F>>;
1047
+ /**
1048
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
1049
+ * capture and speaker playback implementations injected into the composable via
1050
+ * its `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
1051
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
1052
+ * composable's transport + reactive-state logic and remains mockable in a
1053
+ * non-browser test env.
1054
+ */
1055
+ /**
1056
+ * The negotiated audio format the voice DO streams back. Mirrors
1057
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1058
+ * imported) so this Svelte package never pulls in the server-only `@lunora/agent`
1059
+ * module graph.
1060
+ */
1061
+ type VoiceAudioFormat = "mp3" | "wav";
1062
+ /** Captures microphone audio and reports level / turn boundaries back to the composable. */
1063
+ interface VoiceMicrophone {
1064
+ /** Mute/unmute the mic without tearing down the capture graph. */
1065
+ setMuted: (muted: boolean) => void;
1066
+ /** Stop capture and release the media stream + audio graph. */
1067
+ stop: () => void;
1068
+ }
1069
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1070
+ interface VoiceSpeaker {
1071
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1072
+ enqueue: (audio: Uint8Array) => void;
1073
+ /** Drop everything queued and stop the current chunk (barge-in). */
1074
+ interrupt: () => void;
1075
+ /** Release the playback audio context. */
1076
+ stop: () => void;
1077
+ }
1078
+ /** Config passed to a {@link CreateMicrophone} factory. */
1079
+ interface MicrophoneConfig {
1080
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1081
+ interruptChunks: number;
1082
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1083
+ interruptThreshold: number;
1084
+ /**
1085
+ * `true` from the moment a turn is committed until it completes — the whole
1086
+ * `thinking` + `speaking` window, not just the audible half.
1087
+ *
1088
+ * It gates BOTH branches below, and the wider span is the point. Gated only
1089
+ * on "audibly speaking", turn detection kept running through the entire
1090
+ * STT+LLM window after a `commit`: room noise at the (deliberately low)
1091
+ * `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
1092
+ * `commit`, and the DO refused it with "a turn is already in progress" —
1093
+ * a refusal that returns before draining the audio buffer, so the PCM
1094
+ * captured since the first commit leaked into the next utterance.
1095
+ *
1096
+ * A genuine barge-in still works in that window: it routes through the
1097
+ * `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
1098
+ * `interruptThreshold` — an order of magnitude above `silenceThreshold` —
1099
+ * and `interrupt` is exactly what the DO tells the client to send.
1100
+ */
1101
+ isTurnActive: () => boolean;
1102
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1103
+ onAudio: (pcm: Uint8Array) => void;
1104
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1105
+ onInterrupt: () => void;
1106
+ /** The current input RMS (0–1), for a level meter. */
1107
+ onLevel: (rms: number) => void;
1108
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1109
+ onSilence: () => void;
1110
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1111
+ silenceDurationMs: number;
1112
+ /** RMS below which audio counts as silence. */
1113
+ silenceThreshold: number;
1114
+ }
1115
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1116
+ type CreateSpeaker = (config: {
1117
+ audioFormat: VoiceAudioFormat;
1118
+ }) => VoiceSpeaker;
1119
+ /**
1120
+ * The `agents.<name>Voice` reference codegen emits for a voice-enabled agent — a
1121
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1122
+ * generated member, so passing `api.agents.<name>Voice` type-checks.
1123
+ */
1124
+ type VoiceReference = FunctionReference<"stream", {
1125
+ threadKey: string;
1126
+ }, Record<string, unknown>>;
1127
+ /** The lifecycle of a voice call, mirrored to the UI. */
1128
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1129
+ /** A minimal structural subset of the DOM `WebSocket` the handle drives. */
1130
+ interface VoiceSocket {
1131
+ binaryType: string;
1132
+ close: () => void;
1133
+ onclose: ((event: unknown) => void) | null;
1134
+ onerror: ((event: unknown) => void) | null;
1135
+ onmessage: ((event: {
1136
+ data: unknown;
1137
+ }) => void) | null;
1138
+ onopen: ((event: unknown) => void) | null;
1139
+ readonly readyState: number;
1140
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1141
+ }
1142
+ type CreateSocket = (url: string) => VoiceSocket;
1143
+ interface VoiceAgentOptions {
1144
+ /**
1145
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1146
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1147
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1148
+ */
1149
+ createMicrophone?: CreateMicrophone;
1150
+ /**
1151
+ * Advanced/test seam: open the transport. Defaults to the WebSocket
1152
+ * implementation the client was built with (`client.getWebSocketImpl()`),
1153
+ * NOT a raw `globalThis.WebSocket`.
1154
+ */
1155
+ createSocket?: CreateSocket;
1156
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1157
+ createSpeaker?: CreateSpeaker;
1158
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1159
+ interruptChunks?: number;
1160
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1161
+ interruptThreshold?: number;
1162
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1163
+ silenceDurationMs?: number;
1164
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1165
+ silenceThreshold?: number;
1166
+ /** The thread to converse on — shared with the agent's text turns. */
1167
+ threadKey: string;
1168
+ /** The generated `api.agents.<name>Voice` reference — identifies the voice DO endpoint. */
1169
+ voice: VoiceReference;
1170
+ }
1171
+ interface VoiceAgentHandle {
1172
+ /** Svelte readable store of the current input RMS (0–1) — drive a mic level meter. Read with `$audioLevel`. */
1173
+ audioLevel: Readable<number>;
1174
+ /** Svelte readable store: `true` once the WS `ready` handshake completed. Read with `$connected`. */
1175
+ connected: Readable<boolean>;
1176
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. Call in `onDestroy`. */
1177
+ endCall: () => void;
1178
+ /** Svelte readable store of the last transport/pipeline error, or `undefined`. Read with `$error`. */
1179
+ error: Readable<Error | undefined>;
1180
+ /** Svelte readable store of the live assistant text for the in-flight turn (grows via deltas; finalized on done). Read with `$interimTranscript`. */
1181
+ interimTranscript: Readable<string>;
1182
+ /** Svelte readable store: `true` while the mic is muted. Read with `$isMuted`. */
1183
+ isMuted: Readable<boolean>;
1184
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1185
+ sendText: (text: string) => void;
1186
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1187
+ startCall: () => Promise<void>;
1188
+ /** Svelte readable store of the current call lifecycle. Read with `$status`. */
1189
+ status: Readable<VoiceStatus>;
1190
+ /** Mute/unmute the microphone. Returns the new muted state. */
1191
+ toggleMute: () => boolean;
1192
+ /** Svelte readable store of the last finalized user utterance (STT result). Read with `$transcript`. */
1193
+ transcript: Readable<string>;
1194
+ }
1195
+ /**
1196
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1197
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1198
+ * streams the agent's synthesized speech back through the browser's audio output,
1199
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1200
+ * `audioLevel`) to Svelte readable stores you read with `$`. Pass the generated
1201
+ * `api.agents.<name>Voice` reference (never a string), matching `agentChat`'s
1202
+ * reference-passing style. The Svelte counterpart to React's `useVoiceAgent`,
1203
+ * re-expressed as stores; the per-call connection lives in a closure variable (a
1204
+ * handle is created once per component, so no store-of-store indirection is
1205
+ * needed).
1206
+ *
1207
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1208
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1209
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1210
+ * `createSocket`) so the handle is drivable outside a browser.
1211
+ *
1212
+ * There is no auto-dispose in Svelte — call `endCall` in `onDestroy`
1213
+ * (`onDestroy(handle.endCall)`) to tear the call down if the component unmounts
1214
+ * mid-call.
1215
+ *
1216
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
1217
+ * `setLunoraClient`.
1218
+ */
1219
+ declare function voiceAgent(options: VoiceAgentOptions): VoiceAgentHandle;
1220
+ declare function voiceAgent(client: LunoraClient, options: VoiceAgentOptions): VoiceAgentHandle;
1221
+ export { type ActionHandle, type AgentApi, type AgentChatApi, type AgentChatHandle, type AgentChatMessage, type AgentChatOptions, type AgentHandle, type AgentLiveEvent, type AgentOptions, type AgentProgressEvent, type AgentStateApi, type AgentStateHandle, type AgentStateOptions, type AgentThreadRecord, type AgentThreadStatus, type AgentTokenDelta, type AgentToolEvent, type AgentToolEventsApi, type AgentToolEventsHandle, type AgentToolEventsOptions, type AuthGateStore, type AuthStore, type ConnectionStatusStore, type FlagValue, type HeartbeatReference, type InfiniteQueryHandle, type InfiniteQueryOptions, type ListPresentReference, type MutationHandle, type MutatorHandleStore, type PageItemOf, type PaginatedArgs, type PaginatedQueryHandle, type PaginatedQueryOptions, type PresenceHandle, type PresenceOptions, type QueryStore, type QueryStoreOptions, type RateLimitHandle, type RateLimitOptions, type ReactiveArgs, type ReactivePaginatedArgs, type StreamHandle, type StreamStatus, type StreamStoreOptions, type SubscriptionHandle, type SubscriptionStoreOptions, type VoiceAgentHandle, type VoiceAgentOptions, type VoiceAudioFormat, type VoiceReference, type VoiceStatus, action, agent, agentChat, agentState, agentToolEvents, auth, authGate, connectionStatus, flag, flags,
1222
+ /**
1223
+ * Svelte adapter for Lunora (`@lunora/svelte`).
1224
+ *
1225
+ * Thin, idiomatic glue over the framework-neutral `@lunora/client` (no React):
1226
+ * live readable stores you read with `$store`, an optimistic mutation helper,
1227
+ * and the reactive-loader handoff (`hydratePreloaded`). The contract mirrors
1228
+ * `@lunora/react`, re-expressed in Svelte stores: `setLunoraClient` /
1229
+ * `getLunoraClient` are the context provider/consumer; `query` is a live
1230
+ * readable store (React's `useQuery`); `mutation` is an optimistic
1231
+ * `{ data, error, pending, mutate, reset }` (React's `useMutation`); and
1232
+ * `hydratePreloaded` is the SSR-seed-to-live-store handoff (React's
1233
+ * `usePreloadedQuery`).
1234
+ *
1235
+ * The package is plain `.ts` over stores — no `.svelte` component compiler is
1236
+ * required to build or test it.
1237
+ *
1238
+ * Server-side preload helpers (`createServerClient`, `preloadQuery`) live in the
1239
+ * socket-free `@lunora/svelte/server` entry (a re-export of `@lunora/client/ssr`, the
1240
+ * framework-neutral server contract) — import them there in your SvelteKit
1241
+ * `+page.ts` / `+layout.ts` load.
1242
+ */
1243
+ getLunoraClient, hydratePreloaded, infiniteQuery, mutation, mutator, paginatedQuery, presence, query, rateLimit,
1244
+ /**
1245
+ * Svelte adapter for Lunora (`@lunora/svelte`).
1246
+ *
1247
+ * Thin, idiomatic glue over the framework-neutral `@lunora/client` (no React):
1248
+ * live readable stores you read with `$store`, an optimistic mutation helper,
1249
+ * and the reactive-loader handoff (`hydratePreloaded`). The contract mirrors
1250
+ * `@lunora/react`, re-expressed in Svelte stores: `setLunoraClient` /
1251
+ * `getLunoraClient` are the context provider/consumer; `query` is a live
1252
+ * readable store (React's `useQuery`); `mutation` is an optimistic
1253
+ * `{ data, error, pending, mutate, reset }` (React's `useMutation`); and
1254
+ * `hydratePreloaded` is the SSR-seed-to-live-store handoff (React's
1255
+ * `usePreloadedQuery`).
1256
+ *
1257
+ * The package is plain `.ts` over stores — no `.svelte` component compiler is
1258
+ * required to build or test it.
1259
+ *
1260
+ * Server-side preload helpers (`createServerClient`, `preloadQuery`) live in the
1261
+ * socket-free `@lunora/svelte/server` entry (a re-export of `@lunora/client/ssr`, the
1262
+ * framework-neutral server contract) — import them there in your SvelteKit
1263
+ * `+page.ts` / `+layout.ts` load.
1264
+ */
1265
+ setLunoraClient, stream, subscription, voiceAgent };