@lunora/svelte 1.0.0-alpha.7 → 1.0.0-alpha.71

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 (42) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/dist/index.d.mts +897 -168
  4. package/dist/index.d.ts +897 -168
  5. package/dist/index.mjs +1 -10
  6. package/dist/packem_shared/agent-CddTbgxO.mjs +1 -0
  7. package/dist/packem_shared/agentChat-BmvA3u8B.mjs +1 -0
  8. package/dist/packem_shared/agentState-fc7KRCp9.mjs +1 -0
  9. package/dist/packem_shared/agentToolEvents-sOUvSZsy.mjs +1 -0
  10. package/dist/packem_shared/auth-BWCPnv0n.mjs +1 -0
  11. package/dist/packem_shared/connectionStatus-BHVAskxU.mjs +1 -0
  12. package/dist/packem_shared/flag-5trRaaSv.mjs +1 -0
  13. package/dist/packem_shared/getLunoraClient-DU7BmZy1.mjs +1 -0
  14. package/dist/packem_shared/hydratePreloaded-Bbm6vwbA.mjs +1 -0
  15. package/dist/packem_shared/infiniteQuery-s_5r8MQZ.mjs +1 -0
  16. package/dist/packem_shared/is-browser-BEdfLJHK.mjs +1 -0
  17. package/dist/packem_shared/is-function-reference-ByqJF30w.mjs +1 -0
  18. package/dist/packem_shared/mutation-fa0Bj5Bo.mjs +1 -0
  19. package/dist/packem_shared/mutator-cvH3UrNm.mjs +1 -0
  20. package/dist/packem_shared/presence-C2YC1KOc.mjs +1 -0
  21. package/dist/packem_shared/query-BEQBdOJ2.mjs +1 -0
  22. package/dist/packem_shared/rateLimit-DtykU7F_.mjs +1 -0
  23. package/dist/packem_shared/stream-DItOnXt6.mjs +1 -0
  24. package/dist/packem_shared/subscription-Dbz9sy8N.mjs +1 -0
  25. package/dist/packem_shared/voiceAgent-CPQvbrxT.mjs +1 -0
  26. package/dist/server.mjs +1 -1
  27. package/dist/upload.d.mts +2 -0
  28. package/dist/upload.d.ts +2 -0
  29. package/dist/upload.mjs +1 -0
  30. package/dist/worker.mjs +1 -1
  31. package/package.json +10 -4
  32. package/dist/packem_shared/auth-DLPf_bK9.mjs +0 -28
  33. package/dist/packem_shared/connectionStatus-CRsOMeYl.mjs +0 -14
  34. package/dist/packem_shared/getLunoraClient--bwSz7F6.mjs +0 -16
  35. package/dist/packem_shared/hydratePreloaded-D5rUJdXy.mjs +0 -21
  36. package/dist/packem_shared/infiniteQuery-jPMQw8Vz.mjs +0 -196
  37. package/dist/packem_shared/is-function-reference-ycLAcI79.mjs +0 -3
  38. package/dist/packem_shared/mutation-CnDkAaLH.mjs +0 -31
  39. package/dist/packem_shared/presence-BQWixJ2T.mjs +0 -66
  40. package/dist/packem_shared/query-D8Pct9Qe.mjs +0 -36
  41. package/dist/packem_shared/rateLimit-Cdw1kp8t.mjs +0 -66
  42. package/dist/packem_shared/subscription-twuBT_Wb.mjs +0 -46
package/dist/index.d.ts CHANGED
@@ -1,29 +1,462 @@
1
- import { LunoraClient, User, ConnectionStatus, Preloaded, FunctionReference, ReturnOf, ArgsOf, MutationCallOptions, SubscriptionErrorCallback } from '@lunora/client';
2
- export type { ArgsOf, ConnectionStatus, FunctionReference, LunoraClient, MutationCallOptions, Preloaded, ReturnOf } from '@lunora/client';
1
+ import { FunctionReference, LunoraClient, User, ConnectionStatus, Preloaded, ReturnOf, ArgsOf, MutationCallOptions, MutatorHandle, SubscriptionErrorCallback } from '@lunora/client';
2
+ export type { ArgsOf, ConnectionStatus, FunctionReference, LunoraClient, MutationCallOptions, MutatorHandle, MutatorTransaction, Preloaded, ReturnOf } from '@lunora/client';
3
3
  import { Readable } from 'svelte/store';
4
4
  import { PaginationStatus } from '@lunora/client/pagination';
5
5
  import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
