@lunora/svelte 1.0.0-alpha.30 → 1.0.0-alpha.300

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