@lunora/svelte 1.0.0-alpha.24 → 1.0.0-alpha.241

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