6
6
  /**
7
- * Publish a {@link LunoraClient} on the Svelte component context so that
8
- * descendant components can read it with {@link getLunoraClient} (or implicitly,
9
- * via the default-client lookups inside `query`/`mutation`/`hydratePreloaded`).
10
- *
11
- * Call this once, high in the tree (typically your root `+layout.svelte` or
12
- * `App.svelte`), during component initialisation — `setContext` must run while
13
- * the component is being constructed, exactly like React's provider mounts once.
14
- * This is the Svelte analogue of mounting `LunoraProvider`.
15
- */
7
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
8
+ * `@lunora/agent`'s `AgentThreadStatus` — re-declared here (rather than imported)
9
+ * so this Svelte entry never pulls in the server-only `@lunora/agent` module graph
10
+ * (the adapter stays Svelte + `@lunora/client` only). Keep in sync with
11
+ * `packages/agent/src/types.ts`.
12
+ */
13
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
14
+ /**
15
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
16
+ * subset of the persisted thread row — every field beyond `status` is optional so
17
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
18
+ * `agent_threads` table in `packages/agent/src/component.ts`.
19
+ */
20
+ interface AgentThreadRecord {
21
+ createdAt?: number;
22
+ /** The failure message when `status === "error"`. */
23
+ error?: string;
24
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
25
+ instanceId?: string;
26
+ messageCount?: number;
27
+ /** The verified thread owner, when the run was started with one. */
28
+ owner?: string;
29
+ status: AgentThreadStatus;
30
+ title?: string;
31
+ updatedAt?: number;
32
+ }
33
+ /**
34
+ * The `agents.agentThread` reference the handle subscribes to for live thread
35
+ * state (status + the in-flight `instanceId`). A structural subset of the
36
+ * generated `api.agents` surface, so the whole generated `api` object is
37
+ * assignable.
38
+ */
39
+ interface AgentApi {
40
+ agents: {
41
+ agentThread: FunctionReference<"query", {
42
+ key: string;
43
+ }, Record<string, unknown> | undefined>;
44
+ };
45
+ }
46
+ interface AgentOptions {
47
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
48
+ api: AgentApi;
49
+ /**
50
+ * Optional app mutation over the agent's cancel path
51
+ * (`ctx.agents[name].cancel(id)`). Called with `{ instanceId, threadKey }`.
52
+ * When omitted (or no run is in flight) {@link AgentHandle.cancel} is a no-op.
53
+ */
54
+ cancel?: FunctionReference<"mutation">;
55
+ /**
56
+ * The app mutation that starts (or continues) a run — a thin wrapper over
57
+ * `ctx.agents[name].run(...)`. Called with `{ threadKey, input }` merged with
58
+ * {@link AgentOptions.runArgs} and the per-call args.
59
+ */
60
+ run: FunctionReference<"mutation">;
61
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
62
+ runArgs?: Record<string, unknown>;
63
+ /** The thread to observe and drive. */
64
+ threadKey: string;
65
+ }
66
+ interface AgentHandle {
67
+ /**
68
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
69
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
70
+ */
71
+ cancel: () => Promise<void>;
72
+ /** `true` while a `run` invocation is in flight. Read with `$pending`. */
73
+ pending: Readable<boolean>;
74
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
75
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
76
+ /** The live thread status, or `undefined` before the thread exists. Read with `$status`. */
77
+ status: Readable<AgentThreadStatus | undefined>;
78
+ /**
79
+ * Stop the live thread subscription. Call in `onDestroy`
80
+ * (`onDestroy(handle.teardown)`).
81
+ */
82
+ teardown: () => void;
83
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. Read with `$thread`. */
84
+ thread: Readable<AgentThreadRecord | undefined>;
85
+ }
86
+ /**
87
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
88
+ * chat message surface — the Svelte counterpart to React's `useAgent`,
89
+ * re-expressed as stores you read with `$`. Composes `client.subscribe` for live
90
+ * thread state and {@link mutation} for the run/cancel writes. For the full
91
+ * conversation surface (durable history + approvals) use `agentChat`.
92
+ *
93
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
94
+ * `ctx.agents[name].run` / `.cancel`, so the handle hard-codes no function names
95
+ * beyond the `agents:*` surface. The subscription opens eagerly on the call and
96
+ * runs until {@link AgentHandle.teardown} — call `onDestroy(handle.teardown)`.
97
+ *
98
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
99
+ * `setLunoraClient`.
100
+ */
101
+ declare function agent(options: AgentOptions): AgentHandle;
102
+ declare function agent(client: LunoraClient, options: AgentOptions): AgentHandle;
103
+ /**
104
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
105
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
106
+ * re-declared here (rather than imported) so this Svelte entry never pulls in the
107
+ * server-only `@lunora/agent` module graph. Keep in sync with the
108
+ * `agent_messages` table in `packages/agent/src/component.ts`.
109
+ */
110
+ interface AgentChatMessage {
111
+ content: string;
112
+ createdAt?: number;
113
+ /**
114
+ * `true` for a client-side optimistic user message not yet acknowledged by
115
+ * the server. Cleared once the durable history carries the matching user turn.
116
+ */
117
+ optimistic?: boolean;
118
+ role: "assistant" | "system" | "tool" | "user";
119
+ seq: number;
120
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
121
+ status?: "approved" | "awaiting_approval" | "rejected";
122
+ toolCallId?: string;
123
+ toolCalls?: ReadonlyArray<{
124
+ id: string;
125
+ input: unknown;
126
+ name: string;
127
+ }>;
128
+ toolName?: string;
129
+ }
130
+ /**
131
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
132
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed
133
+ * {@link AgentChatHandle.streamingText} live and are never replayed; the
134
+ * persisted assistant message stays the single source of truth.
135
+ */
136
+ interface AgentTokenDelta {
137
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
138
+ kind?: "token";
139
+ /** The incremental text chunk the model just produced. */
140
+ text: string;
141
+ /** The thread this delta belongs to. */
142
+ threadKey: string;
143
+ /** The zero-based index of the turn producing the delta. */
144
+ turn: number;
145
+ }
146
+ /**
147
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
148
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
149
+ * surfaced by `agentToolEvents`, ignored by {@link AgentChatHandle.streamingText}.
150
+ */
151
+ interface AgentProgressEvent {
152
+ /** The arbitrary, JSON-serializable payload the tool reported. */
153
+ data: unknown;
154
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
155
+ kind: "progress";
156
+ /** The thread this event belongs to. */
157
+ threadKey: string;
158
+ /** The tool call this progress belongs to. */
159
+ toolCallId: string;
160
+ }
161
+ /**
162
+ * A single event on the agent's live-only channel — a streamed token delta or a
163
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
164
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
165
+ * it unset).
166
+ */
167
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
168
+ /** The `agents:agentMessages` reference — live durable thread history. */
169
+ type AgentMessagesReference$1 = FunctionReference<"query", {
170
+ key: string;
171
+ limit?: number;
172
+ }, ReadonlyArray<Record<string, unknown>>>;
173
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
174
+ type AgentApprovalReference = FunctionReference<"mutation", {
175
+ decision: "approve" | "reject";
176
+ instanceId: string;
177
+ note?: string;
178
+ threadKey: string;
179
+ toolCallId: string;
180
+ }, {
181
+ resolved: boolean;
182
+ }>;
183
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
184
+ type AgentThreadReference = FunctionReference<"query", {
185
+ key: string;
186
+ }, Record<string, unknown> | undefined>;
187
+ /**
188
+ * An app stream reference that tees the agent's in-flight live events, keyed by
189
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
190
+ * sink — tool progress events; this handle consumes only the token arm.
191
+ */
192
+ type AgentTokenStreamReference = FunctionReference<"stream", {
193
+ key: string;
194
+ }, AgentLiveEvent>;
195
+ /**
196
+ * The `agents.*` reference surface the chat handle reads. A structural subset of
197
+ * the generated `api.agents`, so the whole generated `api` object is assignable.
198
+ */
199
+ interface AgentChatApi {
200
+ agents: {
201
+ agentMessages: AgentMessagesReference$1;
202
+ agentResolveApproval: AgentApprovalReference;
203
+ agentThread: AgentThreadReference;
204
+ };
205
+ }
206
+ interface AgentChatOptions {
207
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
208
+ api: AgentChatApi;
209
+ /**
210
+ * Optional app mutation over the agent's cancel path
211
+ * (`ctx.agents[name].cancel(id)`). Called with `{ instanceId, threadKey }`.
212
+ * When omitted (or no run is in flight) {@link AgentChatHandle.cancel} is a
213
+ * no-op.
214
+ */
215
+ cancel?: FunctionReference<"mutation">;
216
+ /** History depth forwarded to `agents:agentMessages`. */
217
+ limit?: number;
218
+ /**
219
+ * The app mutation that starts (or continues) a run — a thin wrapper over
220
+ * `ctx.agents[name].run(...)`. Called with `{ threadKey, input }` merged with
221
+ * {@link AgentChatOptions.sendArgs} and the per-call args.
222
+ */
223
+ send: FunctionReference<"mutation">;
224
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
225
+ sendArgs?: Record<string, unknown>;
226
+ /**
227
+ * Optional live token-delta stream — an app stream function that tees the
228
+ * agent's in-flight deltas. When omitted {@link AgentChatHandle.streamingText}
229
+ * stays empty and the UI updates message-by-message from durable history.
230
+ */
231
+ stream?: AgentTokenStreamReference;
232
+ /** The thread to observe and continue. */
233
+ threadKey: string;
234
+ }
235
+ interface AgentChatHandle {
236
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
237
+ approve: (toolCallId: string, note?: string) => Promise<void>;
238
+ /**
239
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
240
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
241
+ */
242
+ cancel: () => Promise<void>;
243
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. Read with `$messages`. */
244
+ messages: Readable<ReadonlyArray<AgentChatMessage>>;
245
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
246
+ reject: (toolCallId: string, note?: string) => Promise<void>;
247
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
248
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
249
+ /** The live thread status, or `undefined` before the thread exists. Read with `$status`. */
250
+ status: Readable<AgentThreadStatus | undefined>;
251
+ /**
252
+ * The in-flight turn's streamed text — live-only, `""` once the turn persists
253
+ * to `messages`. Populated when a `stream` reference is supplied (via the
254
+ * {@link stream} primitive); with no reference it stays `""` and the UI advances
255
+ * message-by-message from durable history. Read with `$streamingText`.
256
+ */
257
+ streamingText: Readable<string>;
258
+ /**
259
+ * Stop the live history + thread subscriptions (and the token stream, if any).
260
+ * Call in `onDestroy` (`onDestroy(handle.teardown)`).
261
+ */
262
+ teardown: () => void;
263
+ }
264
+ /**
265
+ * A first-class agent chat surface: live durable history + in-flight token
266
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey` —
267
+ * the Svelte counterpart to React's `useAgentChat`, re-expressed as stores you
268
+ * read with `$`.
269
+ *
270
+ * It composes the existing primitives rather than adding transport:
271
+ * `client.subscribe(api.agents.agentMessages)` for durable history,
272
+ * `client.subscribe(api.agents.agentThread)` for live status + the in-flight
273
+ * `instanceId`, {@link stream} over an app token stream for in-flight deltas, and
274
+ * {@link mutation} for the writes (`api.agents.agentResolveApproval` for approvals;
275
+ * app-defined wrappers for `send`/`cancel`). Only the `agents:*` surface is
276
+ * hard-coded — `send`/`cancel`/`stream` stay generic references.
277
+ *
278
+ * A `send` optimistically appends the user turn so it renders immediately; the
279
+ * optimistic row clears once the durable history carries the acknowledged turn.
280
+ * `streamingText` is live-only: it holds the current turn's streamed text and
281
+ * empties as soon as that turn's assistant message lands in `messages` (the
282
+ * persisted message is the source of truth); with no `stream` reference it stays
283
+ * `""` and the UI advances message-by-message from durable history. The
284
+ * subscriptions (and the token stream, if any) open eagerly and run until
285
+ * {@link AgentChatHandle.teardown} — call `onDestroy(handle.teardown)`.
286
+ *
287
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
288
+ * `setLunoraClient`.
289
+ */
290
+ declare function agentChat(options: AgentChatOptions): AgentChatHandle;
291
+ declare function agentChat(client: LunoraClient, options: AgentChatOptions): AgentChatHandle;
292
+ /**
293
+ * The `agents.agentState` reference the handle subscribes to for the thread's live
294
+ * synced state. A structural subset of the generated `api.agents` surface (like
295
+ * `AgentApi` for `agentThread`), so the whole generated `api` object is
296
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type is
297
+ * mirrored by the handle's generic `T`, since codegen pins the reference return as
298
+ * an optional record (it never evaluates agent config).
299
+ */
300
+ interface AgentStateApi {
301
+ agents: {
302
+ agentState: FunctionReference<"query", {
303
+ key: string;
304
+ }, Record<string, unknown> | undefined>;
305
+ };
306
+ }
307
+ interface AgentStateOptions {
308
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
309
+ api: AgentStateApi;
310
+ /** The thread whose synced state to observe. */
311
+ threadKey: string;
312
+ }
313
+ interface AgentStateHandle<T> {
314
+ /** Svelte readable store of the subscription error, if the live channel reported one. Read with `$error`. */
315
+ error: Readable<Error | undefined>;
316
+ /** Svelte readable store of the live synced state, or `undefined` before it is seeded/first pushed. Read with `$state`. */
317
+ state: Readable<T | undefined>;
318
+ }
319
+ /**
320
+ * Subscribe to an agent thread's synced state — the `setState`-style value a tool
321
+ * writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`. A
322
+ * thin wrapper over {@link subscription} against `api.agents.agentState`: the
323
+ * server pushes a fresh frame whenever the state changes (the dedicated query's
324
+ * per-socket JSON memo suppresses no-op pushes on unrelated thread writes), so
325
+ * `state` updates only on a real `setState`. The Svelte counterpart to React's
326
+ * `useAgentState`, re-expressed as stores you read with `$`.
327
+ *
328
+ * Generic over the app's state shape (`agentState<SupportState>(...)`, itself a
329
+ * record) — the reference is typed as an optional record because codegen cannot
330
+ * see the per-agent state type; the generic casts to `T`. The `state`/`error`
331
+ * stores are lazy, so the subscription opens on the first subscriber to `state`
332
+ * and tears down when the last one leaves — there is no `teardown` to call.
333
+ *
334
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
335
+ * `setLunoraClient`.
336
+ */
337
+ declare function agentState<T extends Record<string, unknown> = Record<string, unknown>>(options: AgentStateOptions): AgentStateHandle<T>;
338
+ declare function agentState<T extends Record<string, unknown> = Record<string, unknown>>(client: LunoraClient, options: AgentStateOptions): AgentStateHandle<T>;
339
+ /** The `agents:agentMessages` reference — live durable thread history. */
340
+ type AgentMessagesReference = FunctionReference<"query", {
341
+ key: string;
342
+ limit?: number;
343
+ }, ReadonlyArray<Record<string, unknown>>>;
344
+ /**
345
+ * An app stream reference that tees the agent's in-flight live events, keyed by
346
+ * thread. Carries token deltas and tool progress events; this handle consumes only
347
+ * the progress arm (`kind === "progress"`).
348
+ */
349
+ type AgentLiveStreamReference = FunctionReference<"stream", {
350
+ key: string;
351
+ }, AgentLiveEvent>;
352
+ /**
353
+ * The `agents.*` reference surface the tool-events handle reads. A structural
354
+ * subset of the generated `api.agents`, so the whole generated `api` object is
355
+ * assignable.
356
+ */
357
+ interface AgentToolEventsApi {
358
+ agents: {
359
+ agentMessages: AgentMessagesReference;
360
+ };
361
+ }
362
+ interface AgentToolEventsOptions {
363
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
364
+ api: AgentToolEventsApi;
365
+ /** History depth forwarded to `agents:agentMessages`. */
366
+ limit?: number;
367
+ /**
368
+ * Optional live event stream — the same app stream function `agentChat` uses.
369
+ * When supplied, ephemeral `ctx.reportProgress(...)` events for the thread are
370
+ * surfaced as `{ type: "progress" }` entries; when omitted only the durable
371
+ * lifecycle (call / result / awaiting-approval) is returned.
372
+ */
373
+ stream?: AgentLiveStreamReference;
374
+ /** The thread whose tool activity to observe. */
375
+ threadKey: string;
376
+ }
377
+ /**
378
+ * A single tool-lifecycle event for a thread. The durable arms
379
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
380
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
381
+ * stream and has no `seq`. Discriminate on `type`.
382
+ */
383
+ type AgentToolEvent = {
384
+ data: unknown;
385
+ toolCallId: string;
386
+ type: "progress";
387
+ } | {
388
+ input: unknown;
389
+ seq: number;
390
+ toolCallId: string;
391
+ toolName: string;
392
+ type: "call";
393
+ } | {
394
+ output: string;
395
+ seq: number;
396
+ status?: "approved" | "rejected";
397
+ toolCallId?: string;
398
+ toolName?: string;
399
+ type: "result";
400
+ } | {
401
+ seq: number;
402
+ toolCallId?: string;
403
+ toolName?: string;
404
+ type: "awaiting-approval";
405
+ };
406
+ interface AgentToolEventsHandle {
407
+ /**
408
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
409
+ * followed by any in-flight ephemeral progress events, recomputed from the live
410
+ * subscription + stream. Read with `$events`. With no `stream` reference only
411
+ * the durable lifecycle is surfaced. Treat as derived, not identity-stable.
412
+ */
413
+ events: Readable<ReadonlyArray<AgentToolEvent>>;
414
+ }
415
+ /**
416
+ * A focused view of a thread's tool activity: tool calls, their results,
417
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
418
+ * without the full chat message surface. The Svelte counterpart to React's
419
+ * `useAgentToolEvents`, re-expressed as a readable store you read with `$`.
420
+ *
421
+ * It composes the existing primitives rather than adding transport:
422
+ * {@link subscription} over `api.agents.agentMessages` for the durable lifecycle
423
+ * and {@link stream} over the optional app event stream for ephemeral progress,
424
+ * combined through `derived`. Progress events are live-only (the durable path never
425
+ * emits them): they ride the same sink as token deltas and are surfaced here,
426
+ * correlated to their tool call by `toolCallId`. For the conversational surface
427
+ * (messages + streaming text + approvals) use `agentChat`; this handle is the
428
+ * tool-observability slice.
429
+ *
430
+ * The underlying subscription and stream are lazy — they open when `events` gains
431
+ * its first subscriber and tear down when the last one leaves — so there is no
432
+ * `teardown` to call (unlike the write-bearing `agentChat`).
433
+ *
434
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
435
+ * `setLunoraClient`.
436
+ */
437
+ declare function agentToolEvents(options: AgentToolEventsOptions): AgentToolEventsHandle;
438
+ declare function agentToolEvents(client: LunoraClient, options: AgentToolEventsOptions): AgentToolEventsHandle;
439
+ /**
440
+ * Publish a {@link LunoraClient} on the Svelte component context so that
441
+ * descendant components can read it with {@link getLunoraClient} (or implicitly,
442
+ * via the default-client lookups inside `query`/`mutation`/`hydratePreloaded`).
443
+ *
444
+ * Call this once, high in the tree (typically your root `+layout.svelte` or
445
+ * `App.svelte`), during component initialisation — `setContext` must run while
446
+ * the component is being constructed, exactly like React's provider mounts once.
447
+ * This is the Svelte analogue of mounting `LunoraProvider`.
448
+ */
16
449
  declare const setLunoraClient: (client: LunoraClient) => LunoraClient;
17
450
  /**
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
- */
451
+ * Read the {@link LunoraClient} published by {@link setLunoraClient} from the
452
+ * nearest ancestor. Throws if no provider is mounted, mirroring `useLunora`'s
453
+ * "must be used inside a LunoraProvider" guard so the failure is loud and
454
+ * early rather than a confusing `undefined` deref later.
455
+ *
456
+ * Must be called during component initialisation (Svelte's `getContext`
457
+ * constraint); the live stores returned by `query`/`hydratePreloaded` resolve
458
+ * the client eagerly at call time for exactly this reason.
459
+ */
27
460
  declare const getLunoraClient: () => LunoraClient;
28
461
  interface AuthStore {
29
462
  /** Set the auth token on the underlying `LunoraClient`. */
@@ -34,93 +467,188 @@ interface AuthStore {
34
467
  user: Readable<User | null>;
35
468
  }
36
469
  /**
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
- */
470
+ * Create a pair of Svelte readable stores tracking the auth token and the
471
+ * resolved user identity. The stores are lazy: subscriptions open on the first
472
+ * reader and close when the last unsubscribes. Calling `setToken(jwt)` after
473
+ * sign-in refreshes both stores.
474
+ *
475
+ * Pass an explicit client to bypass the ambient context (useful in tests).
476
+ */
44
477
  declare const auth: (explicitClient?: ReturnType<typeof getLunoraClient>) => AuthStore;
478
+ /** Derived auth-gate stores for template gating (`{#if $isAuthenticated}`), built on {@link auth}. */
479
+ interface AuthGateStore {
480
+ /** Readable store, `true` once a token is set and the user has resolved. */
481
+ isAuthenticated: Readable<boolean>;
482
+ /** Readable store, `true` while a token is set but the user hasn't resolved yet. */
483
+ isLoading: Readable<boolean>;
484
+ }
485
+ /**
486
+ * Derived auth-gate stores built on {@link auth}. Svelte has no JSX-style
487
+ * `Authenticated` slot component the way React/Vue/Solid do (this package is
488
+ * plain `.ts` over stores — no `.svelte` component compiler required), so this
489
+ * exposes the same three-state logic as two boolean stores instead: a token
490
+ * with no resolved user yet is `isLoading`; a token with a resolved user is
491
+ * `isAuthenticated`; no token is neither (the signed-out state a template
492
+ * checks for with a plain `{:else}`).
493
+ *
494
+ * ```ts
495
+ * import { authGate } from "@lunora/svelte";
496
+ * const { isAuthenticated, isLoading } = authGate();
497
+ * // markup: {#if $isAuthenticated} signed in {:else if $isLoading} loading… {:else} signed out {/if}
498
+ * ```
499
+ *
500
+ * Pass an explicit client to bypass the ambient context (useful in tests).
501
+ */
502
+ declare const authGate: (explicitClient?: ReturnType<typeof getLunoraClient>) => AuthGateStore;
45
503
  /** The shape held by a {@link connectionStatus} store: the latest aggregate live-socket status. */
46
504
  type ConnectionStatusStore = Readable<ConnectionStatus>;
47
505
  /**
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
- */
506
+ * Expose the client's aggregate live-socket status as a Svelte readable store.
507
+ * Read it with the `$store` idiom (`{$status}`) and it stays current: the value
508
+ * transitions through `idle` → `connecting` → `connected` → `offline` as
509
+ * sockets open and drop — the Svelte equivalent of `@lunora/react`'s
510
+ * `useConnectionStatus`. Use it to drive a connection indicator.
511
+ *
512
+ * The status listener attaches inside `readable`'s start callback (on the first
513
+ * `$`-read / `.subscribe()`) and is released by the returned stop function when
514
+ * the last subscriber goes away, so a store that's never read attaches nothing.
515
+ *
516
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
517
+ * by `setLunoraClient` (which must therefore be called during component init,
518
+ * before this runs).
519
+ */
62
520
  declare const connectionStatus: (client?: LunoraClient) => ConnectionStatusStore;
521
+ /** A targeting context merged on top of the app's default (`defineFlags({ identify })`). */
522
+ type FlagContext = Record<string, unknown>;
523
+ /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
524
+ type FlagValue = boolean | number | string | {
525
+ [key: string]: unknown;
526
+ } | unknown[] | null;
527
+ /**
528
+ * Open a single feature flag as a Svelte readable store, live over Lunora's
529
+ * WebSocket. Read it with the `$store` idiom (`{$darkMode}`).
530
+ *
531
+ * The store holds `defaultValue` until the first evaluation lands, then the
532
+ * server's resolved value — re-emitted whenever the provider re-evaluates (e.g. a
533
+ * flag is toggled in Cloudflare Flagship). The flag's kind is inferred from
534
+ * `defaultValue`'s runtime type, so `flag("dark", false)` reads a boolean and
535
+ * `flag("hero", "control")` a string. `context` supplies a per-call targeting
536
+ * context merged on top of the app's default `identify` targeting key.
537
+ *
538
+ * The subscription opens lazily on the first `$`-read and tears down when the
539
+ * last subscriber detaches. Pass `client` explicitly, or omit it to resolve the
540
+ * ambient client published by `setLunoraClient`. Evaluation never throws — a
541
+ * provider error resolves the default (the same fail-open contract as `ctx.flags`).
542
+ */
543
+ declare function flag<T extends FlagValue>(key: string, defaultValue: T, context?: FlagContext): Readable<T>;
544
+ declare function flag<T extends FlagValue>(client: LunoraClient, key: string, defaultValue: T, context?: FlagContext): Readable<T>;
545
+ /**
546
+ * Open several feature flags at once as a single Svelte readable store of the
547
+ * resolved record, live over Lunora's WebSocket.
548
+ *
549
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
550
+ * default, and the store holds the same-shaped record with resolved values (the
551
+ * defaults until each evaluation lands). A single `context` applies to every
552
+ * flag. This is the batched form of {@link flag} — one store, one subscription
553
+ * per key, torn down together when the last subscriber detaches.
554
+ *
555
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
556
+ * by `setLunoraClient`.
557
+ */
558
+ declare function flags<T extends Record<string, FlagValue>>(flagDefaults: T, context?: FlagContext): Readable<T>;
559
+ declare function flags<T extends Record<string, FlagValue>>(client: LunoraClient, flagDefaults: T, context?: FlagContext): Readable<T>;
63
560
  /**
64
- * Hydrate a query store from a {@link Preloaded} token produced by
65
- * `preloadQuery` during SSR, then keep it live — the reactive-loader handoff.
66
- *
67
- * The store is seeded **synchronously** with `preloaded.value`, so the very
68
- * first read (`$store` during hydration) returns the server value with no
69
- * loading flash and no hydration mismatch — there is no `undefined` window and
70
- * no refetch. When the store gains its first subscriber on the client, a live
71
- * WS subscription attaches and every subsequent delta re-emits, exactly like a
72
- * plain `query` store. This is the Svelte equivalent of React's
73
- * `usePreloadedQuery`.
74
- *
75
- * Pass `client` explicitly, or omit it to resolve the ambient client published
76
- * by `setLunoraClient`.
77
- *
78
- * Note on SSR: `readable`'s start callback only runs when the store is actually
79
- * subscribed (the browser), so on the server the store simply holds the seeded
80
- * value and opens no socket. The token's `value` is the single source of truth
81
- * for the first paint either way.
82
- */
561
+ * Hydrate a query store from a {@link Preloaded} token produced by
562
+ * `preloadQuery` during SSR, then keep it live — the reactive-loader handoff.
563
+ *
564
+ * The store is seeded **synchronously** with `preloaded.value`, so the very
565
+ * first read (`$store` during hydration) returns the server value with no
566
+ * loading flash and no hydration mismatch — there is no `undefined` window and
567
+ * no refetch. When the store gains its first subscriber on the client, a live
568
+ * WS subscription attaches and every subsequent delta re-emits, exactly like a
569
+ * plain `query` store. This is the Svelte equivalent of React's
570
+ * `usePreloadedQuery`.
571
+ *
572
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
573
+ * by `setLunoraClient`.
574
+ *
575
+ * Note on SSR: `readable`'s start callback only runs when the store is actually
576
+ * subscribed (the browser), so on the server the store simply holds the seeded
577
+ * value and opens no socket. The token's `value` is the single source of truth
578
+ * for the first paint either way.
579
+ */
83
580
  declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, client?: LunoraClient) => Readable<T>;
84
581
  /**
85
- * The reactive handle returned by {@link mutation} — the Svelte counterpart to
86
- * React's `useMutation`, re-expressed as stores you read with `$`. The surface
87
- * is identical across the Lunora adapters (`@lunora/solid`, `/vue`):
88
- * `data`/`error`/`pending` are readable stores and `mutate` is an awaitable.
89
- */
582
+ * The reactive handle returned by {@link mutation} — the Svelte counterpart to
583
+ * React's `useMutation`, re-expressed as stores you read with `$`. The surface
584
+ * is identical across the Lunora adapters (`@lunora/solid`, `/vue`):
585
+ * `data`/`error`/`pending` are readable stores and `mutate` is an awaitable.
586
+ */
90
587
  interface MutationHandle<F extends FunctionReference> {
91
588
  /** The latest invocation's resolved value, or `undefined` before the first success. */
92
589
  data: Readable<ReturnOf<F> | undefined>;
93
590
  /** The latest invocation's error, or `undefined`. */
94
591
  error: Readable<Error | undefined>;
95
592
  /**
96
- * Run the mutation. Resolves with the server result and rejects on failure
97
- * (errors propagate — there is no swallowing). Optimistic updates passed in
98
- * `options` are applied and rolled back by the client against the live query
99
- * subscriptions, exactly as in the React adapter.
100
- */
593
+ * Run the mutation. Resolves with the server result and rejects on failure
594
+ * (errors propagate — there is no swallowing). Optimistic updates passed in
595
+ * `options` are applied and rolled back by the client against the live query
596
+ * subscriptions, exactly as in the React adapter.
597
+ */
101
598
  mutate: (args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>;
102
599
  /**
103
- * `true` while any invocation from this handle is in flight. Ref-counted, so
104
- * overlapping calls compose and it only flips back to `false` once the last
105
- * one settles. Read it with `$pending` in a component to disable a button.
106
- */
600
+ * `true` while any invocation from this handle is in flight. Ref-counted, so
601
+ * overlapping calls compose and it only flips back to `false` once the last
602
+ * one settles. Read it with `$pending` in a component to disable a button.
603
+ */
107
604
  pending: Readable<boolean>;
108
605
  /** Clear `data`/`error` back to idle. */
109
606
  reset: () => void;
110
607
  }
111
608
  /**
112
- * Create an optimistic {@link MutationHandle} for a mutation reference. The
113
- * Svelte counterpart to React's `useMutation`: returns
114
- * `{ data, error, pending, mutate, reset }` of readable stores plus an awaitable
115
- * `mutate`. The ref-counted pending + error-normalize orchestration is the
116
- * shared `createMutationRunner` from `@lunora/client`; only the stores are
117
- * adapter-specific.
118
- *
119
- * Pass `client` explicitly, or omit it to resolve the ambient client published
120
- * by `setLunoraClient`.
121
- */
609
+ * Create an optimistic {@link MutationHandle} for a mutation reference. The
610
+ * Svelte counterpart to React's `useMutation`: returns
611
+ * `{ data, error, pending, mutate, reset }` of readable stores plus an awaitable
612
+ * `mutate`. The ref-counted pending + error-normalize orchestration is the
613
+ * shared `createMutationRunner` from `@lunora/client`; only the stores are
614
+ * adapter-specific.
615
+ *
616
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
617
+ * by `setLunoraClient`.
618
+ */
122
619
  declare function mutation<F extends FunctionReference>(function_: F): MutationHandle<F>;
123
620
  declare function mutation<F extends FunctionReference>(client: LunoraClient, function_: F): MutationHandle<F>;
621
+ /**
622
+ * The reactive handle returned by {@link mutator} — the Svelte counterpart to
623
+ * `@lunora/react`'s `useMutator`, re-expressed as stores you read with `$`.
624
+ * `error`/`isError`/`pending` are readable stores and `mutate` is an awaitable
625
+ * that resolves once the write is persisted (or rejects).
626
+ */
627
+ interface MutatorHandleStore<TArgs> {
628
+ /** The latest invocation's error, or `undefined`. */
629
+ error: Readable<Error | undefined>;
630
+ /** `true` when the latest invocation rejected. */
631
+ isError: Readable<boolean>;
632
+ /** Run the mutator; resolves once the write is persisted, rejects on failure. */
633
+ mutate: (args: TArgs) => Promise<void>;
634
+ /** `true` while ANY invocation from this handle is in flight (ref-counted, so overlapping calls compose). */
635
+ pending: Readable<boolean>;
636
+ /** Clear the latest `error` back to idle. */
637
+ reset: () => void;
638
+ }
639
+ /**
640
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
641
+ * custom-mutator handle from `@lunora/db`'s `bindMutators` — the Svelte
642
+ * equivalent of `@lunora/react`'s `useMutator`. The optimistic overlay and
643
+ * server-authoritative push are owned by the bound handle (and TanStack DB's
644
+ * optimistic-transaction layer rebases pending overlays on every sync tick);
645
+ * this helper only surfaces store state for the in-flight/error lifecycle. Reads
646
+ * stay on the existing TanStack `useLiveQuery`; no new query store is needed.
647
+ *
648
+ * `pending` is ref-counted across overlapping invocations of THIS handle, so it
649
+ * clears only once every concurrent call has settled.
650
+ */
651
+ declare const mutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHandleStore<TArgs>;
124
652
  /** The args a paginated query exposes minus the framework-supplied page cursor. */
125
653
  type PaginatedArgs<F extends FunctionReference> = Omit<ArgsOf<F>, "paginationOpts">;
126
654
  /** The element type of the `page` array a paginated query returns. */
@@ -160,46 +688,46 @@ interface InfiniteQueryHandle<T> {
160
688
  status: Readable<PaginationStatus>;
161
689
  }
162
690
  /**
163
- * Open a live paginated query as Svelte stores. The first page opens when
164
- * called; call `loadMore(n)` to append the next page. Results are flattened
165
- * across all loaded pages.
166
- *
167
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
168
- * Svelte context.
169
- */
691
+ * Open a live paginated query as Svelte stores. The first page opens when
692
+ * called; call `loadMore(n)` to append the next page. Results are flattened
693
+ * across all loaded pages.
694
+ *
695
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
696
+ * Svelte context.
697
+ */
170
698
  declare function paginatedQuery<F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: PaginatedQueryOptions): PaginatedQueryHandle<PageItemOf<F>>;
171
699
  declare function paginatedQuery<F extends FunctionReference>(client: LunoraClient, function_: F, args: "skip" | PaginatedArgs<F>, options: PaginatedQueryOptions): PaginatedQueryHandle<PageItemOf<F>>;
172
700
  /**
173
- * Open a live paginated query as Svelte stores, keeping each page as its own
174
- * inner array (TanStack-Query-style `fetchNextPage` / `hasNextPage` shape).
175
- *
176
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
177
- * Svelte context.
178
- */
701
+ * Open a live paginated query as Svelte stores, keeping each page as its own
702
+ * inner array (TanStack-Query-style `fetchNextPage` / `hasNextPage` shape).
703
+ *
704
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
705
+ * Svelte context.
706
+ */
179
707
  declare function infiniteQuery<F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: InfiniteQueryOptions): InfiniteQueryHandle<PageItemOf<F>>;
180
708
  declare function infiniteQuery<F extends FunctionReference>(client: LunoraClient, function_: F, args: "skip" | PaginatedArgs<F>, options: InfiniteQueryOptions): InfiniteQueryHandle<PageItemOf<F>>;
181
709
  /**
182
- * `presence` — collaborative-awareness stores, the client half of the
183
- * `@lunora/server` `definePresence` preset.
184
- *
185
- * Drives the heartbeat mutation (on call, interval, and tab re-focus) and
186
- * subscribes to the live `listPresent` query for the given room.
187
- *
188
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
189
- * Svelte context.
190
- */
191
- /**
192
- * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }`.
193
- */
710
+ * `presence` — collaborative-awareness stores, the client half of the
711
+ * `@lunora/server` `definePresence` preset.
712
+ *
713
+ * Drives the heartbeat mutation (on call, interval, and tab re-focus) and
714
+ * subscribes to the live `listPresent` query for the given room.
715
+ *
716
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
717
+ * Svelte context.
718
+ */
719
+ /**
720
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }`.
721
+ */
194
722
  type HeartbeatReference = FunctionReference<"mutation", {
195
723
  data?: Record<string, unknown>;
196
724
  roomId: string;
197
725
  sessionId: string;
198
726
  }>;
199
727
  /**
200
- * A listPresent query reference: takes `{ roomId }` and returns the array of
201
- * present members.
202
- */
728
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
729
+ * present members.
730
+ */
203
731
  type ListPresentReference = FunctionReference<"query", {
204
732
  roomId: string;
205
733
  }>;
@@ -213,9 +741,9 @@ interface PresenceOptions<H extends HeartbeatReference, L extends ListPresentRef
213
741
  /** The `api.*` reference for the presence listPresent query. */
214
742
  listPresent: L;
215
743
  /**
216
- * Stable id for this presence row. Defaults to a fresh per-mount id.
217
- * Pass a user/connection id to control deduping across tabs.
218
- */
744
+ * Stable id for this presence row. Defaults to a fresh per-mount id.
745
+ * Pass a user/connection id to control deduping across tabs.
746
+ */
219
747
  sessionId?: string;
220
748
  /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
221
749
  shardKey?: string;
@@ -231,15 +759,18 @@ interface PresenceHandle<L extends ListPresentReference> {
231
759
  teardown: () => void;
232
760
  }
233
761
  /**
234
- * Open a live presence handle.
235
- *
236
- * Pass `client` explicitly, or omit it to resolve the ambient client from the
237
- * Svelte context (requires calling inside a component's `&lt;script>` block or
238
- * inside a function called during component initialisation).
239
- *
240
- * Call `teardown()` when the component is destroyed to stop heartbeats and
241
- * remove the visibility listener (`onDestroy(handle.teardown)`).
242
- */
762
+ * Open a live presence handle.
763
+ *
764
+ * Pass `client` explicitly, or omit it to resolve the ambient client from the
765
+ * Svelte context (requires calling inside a component's `<script>` block or
766
+ * inside a function called during component initialisation).
767
+ *
768
+ * Teardown (stop heartbeats, remove the visibility listener, release the
769
+ * connection context) is wired automatically to the component's `onDestroy`
770
+ * when called during component initialisation. Outside a component call
771
+ * `handle.teardown()` yourself. `teardown()` is idempotent, so an explicit
772
+ * `onDestroy(handle.teardown)` on top of the auto-wiring is safe.
773
+ */
243
774
  declare function presence<H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: PresenceOptions<H, L>): PresenceHandle<L>;
244
775
  declare function presence<H extends HeartbeatReference, L extends ListPresentReference>(client: LunoraClient, roomId: string, options: PresenceOptions<H, L>): PresenceHandle<L>;
245
776
  /** Options accepted by {@link query}. */
@@ -250,36 +781,40 @@ interface QueryStoreOptions {
250
781
  shardKey?: string;
251
782
  }
252
783
  /**
253
- * The shape held by a {@link query} store: the latest server value (`undefined`
254
- * until the first response lands, mirroring React's `useQuery`).
255
- */
784
+ * The shape held by a {@link query} store: the latest server value (`undefined`
785
+ * until the first response lands, mirroring React's `useQuery`).
786
+ */
256
787
  type QueryStore<F extends FunctionReference> = Readable<ReturnOf<F> | undefined>;
257
788
  /**
258
- * Open a live query as a Svelte readable store. Read it with the `$store`
259
- * idiom in a component (`{$messages}`) and it stays current: a WS subscription
260
- * attaches the moment the store gains its first subscriber and the value
261
- * re-emits on every server delta — the Svelte equivalent of React's `useQuery`.
262
- *
263
- * The subscription is opened lazily (inside `readable`'s start callback, on the
264
- * first `$`-read / `.subscribe()`) and torn down by the returned stop function
265
- * when the last subscriber goes away — so a store that's never read opens no
266
- * socket, and a component that unmounts releases its subscription. Sharing one
267
- * store across several components shares a single underlying subscription
268
- * (the `LunoraClient` de-dupes by `(fn, args, shardKey)`).
269
- *
270
- * Pass `client` explicitly, or omit it to resolve the ambient client published
271
- * by `setLunoraClient` (which must therefore be called during component init,
272
- * before this runs).
273
- */
274
- declare function query<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: QueryStoreOptions): QueryStore<F>;
275
- declare function query<F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: QueryStoreOptions): QueryStore<F>;
789
+ * Open a live query as a Svelte readable store. Read it with the `$store`
790
+ * idiom in a component (`{$messages}`) and it stays current: a WS subscription
791
+ * attaches the moment the store gains its first subscriber and the value
792
+ * re-emits on every server delta — the Svelte equivalent of React's `useQuery`.
793
+ *
794
+ * The subscription is opened lazily (inside `readable`'s start callback, on the
795
+ * first `$`-read / `.subscribe()`) and torn down by the returned stop function
796
+ * when the last subscriber goes away — so a store that's never read opens no
797
+ * socket, and a component that unmounts releases its subscription. Sharing one
798
+ * store across several components shares a single underlying subscription
799
+ * (the `LunoraClient` de-dupes by `(fn, args, shardKey)`).
800
+ *
801
+ * Pass `"skip"` as `args` to keep the store connected but the subscription
802
+ * dormant (the value stays `undefined`, no socket opens) — useful for a query
803
+ * gated on auth or a route param, matching React/Vue/Solid's `useQuery`.
804
+ *
805
+ * Pass `client` explicitly, or omit it to resolve the ambient client published
806
+ * by `setLunoraClient` (which must therefore be called during component init,
807
+ * before this runs).
808
+ */
809
+ declare function query<F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: QueryStoreOptions): QueryStore<F>;
810
+ declare function query<F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F> | "skip", options?: QueryStoreOptions): QueryStore<F>;
276
811
  interface RateLimitOptions {
277
812
  /** Clock injection for tests. Defaults to `Date.now`. */
278
813
  now?: () => number;
279
814
  /**
280
- * Re-evaluation cadence in milliseconds while throttled, so `retryAfter`
281
- * ticks down and `disabled` flips back automatically. Defaults to `1000`.
282
- */
815
+ * Re-evaluation cadence in milliseconds while throttled, so `retryAfter`
816
+ * ticks down and `disabled` flips back automatically. Defaults to `1000`.
817
+ */
283
818
  tickMs?: number;
284
819
  }
285
820
  interface RateLimitHandle {
@@ -299,17 +834,57 @@ interface RateLimitHandle {
299
834
  teardown: () => void;
300
835
  }
301
836
  /**
302
- * Client-side mirror of a rate limit for instant UX — disable a button or show
303
- * a countdown without a round-trip. It runs the same token-bucket / fixed-window
304
- * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
305
- * authoritative check; the server remains the source of truth.
306
- *
307
- * `config` is read on every call; pass a stable reference (module constant).
308
- *
309
- * Call `teardown()` when the component is destroyed to stop the auto-tick
310
- * interval (`onDestroy(handle.teardown)`).
311
- */
837
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
838
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
839
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
840
+ * authoritative check; the server remains the source of truth.
841
+ *
842
+ * `config` is read on every call; pass a stable reference (module constant).
843
+ *
844
+ * Call `teardown()` when the component is destroyed to stop the auto-tick
845
+ * interval (`onDestroy(handle.teardown)`).
846
+ */
312
847
  declare const rateLimit: (config: RateLimitConfig, options?: RateLimitOptions) => RateLimitHandle;
848
+ /** The lifecycle of a stream the store is observing. */
849
+ type StreamStatus = "complete" | "error" | "idle" | "streaming";
850
+ interface StreamStoreOptions {
851
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
852
+ maxBuffer?: number;
853
+ shardKey?: string;
854
+ }
855
+ interface StreamHandle<T> {
856
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
857
+ cancel: () => void;
858
+ /** Svelte readable store of the chunks the server has pushed so far, in arrival order. */
859
+ chunks: Readable<ReadonlyArray<T>>;
860
+ /** Svelte readable store of the last stream error (`undefined` when healthy). */
861
+ error: Readable<Error | undefined>;
862
+ /** Svelte readable store of the stream lifecycle status. */
863
+ status: Readable<StreamStatus>;
864
+ /**
865
+ * Stop the stream and release the iterator. Call in `onDestroy`
866
+ * (`onDestroy(handle.teardown)`) when you consume `chunks` eagerly; when you
867
+ * read `chunks` with `$` the store tears itself down as the last subscriber
868
+ * leaves.
869
+ */
870
+ teardown: () => void;
871
+ }
872
+ /**
873
+ * Open a streaming query and expose its chunks, lifecycle status, and last error
874
+ * as Svelte readable stores. The `chunks` store is lazy: the stream opens on the
875
+ * first subscriber to `chunks` and is cancelled when the last one leaves (its
876
+ * chunks reset on the next open). `status` and `error` mirror that same stream.
877
+ *
878
+ * Passing `"skip"` as `args` keeps the stores connected but the stream dormant
879
+ * (`chunks` stays empty, `status` stays `"idle"`). The Svelte counterpart to
880
+ * React's `useStream`, re-expressed as stores you read with `$`.
881
+ *
882
+ * Pass an explicit `client` as the first argument to bypass the ambient context
883
+ * (useful in tests), or omit it to resolve the client published by
884
+ * `setLunoraClient`.
885
+ */
886
+ declare function stream<F extends FunctionReference<"stream">>(function_: F, args: ArgsOf<F> | "skip", options?: StreamStoreOptions): StreamHandle<ReturnOf<F>>;
887
+ declare function stream<F extends FunctionReference<"stream">>(client: LunoraClient, function_: F, args: ArgsOf<F> | "skip", options?: StreamStoreOptions): StreamHandle<ReturnOf<F>>;
313
888
  interface SubscriptionStoreOptions {
314
889
  onError?: (error: Error) => void;
315
890
  shardKey?: string;
@@ -321,15 +896,169 @@ interface SubscriptionHandle<T> {
321
896
  error: Readable<Error | undefined>;
322
897
  }
323
898
  /**
324
- * Create a pair of Svelte readable stores that open a live subscription
325
- * against the Lunora backend. `data` updates on every server push; `error`
326
- * captures the last subscription error. Both stores are lazy: the subscription
327
- * opens on the first subscriber to `data` and tears down when it stops.
328
- *
329
- * Passing `"skip"` as `args` keeps the stores connected but the subscription
330
- * dormant (`data` stays `undefined`). Pass an explicit `client` as the first
331
- * argument to bypass the ambient context (useful in tests).
332
- */
899
+ * Create a pair of Svelte readable stores that open a live subscription
900
+ * against the Lunora backend. `data` updates on every server push; `error`
901
+ * captures the last subscription error. Both stores are lazy: the subscription
902
+ * opens on the first subscriber to `data` and tears down when it stops.
903
+ *
904
+ * Passing `"skip"` as `args` keeps the stores connected but the subscription
905
+ * dormant (`data` stays `undefined`). Pass an explicit `client` as the first
906
+ * argument to bypass the ambient context (useful in tests).
907
+ */
333
908
  declare function subscription<F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: SubscriptionStoreOptions): SubscriptionHandle<ReturnOf<F>>;
334
909
  declare function subscription<F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F> | "skip", options?: SubscriptionStoreOptions): SubscriptionHandle<ReturnOf<F>>;
335
- export { type AuthStore, type ConnectionStatusStore, type HeartbeatReference, type InfiniteQueryHandle, type InfiniteQueryOptions, type ListPresentReference, type MutationHandle, 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, getLunoraClient, hydratePreloaded, infiniteQuery, mutation, paginatedQuery, presence, query, rateLimit, setLunoraClient, subscription };
910
+ /**
911
+ * Browser Web Audio subsystems for `useVoiceAgent` — the default microphone
912
+ * capture and speaker playback implementations injected into the composable via
913
+ * its `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
914
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
915
+ * composable's transport + reactive-state logic and remains mockable in a
916
+ * non-browser test env.
917
+ */
918
+ /**
919
+ * The negotiated audio format the voice DO streams back. Mirrors
920
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
921
+ * imported) so this Svelte package never pulls in the server-only `@lunora/agent`
922
+ * module graph.
923
+ */
924
+ type VoiceAudioFormat = "mp3" | "wav";
925
+ /** Captures microphone audio and reports level / turn boundaries back to the composable. */
926
+ interface VoiceMicrophone {
927
+ /** Mute/unmute the mic without tearing down the capture graph. */
928
+ setMuted: (muted: boolean) => void;
929
+ /** Stop capture and release the media stream + audio graph. */
930
+ stop: () => void;
931
+ }
932
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
933
+ interface VoiceSpeaker {
934
+ /** Queue a decoded audio chunk for gap-minimized playback. */
935
+ enqueue: (audio: Uint8Array) => void;
936
+ /** Drop everything queued and stop the current chunk (barge-in). */
937
+ interrupt: () => void;
938
+ /** Release the playback audio context. */
939
+ stop: () => void;
940
+ }
941
+ /** Config passed to a {@link CreateMicrophone} factory. */
942
+ interface MicrophoneConfig {
943
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
944
+ interruptChunks: number;
945
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
946
+ interruptThreshold: number;
947
+ /** `true` while `status === "speaking"` — gates barge-in detection. */
948
+ isSpeaking: () => boolean;
949
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
950
+ onAudio: (pcm: Uint8Array) => void;
951
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
952
+ onInterrupt: () => void;
953
+ /** The current input RMS (0–1), for a level meter. */
954
+ onLevel: (rms: number) => void;
955
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
956
+ onSilence: () => void;
957
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
958
+ silenceDurationMs: number;
959
+ /** RMS below which audio counts as silence. */
960
+ silenceThreshold: number;
961
+ }
962
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
963
+ type CreateSpeaker = (config: {
964
+ audioFormat: VoiceAudioFormat;
965
+ }) => VoiceSpeaker;
966
+ /**
967
+ * The `agents.<name>Voice` reference codegen emits for a voice-enabled agent — a
968
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
969
+ * generated member, so passing `api.agents.<name>Voice` type-checks.
970
+ */
971
+ type VoiceReference = FunctionReference<"stream", {
972
+ threadKey: string;
973
+ }, Record<string, unknown>>;
974
+ /** The lifecycle of a voice call, mirrored to the UI. */
975
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
976
+ /** A minimal structural subset of the DOM `WebSocket` the handle drives. */
977
+ interface VoiceSocket {
978
+ binaryType: string;
979
+ close: () => void;
980
+ onclose: ((event: unknown) => void) | null;
981
+ onerror: ((event: unknown) => void) | null;
982
+ onmessage: ((event: {
983
+ data: unknown;
984
+ }) => void) | null;
985
+ onopen: ((event: unknown) => void) | null;
986
+ readonly readyState: number;
987
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
988
+ }
989
+ type CreateSocket = (url: string) => VoiceSocket;
990
+ interface VoiceAgentOptions {
991
+ /**
992
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
993
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
994
+ * Audio graph stays isolated (and mockable in a non-browser test env).
995
+ */
996
+ createMicrophone?: CreateMicrophone;
997
+ /** Advanced/test seam: open the transport. Defaults to `new WebSocket(url)`. */
998
+ createSocket?: CreateSocket;
999
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1000
+ createSpeaker?: CreateSpeaker;
1001
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1002
+ interruptChunks?: number;
1003
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1004
+ interruptThreshold?: number;
1005
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1006
+ silenceDurationMs?: number;
1007
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1008
+ silenceThreshold?: number;
1009
+ /** The thread to converse on — shared with the agent's text turns. */
1010
+ threadKey: string;
1011
+ /** The generated `api.agents.<name>Voice` reference — identifies the voice DO endpoint. */
1012
+ voice: VoiceReference;
1013
+ }
1014
+ interface VoiceAgentHandle {
1015
+ /** Svelte readable store of the current input RMS (0–1) — drive a mic level meter. Read with `$audioLevel`. */
1016
+ audioLevel: Readable<number>;
1017
+ /** Svelte readable store: `true` once the WS `ready` handshake completed. Read with `$connected`. */
1018
+ connected: Readable<boolean>;
1019
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. Call in `onDestroy`. */
1020
+ endCall: () => void;
1021
+ /** Svelte readable store of the last transport/pipeline error, or `undefined`. Read with `$error`. */
1022
+ error: Readable<Error | undefined>;
1023
+ /** Svelte readable store of the live assistant text for the in-flight turn (grows via deltas; finalized on done). Read with `$interimTranscript`. */
1024
+ interimTranscript: Readable<string>;
1025
+ /** Svelte readable store: `true` while the mic is muted. Read with `$isMuted`. */
1026
+ isMuted: Readable<boolean>;
1027
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1028
+ sendText: (text: string) => void;
1029
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1030
+ startCall: () => Promise<void>;
1031
+ /** Svelte readable store of the current call lifecycle. Read with `$status`. */
1032
+ status: Readable<VoiceStatus>;
1033
+ /** Mute/unmute the microphone. Returns the new muted state. */
1034
+ toggleMute: () => boolean;
1035
+ /** Svelte readable store of the last finalized user utterance (STT result). Read with `$transcript`. */
1036
+ transcript: Readable<string>;
1037
+ }
1038
+ /**
1039
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1040
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1041
+ * streams the agent's synthesized speech back through the browser's audio output,
1042
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1043
+ * `audioLevel`) to Svelte readable stores you read with `$`. Pass the generated
1044
+ * `api.agents.<name>Voice` reference (never a string), matching `agentChat`'s
1045
+ * reference-passing style. The Svelte counterpart to React's `useVoiceAgent`,
1046
+ * re-expressed as stores; the per-call connection lives in a closure variable (a
1047
+ * handle is created once per component, so no store-of-store indirection is
1048
+ * needed).
1049
+ *
1050
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1051
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1052
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1053
+ * `createSocket`) so the handle is drivable outside a browser.
1054
+ *
1055
+ * There is no auto-dispose in Svelte — call `endCall` in `onDestroy`
1056
+ * (`onDestroy(handle.endCall)`) to tear the call down if the component unmounts
1057
+ * mid-call.
1058
+ *
1059
+ * Pass `client` explicitly, or omit it to resolve the ambient client published by
1060
+ * `setLunoraClient`.
1061
+ */
1062
+ declare function voiceAgent(options: VoiceAgentOptions): VoiceAgentHandle;
1063
+ declare function voiceAgent(client: LunoraClient, options: VoiceAgentOptions): VoiceAgentHandle;
1064
+ export { type AgentApi, type AgentChatApi, type AgentChatHandle, type AgentChatMessage, type AgentChatOptions, type AgentHandle, type AgentLiveEvent, type AgentOptions, type AgentProgressEvent, type AgentStateApi, type AgentStateHandle, type AgentStateOptions, type AgentThreadRecord, type AgentThreadStatus, type AgentTokenDelta, type AgentToolEvent, type AgentToolEventsApi, type AgentToolEventsHandle, type AgentToolEventsOptions, type AuthGateStore, type AuthStore, type ConnectionStatusStore, type 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 StreamHandle, type StreamStatus, type StreamStoreOptions, type SubscriptionHandle, type SubscriptionStoreOptions, type VoiceAgentHandle, type VoiceAgentOptions, type VoiceAudioFormat, type VoiceReference, type VoiceStatus, agent, agentChat, agentState, agentToolEvents, auth, authGate, connectionStatus, flag, flags, getLunoraClient, hydratePreloaded, infiniteQuery, mutation, mutator, paginatedQuery, presence, query, rateLimit, setLunoraClient, stream, subscription, voiceAgent };