@lunora/angular 1.0.0-alpha.1 → 1.0.0-alpha.100

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 (36) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +44 -0
  3. package/dist/index.d.mts +1479 -113
  4. package/dist/index.d.ts +1479 -113
  5. package/dist/index.mjs +1 -5
  6. package/dist/packem_shared/LUNORA_CLIENT-B0toApHY.mjs +1 -0
  7. package/dist/packem_shared/agent-BCt1D_wQ.mjs +1 -0
  8. package/dist/packem_shared/agentChat-DMMjTLnF.mjs +1 -0
  9. package/dist/packem_shared/agentState-Cdyss0S4.mjs +1 -0
  10. package/dist/packem_shared/agentToolEvents-BOp6-TK8.mjs +1 -0
  11. package/dist/packem_shared/auth-C3dB8sYS.mjs +1 -0
  12. package/dist/packem_shared/connectionStatus-UhmuwzMa.mjs +1 -0
  13. package/dist/packem_shared/flag-BJxkgJR2.mjs +1 -0
  14. package/dist/packem_shared/hydratePreloaded-gUUl_6tS.mjs +1 -0
  15. package/dist/packem_shared/infiniteQuery-yZS4F7PI.mjs +1 -0
  16. package/dist/packem_shared/liveQuery-ZIgKq4et.mjs +1 -0
  17. package/dist/packem_shared/mutate-BZvLQLyu.mjs +1 -0
  18. package/dist/packem_shared/mutator-DjG1yGk8.mjs +1 -0
  19. package/dist/packem_shared/platform-DNlq-CRU.mjs +1 -0
  20. package/dist/packem_shared/presence-DUkZtSSL.mjs +1 -0
  21. package/dist/packem_shared/rateLimit-B3h9qzh-.mjs +1 -0
  22. package/dist/packem_shared/runAction-BfiPq4Xz.mjs +1 -0
  23. package/dist/packem_shared/stream-CVSnLbC2.mjs +1 -0
  24. package/dist/packem_shared/subscription-B_Xj8Ezd.mjs +1 -0
  25. package/dist/packem_shared/voiceAgent-CyPFWGUt.mjs +1 -0
  26. package/dist/server.d.mts +1 -0
  27. package/dist/server.d.ts +1 -0
  28. package/dist/server.mjs +1 -0
  29. package/dist/upload.d.mts +57 -0
  30. package/dist/upload.d.ts +57 -0
  31. package/dist/upload.mjs +1 -0
  32. package/package.json +13 -3
  33. package/dist/packem_shared/LUNORA_CLIENT-DHUfNu9x.mjs +0 -23
  34. package/dist/packem_shared/connectionStatus-BlLodleK.mjs +0 -15
  35. package/dist/packem_shared/liveQuery-D5VQBOgf.mjs +0 -28
  36. package/dist/packem_shared/mutate-D3rEHwbb.mjs +0 -8
package/dist/index.d.ts CHANGED
@@ -1,57 +1,642 @@
1
- import { InjectionToken, EnvironmentProviders, DestroyRef, Signal } from '@angular/core';
2
- import { LunoraClient, LunoraClientOptions, ConnectionStatus, SubscriptionError, FunctionReference, ArgsOf, ReturnOf, MutationCallOptions } from '@lunora/client';
3
- export type { ArgsOf, ConnectionStatus, FunctionReference, LunoraClient, LunoraClientOptions, MutationCallOptions, ReturnOf, SubscriptionError, Unsubscribe } from '@lunora/client';
1
+ import { DestroyRef, Signal, InjectionToken, EnvironmentProviders, Injector } from '@angular/core';
2
+ import { FunctionReference, LunoraClient, SubscriptionErrorCallback, SubscriptionError, User, LunoraClientOptions, ConnectionStatus, Preloaded, ArgsOf, ReturnOf, MutationCallOptions, MutatorHandle, ActionCallOptions } from '@lunora/client';
3
+ export type { ArgsOf, ConnectionStatus, FunctionReference, LunoraClient, LunoraClientOptions, MutationCallOptions, Preloaded, ReturnOf, SubscriptionError, Unsubscribe } from '@lunora/client';
4
+ import { AuthStatus } from '@lunora/client/auth';
5
+ import { PaginationStatus } from '@lunora/client/pagination';
6
+ import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
4
7
  export { SKIP } from '@lunora/client/query';
5
8
  /**
6
- * DI token carrying the framework-neutral {@link LunoraClient}. Every reactive
7
- * primitive in this adapter (`liveQuery`, `mutate`, `connectionStatus`) reads the
8
- * client from here, so a single {@link provideLunora} in the application config
9
- * wires the whole app.
10
- *
11
- * The token has a root-scoped default factory, so it resolves even without
12
- * {@link provideLunora}: it builds one same-origin browser client (which opens
13
- * its WebSocket lazily on the first subscription). Call {@link provideLunora} to
14
- * point it at a remote URL or hand it a pre-built client.
15
- */
9
+ * The lifecycle status stored on an agent thread. Client-safe mirror of
10
+ * `@lunora/agent`'s `AgentThreadStatus` — re-declared here (rather than imported)
11
+ * so this Angular entry never pulls in the server-only `@lunora/agent` module graph
12
+ * (the adapter stays Angular + `@lunora/client` only). Keep in sync with
13
+ * `packages/agent/src/types.ts`.
14
+ * @experimental
15
+ */
16
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
17
+ /**
18
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
19
+ * subset of the persisted thread row — every field beyond `status` is optional so
20
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
21
+ * `agent_threads` table in `packages/agent/src/component.ts`.
22
+ * @experimental
23
+ */
24
+ interface AgentThreadRecord {
25
+ createdAt?: number;
26
+ /**
27
+ * The failure message when `status === "error"`, `null` once a later run
28
+ * cleared it, absent on a thread that has never failed. Read it for
29
+ * truthiness — `null` and absent both mean "no error".
30
+ */
31
+ error?: null | string;
32
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
33
+ instanceId?: string;
34
+ messageCount?: number;
35
+ /** The verified thread owner, when the run was started with one. */
36
+ owner?: string;
37
+ status: AgentThreadStatus;
38
+ title?: string;
39
+ updatedAt?: number;
40
+ }
41
+ /**
42
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
43
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
44
+ * re-declared here (rather than imported) so this Angular entry never pulls in the
45
+ * server-only `@lunora/agent` module graph. Keep in sync with the
46
+ * `agent_messages` table in `packages/agent/src/component.ts`.
47
+ * @experimental
48
+ */
49
+ interface AgentChatMessage {
50
+ content: string;
51
+ createdAt?: number;
52
+ /**
53
+ * `true` for a client-side optimistic user message not yet acknowledged by
54
+ * the server. Cleared once the durable history carries the matching user turn.
55
+ */
56
+ optimistic?: boolean;
57
+ role: "assistant" | "system" | "tool" | "user";
58
+ seq: number;
59
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
60
+ status?: "approved" | "awaiting_approval" | "rejected";
61
+ toolCallId?: string;
62
+ toolCalls?: ReadonlyArray<{
63
+ id: string;
64
+ input: unknown;
65
+ name: string;
66
+ }>;
67
+ toolName?: string;
68
+ }
69
+ /**
70
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
71
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed the chat surface's
72
+ * streaming text live and are never replayed; the persisted assistant message
73
+ * stays the single source of truth.
74
+ * @experimental
75
+ */
76
+ interface AgentTokenDelta {
77
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
78
+ kind?: "token";
79
+ /** The incremental text chunk the model just produced. */
80
+ text: string;
81
+ /** The thread this delta belongs to. */
82
+ threadKey: string;
83
+ /** The zero-based index of the turn producing the delta. */
84
+ turn: number;
85
+ }
86
+ /**
87
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
88
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
89
+ * surfaced by `agentToolEvents`, ignored by the chat surface's streaming text.
90
+ * @experimental
91
+ */
92
+ interface AgentProgressEvent {
93
+ /** The arbitrary, JSON-serializable payload the tool reported. */
94
+ data: unknown;
95
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
96
+ kind: "progress";
97
+ /** The thread this event belongs to. */
98
+ threadKey: string;
99
+ /** The tool call this progress belongs to. */
100
+ toolCallId: string;
101
+ }
102
+ /**
103
+ * A single event on the agent's live-only channel — a streamed token delta or a
104
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
105
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
106
+ * it unset).
107
+ * @experimental
108
+ */
109
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
110
+ /**
111
+ * The `agents.agentThread` reference the primitive subscribes to for live thread
112
+ * state (status + the in-flight `instanceId`). A structural subset of the
113
+ * generated `api.agents` surface, so the whole generated `api` object is
114
+ * assignable.
115
+ * @experimental
116
+ */
117
+ interface AgentApi {
118
+ agents: {
119
+ agentThread: FunctionReference<"query", {
120
+ key: string;
121
+ }, Record<string, unknown> | undefined>;
122
+ };
123
+ }
124
+ /**
125
+ * `AgentOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
126
+ * @experimental
127
+ */
128
+ interface AgentOptions {
129
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
130
+ api: AgentApi;
131
+ /**
132
+ * Optional app mutation over the agent's cancel path
133
+ * (`ctx.agents.<name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
134
+ * When omitted (or no run is in flight) {@link AgentResult.cancel} is a no-op.
135
+ */
136
+ cancel?: FunctionReference<"mutation">;
137
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
138
+ client?: LunoraClient;
139
+ /**
140
+ * `DestroyRef` whose `onDestroy` tears the live subscription down. Defaults to
141
+ * `inject(DestroyRef)` — the calling component/service.
142
+ */
143
+ destroyRef?: DestroyRef;
144
+ /**
145
+ * Called when the live thread subscription reports an error (a session
146
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
147
+ * failure is invisible and `thread` / `status` are cleared until a later frame arrives.
148
+ */
149
+ onError?: SubscriptionErrorCallback;
150
+ /**
151
+ * The app mutation that starts (or continues) a run — a thin wrapper over
152
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
153
+ * {@link AgentOptions.runArgs} and the per-call args.
154
+ */
155
+ run: FunctionReference<"mutation">;
156
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
157
+ runArgs?: Record<string, unknown>;
158
+ /** The thread to observe and drive. */
159
+ threadKey: string;
160
+ }
161
+ /**
162
+ * `AgentResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
163
+ * @experimental
164
+ */
165
+ interface AgentResult {
166
+ /**
167
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
168
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
169
+ */
170
+ cancel: () => Promise<void>;
171
+ /** The live thread subscription's last error, or `undefined`. */
172
+ error: Signal<SubscriptionError | undefined>;
173
+ /** `true` while a `run` invocation is in flight. */
174
+ pending: Signal<boolean>;
175
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
176
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
177
+ /** The live thread status, or `undefined` before the thread exists. */
178
+ status: Signal<AgentThreadStatus | undefined>;
179
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
180
+ thread: Signal<AgentThreadRecord | undefined>;
181
+ }
182
+ /**
183
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
184
+ * chat message surface. Composes `subscription(api.agents.agentThread)` for live
185
+ * state and drives the run/cancel writes straight on the client — the Angular
186
+ * counterpart to React's `useAgent`, re-expressed with signals. For the full
187
+ * conversation surface (durable history + streaming + approvals) use `agentChat`.
188
+ *
189
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
190
+ * `ctx.agents.<name>.run` / `.cancel`, so the primitive hard-codes no function
191
+ * names beyond the `agents:*` surface.
192
+ *
193
+ * Call from an injection context (component/service field or constructor); pass an
194
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
195
+ * @experimental
196
+ */
197
+ declare const agent: (options: AgentOptions) => AgentResult;
198
+ /** The `agents:agentMessages` reference — live durable thread history. */
199
+ type AgentMessagesReference$1 = FunctionReference<"query", {
200
+ key: string;
201
+ limit?: number;
202
+ }, ReadonlyArray<Record<string, unknown>>>;
203
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
204
+ type AgentApprovalReference = FunctionReference<"mutation", {
205
+ decision: "approve" | "reject";
206
+ instanceId: string;
207
+ note?: string;
208
+ threadKey: string;
209
+ toolCallId: string;
210
+ }, {
211
+ resolved: boolean;
212
+ }>;
213
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
214
+ type AgentThreadReference = FunctionReference<"query", {
215
+ key: string;
216
+ }, Record<string, unknown> | undefined>;
217
+ /**
218
+ * An app stream reference that tees the agent's in-flight live events, keyed by
219
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
220
+ * sink — tool progress events; this primitive consumes only the token arm.
221
+ * @experimental
222
+ */
223
+ type AgentTokenStreamReference = FunctionReference<"stream", {
224
+ key: string;
225
+ }, AgentLiveEvent>;
226
+ /**
227
+ * The `agents.*` reference surface the chat primitive reads. A structural subset
228
+ * of the generated `api.agents`, so the whole generated `api` object is
229
+ * assignable.
230
+ * @experimental
231
+ */
232
+ interface AgentChatApi {
233
+ agents: {
234
+ agentMessages: AgentMessagesReference$1;
235
+ agentResolveApproval: AgentApprovalReference;
236
+ agentThread: AgentThreadReference;
237
+ };
238
+ }
239
+ /**
240
+ * `AgentChatOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
241
+ * @experimental
242
+ */
243
+ interface AgentChatOptions {
244
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
245
+ api: AgentChatApi;
246
+ /**
247
+ * Optional app mutation over the agent's cancel path
248
+ * (`ctx.agents.<name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
249
+ * When omitted (or no run is in flight) {@link AgentChatResult.cancel} is a
250
+ * no-op.
251
+ */
252
+ cancel?: FunctionReference<"mutation">;
253
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
254
+ client?: LunoraClient;
255
+ /**
256
+ * `DestroyRef` whose `onDestroy` tears the subscriptions + stream down. Defaults
257
+ * to `inject(DestroyRef)` — the calling component/service.
258
+ */
259
+ destroyRef?: DestroyRef;
260
+ /** History depth forwarded to `agents:agentMessages`. */
261
+ limit?: number;
262
+ /**
263
+ * Called when the live history or thread subscription reports an error (a
264
+ * session expiry, an RLS denial). Without it — and without reading `error` —
265
+ * such a failure is invisible and `messages` / `status` are cleared until a later frame arrives.
266
+ */
267
+ onError?: SubscriptionErrorCallback;
268
+ /**
269
+ * The app mutation that starts (or continues) a run — a thin wrapper over
270
+ * `ctx.agents.<name>.run(...)`. Called with `{ threadKey, input }` merged with
271
+ * {@link AgentChatOptions.sendArgs} and the per-call args.
272
+ */
273
+ send: FunctionReference<"mutation">;
274
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
275
+ sendArgs?: Record<string, unknown>;
276
+ /**
277
+ * Optional live token-delta stream — an app stream function that tees the
278
+ * agent's in-flight deltas. When omitted {@link AgentChatResult.streamingText}
279
+ * stays empty and the UI updates message-by-message from durable history.
280
+ */
281
+ stream?: AgentTokenStreamReference;
282
+ /** The thread to observe and continue. */
283
+ threadKey: string;
284
+ }
285
+ /**
286
+ * `AgentChatResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
287
+ * @experimental
288
+ */
289
+ interface AgentChatResult {
290
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
291
+ approve: (toolCallId: string, note?: string) => Promise<void>;
292
+ /**
293
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
294
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
295
+ */
296
+ cancel: () => Promise<void>;
297
+ /** The history or thread subscription's last error, or `undefined`. */
298
+ error: Signal<SubscriptionError | undefined>;
299
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
300
+ messages: Signal<ReadonlyArray<AgentChatMessage>>;
301
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
302
+ reject: (toolCallId: string, note?: string) => Promise<void>;
303
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
304
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
305
+ /** The live thread status, or `undefined` before the thread exists. */
306
+ status: Signal<AgentThreadStatus | undefined>;
307
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
308
+ streamingText: Signal<string>;
309
+ }
310
+ /**
311
+ * A first-class agent chat surface: live durable history + in-flight token
312
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey` —
313
+ * the Angular counterpart to React's `useAgentChat`, re-expressed with signals.
314
+ *
315
+ * It composes the existing primitives rather than adding transport:
316
+ * `subscription(api.agents.agentMessages)` for durable history,
317
+ * `subscription(api.agents.agentThread)` for live status + the in-flight
318
+ * `instanceId`, {@link stream} over an app token stream for in-flight deltas, and
319
+ * the client's own `mutation` for the writes (`api.agents.agentResolveApproval` for
320
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*` surface
321
+ * is hard-coded — `send`/`cancel`/`stream` stay generic references.
322
+ *
323
+ * A `send` optimistically appends the user turn so it renders immediately; the
324
+ * optimistic row clears once the durable history carries the acknowledged turn.
325
+ * `streamingText` is live-only: it holds the current turn's streamed text and
326
+ * empties as soon as that turn's assistant message lands in `messages` (the
327
+ * persisted message is the source of truth), consistent with the loop's
328
+ * replay-safe, live-only delta design.
329
+ *
330
+ * Call from an injection context (component/service field or constructor); pass an
331
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
332
+ * @experimental
333
+ */
334
+ declare const agentChat: (options: AgentChatOptions) => AgentChatResult;
335
+ /**
336
+ * The `agents.agentState` reference the primitive subscribes to for the thread's
337
+ * live synced state. A structural subset of the generated `api.agents` surface
338
+ * (like `AgentApi` for `agentThread`), so the whole generated `api` object is
339
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type is
340
+ * mirrored by the primitive's generic `T`, since codegen pins the reference return
341
+ * as an optional record (it never evaluates agent config).
342
+ * @experimental
343
+ */
344
+ interface AgentStateApi {
345
+ agents: {
346
+ agentState: FunctionReference<"query", {
347
+ key: string;
348
+ }, Record<string, unknown> | undefined>;
349
+ };
350
+ }
351
+ /**
352
+ * `AgentStateOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
353
+ * @experimental
354
+ */
355
+ interface AgentStateOptions {
356
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
357
+ api: AgentStateApi;
358
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
359
+ client?: LunoraClient;
360
+ /**
361
+ * `DestroyRef` whose `onDestroy` tears the subscription down. Defaults to
362
+ * `inject(DestroyRef)` — the calling component/service.
363
+ */
364
+ destroyRef?: DestroyRef;
365
+ /** The thread whose synced state to observe. */
366
+ threadKey: string;
367
+ }
368
+ /**
369
+ * `AgentStateResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
370
+ * @experimental
371
+ */
372
+ interface AgentStateResult<T> {
373
+ /** The subscription error, if the live channel reported one. */
374
+ error: Signal<SubscriptionError | undefined>;
375
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
376
+ state: Signal<T | undefined>;
377
+ }
378
+ /**
379
+ * Subscribe to an agent thread's synced state — the `setState`-style value a tool
380
+ * writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`. A
381
+ * thin wrapper over `subscription(api.agents.agentState, { key })`: the server
382
+ * pushes a fresh frame whenever the state changes (the dedicated query's per-socket
383
+ * JSON memo suppresses no-op pushes on unrelated thread writes), so `state` updates
384
+ * only on a real `setState`. The Angular counterpart to React's `useAgentState`,
385
+ * re-expressed with signals.
386
+ *
387
+ * Generic over the app's state shape (`agentState<SupportState>(...)`, itself a
388
+ * record) — the reference is typed as an optional record because codegen cannot see
389
+ * the per-agent state type; the generic casts to `T`. The `extends` bound (not a
390
+ * bare unbounded type parameter) is required: this `.ts` file is parsed JSX-aware by
391
+ * the bundler, where an unbounded type-param arrow is ambiguous with a JSX element.
392
+ *
393
+ * Call from an injection context (component/service field or constructor); pass an
394
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
395
+ * @experimental
396
+ */
397
+ declare const agentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: AgentStateOptions) => AgentStateResult<T>;
398
+ /** The `agents:agentMessages` reference — live durable thread history. */
399
+ type AgentMessagesReference = FunctionReference<"query", {
400
+ key: string;
401
+ limit?: number;
402
+ }, ReadonlyArray<Record<string, unknown>>>;
403
+ /**
404
+ * An app stream reference that tees the agent's in-flight live events, keyed by
405
+ * thread. Carries token deltas and tool progress events; this primitive consumes
406
+ * only the progress arm (`kind === "progress"`).
407
+ */
408
+ type AgentLiveStreamReference = FunctionReference<"stream", {
409
+ key: string;
410
+ }, AgentLiveEvent>;
411
+ /**
412
+ * The `agents.*` reference surface the tool-events primitive reads. A structural
413
+ * subset of the generated `api.agents`, so the whole generated `api` object is
414
+ * assignable.
415
+ * @experimental
416
+ */
417
+ interface AgentToolEventsApi {
418
+ agents: {
419
+ agentMessages: AgentMessagesReference;
420
+ };
421
+ }
422
+ /**
423
+ * `AgentToolEventsOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
424
+ * @experimental
425
+ */
426
+ interface AgentToolEventsOptions {
427
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
428
+ api: AgentToolEventsApi;
429
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
430
+ client?: LunoraClient;
431
+ /**
432
+ * `DestroyRef` whose `onDestroy` tears the subscription + stream down. Defaults
433
+ * to `inject(DestroyRef)` — the calling component/service.
434
+ */
435
+ destroyRef?: DestroyRef;
436
+ /** History depth forwarded to `agents:agentMessages`. */
437
+ limit?: number;
438
+ /**
439
+ * Optional live event stream — the same app stream function `agentChat` uses.
440
+ * When supplied, ephemeral `ctx.reportProgress(...)` events for the thread are
441
+ * surfaced as `{ type: "progress" }` entries; when omitted only the durable
442
+ * lifecycle (call / result / awaiting-approval) is returned.
443
+ */
444
+ stream?: AgentLiveStreamReference;
445
+ /** The thread whose tool activity to observe. */
446
+ threadKey: string;
447
+ }
448
+ /**
449
+ * A single tool-lifecycle event for a thread. The durable arms
450
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
451
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
452
+ * stream and has no `seq`. Discriminate on `type`.
453
+ * @experimental
454
+ */
455
+ type AgentToolEvent = {
456
+ data: unknown;
457
+ toolCallId: string;
458
+ type: "progress";
459
+ } | {
460
+ input: unknown;
461
+ seq: number;
462
+ toolCallId: string;
463
+ toolName: string;
464
+ type: "call";
465
+ } | {
466
+ output: string;
467
+ seq: number;
468
+ status?: "approved" | "rejected";
469
+ toolCallId?: string;
470
+ toolName?: string;
471
+ type: "result";
472
+ } | {
473
+ seq: number;
474
+ toolCallId?: string;
475
+ toolName?: string;
476
+ type: "awaiting-approval";
477
+ };
478
+ /**
479
+ * `AgentToolEventsResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
480
+ * @experimental
481
+ */
482
+ interface AgentToolEventsResult {
483
+ /**
484
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
485
+ * followed by any in-flight ephemeral progress events, recomputed from the live
486
+ * subscription + stream. Treat as derived, not identity-stable.
487
+ */
488
+ events: Signal<ReadonlyArray<AgentToolEvent>>;
489
+ }
490
+ /**
491
+ * A focused view of a thread's tool activity: tool calls, their results,
492
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
493
+ * without the full chat message surface. The Angular counterpart to React's
494
+ * `useAgentToolEvents`, re-expressed as a `computed` signal.
495
+ *
496
+ * It composes the existing primitives rather than adding transport:
497
+ * `subscription(api.agents.agentMessages)` for the durable lifecycle and
498
+ * {@link stream} over the optional app event stream for ephemeral progress.
499
+ * Progress events are live-only (the durable path never emits them): they ride the
500
+ * same sink as token deltas and are surfaced here, correlated to their tool call by
501
+ * `toolCallId`. For the conversational surface (messages + streaming text +
502
+ * approvals) use `agentChat`; this primitive is the tool-observability slice.
503
+ *
504
+ * Call from an injection context (component/service field or constructor); pass an
505
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
506
+ * @experimental
507
+ */
508
+ declare const agentToolEvents: (options: AgentToolEventsOptions) => AgentToolEventsResult;
509
+ /**
510
+ * `AuthOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
511
+ * @experimental
512
+ */
513
+ interface AuthOptions {
514
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
515
+ client?: LunoraClient;
516
+ /** `DestroyRef` whose `onDestroy` removes the listeners. Defaults to `inject(DestroyRef)`. */
517
+ destroyRef?: DestroyRef;
518
+ }
519
+ /**
520
+ * `AuthResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
521
+ * @experimental
522
+ */
523
+ interface AuthResult {
524
+ /** Set the auth token (sign-in / sign-out). */
525
+ setToken: (token: string | null) => void;
526
+ /**
527
+ * The resolved auth state. Branch on this, not on `user() === null` — see the
528
+ * contract in `@lunora/client/auth`; `user` is `null` both when signed out
529
+ * and when a held credential's identity could not be resolved.
530
+ */
531
+ status: Signal<AuthStatus>;
532
+ /** The current auth token, or `null`. */
533
+ token: Signal<string | null>;
534
+ /** The resolved user from `store.getUser()`, or `null`. */
535
+ user: Signal<User | null>;
536
+ }
537
+ /**
538
+ * Token + identity plumbing for Angular. `token` is a signal tracking the
539
+ * client's auth token; `user` is a signal resolved from `getCurrentUser()`
540
+ * whenever the token changes. `setToken(jwt)` after sign-in makes subsequent
541
+ * RPC calls carry the `Authorization` header.
542
+ *
543
+ * Multiple `auth` instances on the same client share a single per-client
544
+ * identity store (from `@lunora/client/auth`) — a `setToken` from one component
545
+ * re-renders every watcher with the freshly-resolved user.
546
+ *
547
+ * Call from an injection context (component/service field or constructor):
548
+ * ```ts
549
+ * const { token, user, setToken } = auth();
550
+ * ```
551
+ * @experimental
552
+ */
553
+ declare const auth: (options?: AuthOptions) => AuthResult;
554
+ /**
555
+ * `AuthGateResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
556
+ * @experimental
557
+ */
558
+ interface AuthGateResult {
559
+ /** `true` once a credential is held and nothing has contradicted it. */
560
+ isAuthenticated: Signal<boolean>;
561
+ /** `true` while a credential's first identity resolve is in flight. */
562
+ isLoading: Signal<boolean>;
563
+ }
564
+ /**
565
+ * Derived auth-gate signals for template gating (Angular's `\@if` control
566
+ * flow), built on {@link auth}. Angular has no JSX-style `Authenticated` slot
567
+ * component the way React/Vue/Solid do, so this exposes the same three-state
568
+ * logic as two booleans instead, mapped from the shared `AuthStatus` contract in
569
+ * `@lunora/client/auth`: a credential whose first identity resolve is in flight
570
+ * is `isLoading`; a credential nothing has contradicted — including one whose
571
+ * identity endpoint is unreachable — is `isAuthenticated`; no session is neither
572
+ * (the signed-out state a template checks for with a plain `\@else`).
573
+ *
574
+ * Call from an injection context (component/service field or constructor):
575
+ * ```ts
576
+ * protected readonly authState = authGate();
577
+ * // template: \@if (authState.isAuthenticated()) { ... } \@else if (authState.isLoading()) { ... }
578
+ * ```
579
+ * @experimental
580
+ */
581
+ declare const authGate: (options?: AuthOptions) => AuthGateResult;
582
+ /**
583
+ * DI token carrying the framework-neutral {@link LunoraClient}. Every reactive
584
+ * primitive in this adapter (`liveQuery`, `mutate`, `connectionStatus`) reads the
585
+ * client from here, so a single {@link provideLunora} in the application config
586
+ * wires the whole app.
587
+ *
588
+ * The token has a root-scoped default factory, so it resolves even without
589
+ * {@link provideLunora}: it builds one same-origin browser client (which opens
590
+ * its WebSocket lazily on the first subscription). Call {@link provideLunora} to
591
+ * point it at a remote URL or hand it a pre-built client.
592
+ * @experimental
593
+ */
16
594
  declare const LUNORA_CLIENT: InjectionToken<LunoraClient>;
17
595
  /**
18
- * Options accepted by {@link provideLunora}. Identical to {@link LunoraClientOptions}
19
- * except `url` is optional — it defaults to the page origin in the browser (and to
20
- * `""` on the server; pass an explicit `url` for SSR data-loading — see
21
- * {@link sameOriginUrl}).
22
- */
596
+ * Options accepted by {@link provideLunora}. Identical to {@link LunoraClientOptions}
597
+ * except `url` is optional — it defaults to the page origin in the browser (and to
598
+ * `""` on the server; pass an explicit `url` for SSR data-loading — see
599
+ * {@link sameOriginUrl}).
600
+ * @experimental
601
+ */
23
602
  type ProvideLunoraOptions = Omit<LunoraClientOptions, "url"> & {
24
603
  url?: string;
25
604
  };
26
605
  /**
27
- * Wire a {@link LunoraClient} into the application injector. Add the result to the
28
- * `providers` array of an Angular application config (or any `EnvironmentProviders`
29
- * consumer):
30
- *
31
- * ```ts
32
- * export const appConfig: ApplicationConfig = {
33
- * providers: [provideLunora({ url: "https://api.example.com" })],
34
- * };
35
- * ```
36
- *
37
- * Pass {@link LunoraClientOptions} to configure a fresh client (URL defaults to
38
- * the page origin), or hand in an already-constructed {@link LunoraClient} to
39
- * share one instance (e.g. a client you also preload against during SSR).
40
- */
606
+ * Wire a {@link LunoraClient} into the application injector. Add the result to the
607
+ * `providers` array of an Angular application config (or any `EnvironmentProviders`
608
+ * consumer):
609
+ *
610
+ * ```ts
611
+ * export const appConfig: ApplicationConfig = {
612
+ * providers: [provideLunora({ url: "https://api.example.com" })],
613
+ * };
614
+ * ```
615
+ *
616
+ * Pass {@link LunoraClientOptions} to configure a fresh client (URL defaults to
617
+ * the page origin), or hand in an already-constructed {@link LunoraClient} to
618
+ * share one instance (e.g. a client you also preload against during SSR).
619
+ * @experimental
620
+ */
41
621
  declare const provideLunora: (optionsOrClient?: LunoraClient | ProvideLunoraOptions) => EnvironmentProviders;
42
622
  /**
43
- * Read the {@link LunoraClient} from the current injector. Call inside an
44
- * injection context (a component/service field initializer or constructor, or a
45
- * `runInInjectionContext` callback). Use it to hold the client for imperative
46
- * calls — e.g. `mutation`/`action` from event handlers, which run outside an
47
- * injection context:
48
- *
49
- * ```ts
50
- * private readonly client = injectLunoraClient();
51
- * send = (text: string) => this.client.mutation(api.messages.send, { text });
52
- * ```
53
- */
623
+ * Read the {@link LunoraClient} from the current injector. Call inside an
624
+ * injection context (a component/service field initializer or constructor, or a
625
+ * `runInInjectionContext` callback). Use it to hold the client for imperative
626
+ * calls — e.g. `mutation`/`action` from event handlers, which run outside an
627
+ * injection context:
628
+ *
629
+ * ```ts
630
+ * private readonly client = injectLunoraClient();
631
+ * send = (text: string) => this.client.mutation(api.messages.send, { text });
632
+ * ```
633
+ * @experimental
634
+ */
54
635
  declare const injectLunoraClient: () => LunoraClient;
636
+ /**
637
+ * `ConnectionStatusOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
638
+ * @experimental
639
+ */
55
640
  interface ConnectionStatusOptions {
56
641
  /** Client to observe. Defaults to the injected `LUNORA_CLIENT`. */
57
642
  client?: LunoraClient;
@@ -59,88 +644,869 @@ interface ConnectionStatusOptions {
59
644
  destroyRef?: DestroyRef;
60
645
  }
61
646
  /**
62
- * A `signal` of the client's aggregate live-socket status across all shard
63
- * connections. Reads the current status synchronously and updates on every
64
- * transition (`idle` → `connecting` → `connected` → `offline`). The Angular
65
- * equivalent of `@lunora/react`'s `useConnectionStatus`.
66
- *
67
- * The listener is removed when the owning `DestroyRef` fires. Call from an
68
- * injection context (component/service field or constructor).
69
- */
647
+ * A `signal` of the client's aggregate live-socket status across all shard
648
+ * connections. Reads the current status synchronously and updates on every
649
+ * transition (`idle` → `connecting` → `connected` → `offline`). The Angular
650
+ * equivalent of `@lunora/react`'s `useConnectionStatus`.
651
+ *
652
+ * The listener is removed when the owning `DestroyRef` fires. Call from an
653
+ * injection context (component/service field or constructor).
654
+ * @experimental
655
+ */
70
656
  declare const connectionStatus: (options?: ConnectionStatusOptions) => Signal<ConnectionStatus>;
657
+ /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
658
+ type FlagValue$1 = boolean | number | string | {
659
+ [key: string]: unknown;
660
+ } | unknown[] | null;
661
+ /**
662
+ * The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags.
663
+ * @experimental
664
+ */
665
+ type FlagValue = FlagValue$1;
666
+ /**
667
+ * `FlagOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
668
+ * @experimental
669
+ */
670
+ interface FlagOptions {
671
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
672
+ client?: LunoraClient;
673
+ /** `DestroyRef` whose `onDestroy` tears down the subscription. Defaults to `inject(DestroyRef)`. */
674
+ destroyRef?: DestroyRef;
675
+ }
676
+ /**
677
+ * Subscribe to a single feature flag, live over Lunora's WebSocket.
678
+ *
679
+ * The returned signal holds `defaultValue` until the first evaluation lands, then
680
+ * the server's resolved value — re-pushed whenever the provider re-evaluates.
681
+ * The flag's kind is inferred from `defaultValue`'s runtime type, so
682
+ * `flag("dark", false)` reads a boolean and `flag("hero", "control")` a string.
683
+ *
684
+ * The reactive channel is public, so the server evaluates every flag under the
685
+ * socket's own verified identity — the targeting key your `defineFlags({
686
+ * identify })` derives — and accepts no client-supplied targeting context. For
687
+ * evaluation under a context you compute, call `ctx.flags.*` inside a query,
688
+ * mutation, or action and return the resolved value.
689
+ *
690
+ * Evaluation runs through whatever OpenFeature provider the app wired in
691
+ * `lunora/flags.ts`; the read never throws — a provider error resolves the
692
+ * default (the same fail-open contract as server-side `ctx.flags`). No
693
+ * subscription opens during SSR; the signal stays at `defaultValue`.
694
+ *
695
+ * Call from an injection context:
696
+ * ```ts
697
+ * readonly darkMode = flag("dark-mode", false);
698
+ * ```
699
+ * @experimental
700
+ */
701
+ declare const flag: <T extends FlagValue>(key: string, defaultValue: T, options?: FlagOptions) => Signal<T>;
702
+ /**
703
+ * `FlagsOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
704
+ * @experimental
705
+ */
706
+ interface FlagsOptions {
707
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
708
+ client?: LunoraClient;
709
+ /** `DestroyRef` whose `onDestroy` tears down the subscriptions. Defaults to `inject(DestroyRef)`. */
710
+ destroyRef?: DestroyRef;
711
+ }
712
+ /**
713
+ * Subscribe to several feature flags at once, live over Lunora's WebSocket.
714
+ *
715
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
716
+ * default, and the returned signal holds the same-shaped record with resolved
717
+ * values (the defaults until each evaluation lands). Like {@link flag} it
718
+ * evaluates under the socket's server-verified identity only.
719
+ *
720
+ * Call from an injection context:
721
+ * ```ts
722
+ * readonly features = flags({ "dark-mode": false, "new-editor": false });
723
+ * ```
724
+ * @experimental
725
+ */
726
+ declare const flags: <T extends Record<string, FlagValue>>(flagDefaults: T, options?: FlagsOptions) => Signal<T>;
727
+ /**
728
+ * `HydratePreloadedOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
729
+ * @experimental
730
+ */
731
+ interface HydratePreloadedOptions {
732
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
733
+ client?: LunoraClient;
734
+ /** `DestroyRef` whose `onDestroy` tears the subscription down. Defaults to `inject(DestroyRef)`. */
735
+ destroyRef?: DestroyRef;
736
+ }
737
+ /**
738
+ * `HydratePreloadedResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
739
+ * @experimental
740
+ */
741
+ interface HydratePreloadedResult<T> {
742
+ /** The latest value pushed by the server. Seeded synchronously from the preloaded value. */
743
+ data: Signal<T | undefined>;
744
+ /** The latest subscription error, or `undefined`. */
745
+ error: Signal<SubscriptionError | undefined>;
746
+ }
747
+ /**
748
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
749
+ * during SSR, then keep it live — the Angular half of the reactive-loader
750
+ * handoff.
751
+ *
752
+ * The returned signal is seeded **synchronously** from `preloaded.value`, so the
753
+ * very first read (during hydration) shows the server value: no loading flash,
754
+ * no hydration mismatch. After seeding it opens a WebSocket subscription on the
755
+ * same `(functionPath, args, shardKey)` the SSR loader used, so every later
756
+ * server delta updates the signal exactly like `liveQuery`.
757
+ *
758
+ * The subscription tears down when the owning `DestroyRef` fires.
759
+ *
760
+ * Call from an injection context:
761
+ * ```ts
762
+ * readonly { data, error } = hydratePreloaded(preloadedMessages);
763
+ * ```
764
+ * @experimental
765
+ */
766
+ declare const hydratePreloaded: <T>(preloaded: Preloaded<T>, options?: HydratePreloadedOptions) => HydratePreloadedResult<T>;
767
+ /**
768
+ * `LiveQueryOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
769
+ * @experimental
770
+ */
71
771
  interface LiveQueryOptions {
72
772
  /**
73
- * Client to bind to. Defaults to the injected `LUNORA_CLIENT`; pass one
74
- * explicitly to use `liveQuery` outside an injection context (or in a test).
75
- */
773
+ * Client to bind to. Defaults to the injected `LUNORA_CLIENT`; pass one
774
+ * explicitly to use `liveQuery` outside an injection context (or in a test).
775
+ */
76
776
  client?: LunoraClient;
77
777
  /**
78
- * `DestroyRef` whose `onDestroy` tears the subscription down. Defaults to
79
- * `inject(DestroyRef)` — the calling component/service — so it closes when that
80
- * component is destroyed. Pass one explicitly to control the lifetime yourself.
81
- */
778
+ * `DestroyRef` whose `onDestroy` tears the subscription down. Defaults to
779
+ * `inject(DestroyRef)` — the calling component/service — so it closes when that
780
+ * component is destroyed. Pass one explicitly to control the lifetime yourself.
781
+ */
82
782
  destroyRef?: DestroyRef;
83
783
  /**
84
- * Called when the subscription errors after the initial attach — the async
85
- * error channel `createQuerySubscription` only wires when a sink is present.
86
- * Without it, a post-attach failure is dropped silently: the signal simply
87
- * stops updating with no error state exposed. Pass a handler to surface it
88
- * (log, toast, set an error signal of your own).
89
- */
784
+ * `Injector` to create the reactive-args `effect()` from. Only needed when
785
+ * `args` is a function/`Signal` AND `liveQuery` is called outside an injection
786
+ * context (an explicit `destroyRef` is also being passed — e.g. from
787
+ * `ngOnInit`, or from a test with no `TestBed`) — `effect()` cannot resolve an
788
+ * injector on its own there. Defaults to the ambient injection context, the
789
+ * same source `inject(DestroyRef)` already relies on. Unused for the static
790
+ * `args` form, which never creates an `effect()`.
791
+ */
792
+ injector?: Injector;
793
+ /**
794
+ * Called when the subscription errors after the initial attach — the async
795
+ * error channel `createQuerySubscription` only wires when a sink is present.
796
+ * Without it, a post-attach failure is dropped silently: the signal simply
797
+ * stops updating with no error state exposed. Pass a handler to surface it
798
+ * (log, toast, set an error signal of your own).
799
+ */
90
800
  onError?: (error: SubscriptionError) => void;
91
801
  /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
92
802
  shardKey?: string;
93
803
  }
94
804
  /**
95
- * Subscribe to a server query and mirror its value into an Angular `signal`.
96
- *
97
- * Reads `undefined` until the first server frame lands, then updates on every
98
- * delta the WebSocket pushes. The underlying subscription is torn down
99
- * automatically when the owning `DestroyRef` fires (the component/service is
100
- * destroyed), so there is no leaked socket subscription.
101
- *
102
- * Call it from an injection context (a component/service field initializer or
103
- * constructor) so the default `inject(DestroyRef)` resolves the caller's
104
- * lifetime:
105
- *
106
- * ```ts
107
- * export class MessagesComponent {
108
- * readonly messages = liveQuery(api.messages.list, { channelId: "general" });
109
- * }
110
- * ```
111
- *
112
- * Pass `"skip"` (the `SKIP` sentinel from `@lunora/client/query`) as `args` to
113
- * short-circuit — no network call, no socket; the signal stays `undefined`. To
114
- * call outside an injection context (e.g. lazily in `ngOnInit`), supply `client`
115
- * and `destroyRef` via {@link LiveQueryOptions}.
116
- */
117
- declare const liveQuery: <F extends FunctionReference>(reference: F, args: ArgsOf<F> | "skip", options?: LiveQueryOptions) => Signal<ReturnOf<F> | undefined>;
805
+ * Subscribe to a server query and mirror its value into an Angular `signal`.
806
+ *
807
+ * Reads `undefined` until the first server frame lands, then updates on every
808
+ * delta the WebSocket pushes. The underlying subscription is torn down
809
+ * automatically when the owning `DestroyRef` fires (the component/service is
810
+ * destroyed), so there is no leaked socket subscription.
811
+ *
812
+ * Call it from an injection context (a component/service field initializer or
813
+ * constructor) so the default `inject(DestroyRef)` resolves the caller's
814
+ * lifetime:
815
+ *
816
+ * ```ts
817
+ * export class MessagesComponent {
818
+ * readonly messages = liveQuery(api.messages.list, { channelId: "general" });
819
+ * }
820
+ * ```
821
+ *
822
+ * Pass `"skip"` (the `SKIP` sentinel from `@lunora/client/query`) as `args` to
823
+ * short-circuit — no network call, no socket; the signal stays `undefined`. To
824
+ * call outside an injection context (e.g. lazily in `ngOnInit`), supply `client`
825
+ * and `destroyRef` via {@link LiveQueryOptions}.
826
+ *
827
+ * `args` also accepts a function/`Signal` — `() => ({ channelId: channelId() })`
828
+ * — to make the subscription reactive: an args change tears the old
829
+ * subscription down, resets the signal to `undefined`, and opens a fresh one
830
+ * for the new args, mirroring
831
+ * `@lunora/solid`'s `createQuery`/`@lunora/vue`'s `useQuery`. A static (plain
832
+ * object) `args` resolves once and never re-runs — no `effect()` is created for
833
+ * it, so it carries none of the reactive form's DI requirement.
834
+ * @experimental
835
+ */
836
+ declare const liveQuery: <F extends FunctionReference>(reference: F, args: ArgsOf<F> | "skip" | (() => ArgsOf<F> | "skip"), options?: LiveQueryOptions) => Signal<ReturnOf<F> | undefined>;
837
+ /**
838
+ * `MutateOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
839
+ * @experimental
840
+ */
118
841
  interface MutateOptions<F extends FunctionReference> extends MutationCallOptions<unknown, unknown, ArgsOf<F>> {
119
842
  /**
120
- * Client to run the mutation on. Defaults to the injected `LUNORA_CLIENT`.
121
- * Because mutations usually fire from event handlers — which run *outside* an
122
- * injection context — capture the client once (`injectLunoraClient()` in a
123
- * field) and pass it here, or call `client.mutation(...)` directly.
124
- */
125
- client?: LunoraClient;
126
- }
127
- /**
128
- * Run a Lunora mutation and resolve with the server result (rejects on failure).
129
- *
130
- * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
131
- * call options pass straight through to `client.mutation`, which applies and
132
- * rolls them back against the live subscription cache — the same cache
133
- * `liveQuery` reads, so an optimistic write reflects immediately and
134
- * reverts on failure. The client's offline queue also engages when the socket is
135
- * down, so the write stays durable across reconnects.
136
- *
137
- * ```ts
138
- * private readonly client = injectLunoraClient();
139
- * send = (text: string) => mutate(api.messages.send, { text }, { client: this.client });
140
- * ```
141
- *
142
- * When called from within an injection context you may omit `client` and let it
143
- * resolve from the injector.
144
- */
843
+ * Client to run the mutation on. Defaults to the injected `LUNORA_CLIENT`.
844
+ * Because mutations usually fire from event handlers — which run *outside* an
845
+ * injection context — capture the client once (`injectLunoraClient()` in a
846
+ * field) and pass it here, or call `client.mutation(...)` directly.
847
+ */
848
+ client?: LunoraClient;
849
+ }
850
+ /**
851
+ * Run a Lunora mutation and resolve with the server result (rejects on failure).
852
+ *
853
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
854
+ * call options pass straight through to `client.mutation`, which applies and
855
+ * rolls them back against the live subscription cache — the same cache
856
+ * `liveQuery` reads, so an optimistic write reflects immediately and
857
+ * reverts on failure. The client's offline queue also engages when the socket is
858
+ * down, so the write stays durable across reconnects.
859
+ *
860
+ * ```ts
861
+ * private readonly client = injectLunoraClient();
862
+ * send = (text: string) => mutate(api.messages.send, { text }, { client: this.client });
863
+ * ```
864
+ *
865
+ * When called from within an injection context you may omit `client` and let it
866
+ * resolve from the injector.
867
+ * @experimental
868
+ */
145
869
  declare const mutate: <F extends FunctionReference>(reference: F, args: ArgsOf<F>, options?: MutateOptions<F>) => Promise<ReturnOf<F>>;
146
- export { type ConnectionStatusOptions, LUNORA_CLIENT, type LiveQueryOptions, type MutateOptions, type ProvideLunoraOptions, connectionStatus, injectLunoraClient, liveQuery, mutate, provideLunora };
870
+ /**
871
+ * `MutatorResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
872
+ * @experimental
873
+ */
874
+ interface MutatorResult<TArgs> {
875
+ /** The latest invocation's error, or `undefined`. */
876
+ error: Signal<Error | undefined>;
877
+ /** `true` when the latest invocation rejected. */
878
+ isError: Signal<boolean>;
879
+ /** Run the mutator; resolves once the write is persisted, rejects on failure. */
880
+ mutate: (args: TArgs) => Promise<void>;
881
+ /** `true` while ANY invocation from this handle is in flight. */
882
+ pending: Signal<boolean>;
883
+ /** Clear the latest `error` back to idle. */
884
+ reset: () => void;
885
+ }
886
+ /**
887
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
888
+ * custom-mutator handle from `` `@lunora/db` ``'s `bindMutators` — the Angular
889
+ * equivalent of `` `@lunora/react` ``'s `useMutator`. The optimistic overlay and
890
+ * server-authoritative push are owned by the bound handle; this function only
891
+ * surfaces reactive state for the in-flight/error lifecycle.
892
+ *
893
+ * `pending` is ref-counted across overlapping invocations of THIS handle, so it
894
+ * clears only once every concurrent call has settled.
895
+ *
896
+ * Does NOT require an injection context — it works with plain signals.
897
+ *
898
+ * ```ts
899
+ * private readonly collection = bindMutators(collections);
900
+ * readonly mutator = mutator(this.collection.insert);
901
+ * ```
902
+ * @experimental
903
+ */
904
+ declare const mutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorResult<TArgs>;
905
+ /** The args a paginated query exposes minus the framework-supplied page cursor. */
906
+ type PaginatedArgs<F extends FunctionReference> = Omit<ArgsOfRaw<F>, "paginationOpts">;
907
+ /** The element type of the `page` array a paginated query returns. */
908
+ type PageItemOf<F extends FunctionReference> = ReturnTypeOf<F> extends {
909
+ page: (infer T)[];
910
+ } ? T : unknown;
911
+ type ArgsOfRaw<F extends FunctionReference> = F extends FunctionReference<"query", infer A> ? A : never;
912
+ type ReturnTypeOf<F extends FunctionReference> = F extends FunctionReference<"query", unknown, infer R> ? R : never;
913
+ /**
914
+ * Options for the paginated query — part of the experimental `@lunora/angular` API and may change without a major version bump.
915
+ * @experimental
916
+ */
917
+ interface PaginatedQueryOptions {
918
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
919
+ client?: LunoraClient;
920
+ /** `DestroyRef` whose `onDestroy` tears down the subscriptions. Defaults to `inject(DestroyRef)`. */
921
+ destroyRef?: DestroyRef;
922
+ /** Page size for the first page (and the default for `loadMore`). */
923
+ initialNumItems: number;
924
+ /**
925
+ * `Injector` to create the reactive-args `effect()` from. Only needed when
926
+ * `args` is a function/`Signal` AND the call is outside an injection context
927
+ * (an explicit `destroyRef` is also being passed). Defaults to the ambient
928
+ * injection context. Unused for the static `args` form.
929
+ */
930
+ injector?: Injector;
931
+ /** Called when a page subscription reports an error (also surfaced on the `error` signal). */
932
+ onError?: SubscriptionErrorCallback;
933
+ /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
934
+ shardKey?: string;
935
+ }
936
+ /**
937
+ * `PaginatedQueryResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
938
+ * @experimental
939
+ */
940
+ interface PaginatedQueryResult<T> {
941
+ /**
942
+ * The last page subscription error, or `undefined`. A tail page that fails
943
+ * before its first frame is dropped so `status` returns to `"CanLoadMore"`
944
+ * and `loadMore` can retry it; cleared by the next successful frame,
945
+ * `loadMore`, or an args change.
946
+ */
947
+ error: Signal<SubscriptionError | undefined>;
948
+ /** `true` while the first page or a `loadMore` page is in flight. */
949
+ isLoading: Signal<boolean>;
950
+ /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
951
+ loadMore: (numberItems: number) => void;
952
+ /** Flattened items across every loaded page, in order. */
953
+ results: Signal<T[]>;
954
+ /** The pagination status. */
955
+ status: Signal<PaginationStatus>;
956
+ }
957
+ /**
958
+ * `InfiniteQueryResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
959
+ * @experimental
960
+ */
961
+ interface InfiniteQueryResult<T> {
962
+ /** The last page subscription error, or `undefined` — see `PaginatedQueryResult.error`. */
963
+ error: Signal<SubscriptionError | undefined>;
964
+ /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
965
+ fetchNextPage: (numberItems?: number) => void;
966
+ /** `true` when the loaded tail reports it can load another page. */
967
+ hasNextPage: Signal<boolean>;
968
+ /** `true` while a `fetchNextPage` page (beyond the first) is in flight. */
969
+ isFetchingNextPage: Signal<boolean>;
970
+ /** `true` while the first page is in flight. */
971
+ isLoading: Signal<boolean>;
972
+ /** One inner array per loaded page, in order; unresolved pages are omitted. */
973
+ pages: Signal<T[][]>;
974
+ /** The pagination status. */
975
+ status: Signal<PaginationStatus>;
976
+ }
977
+ /**
978
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
979
+ *
980
+ * The query function must accept a `paginationOpts: { numItems, cursor,
981
+ * endCursor }` arg and return a `PaginationResult`. Pages are tracked as an
982
+ * ordered list of stable boundary cursors; each loaded page is a live
983
+ * subscription over a FIXED `(lower, upper]` range.
984
+ *
985
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
986
+ * it is a no-op unless `status === "CanLoadMore"`.
987
+ *
988
+ * Call from an injection context:
989
+ * ```ts
990
+ * readonly messages = paginatedQuery(api.messages.list, {}, { initialNumItems: 20 });
991
+ * ```
992
+ *
993
+ * `args` also accepts a function/`Signal` to make the query reactive — an args
994
+ * change disposes the current pagination engine and builds a fresh one for the
995
+ * new args. A static (plain object) `args` resolves once and never re-runs.
996
+ * @experimental
997
+ */
998
+ declare const paginatedQuery: <F extends FunctionReference>(reference: F, args: PaginatedArgs<F> | "skip" | (() => PaginatedArgs<F> | "skip"), options: PaginatedQueryOptions) => PaginatedQueryResult<PageItemOf<F>>;
999
+ /**
1000
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
1001
+ *
1002
+ * Shares `paginatedQuery`'s reactive-pagination engine but keeps each page as
1003
+ * its own inner array rather than flattening them, and adds the TanStack-Query-
1004
+ * style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage` shape.
1005
+ *
1006
+ * Call from an injection context:
1007
+ * ```ts
1008
+ * readonly feed = infiniteQuery(api.messages.list, {}, { initialNumItems: 20 });
1009
+ * ```
1010
+ *
1011
+ * `args` also accepts a function/`Signal` to make the query reactive — see
1012
+ * `paginatedQuery`'s equivalent note.
1013
+ * @experimental
1014
+ */
1015
+ declare const infiniteQuery: <F extends FunctionReference>(reference: F, args: PaginatedArgs<F> | "skip" | (() => PaginatedArgs<F> | "skip"), options: PaginatedQueryOptions) => InfiniteQueryResult<PageItemOf<F>>;
1016
+ /**
1017
+ * `HeartbeatReference` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1018
+ * @experimental
1019
+ */
1020
+ type HeartbeatReference = FunctionReference<"mutation", {
1021
+ data?: Record<string, unknown>;
1022
+ roomId: string;
1023
+ sessionId: string;
1024
+ }>;
1025
+ /**
1026
+ * `ListPresentReference` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1027
+ * @experimental
1028
+ */
1029
+ type ListPresentReference = FunctionReference<"query", {
1030
+ roomId: string;
1031
+ }>;
1032
+ /**
1033
+ * `PresenceOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1034
+ * @experimental
1035
+ */
1036
+ interface PresenceOptions<H extends HeartbeatReference, L extends ListPresentReference> {
1037
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
1038
+ client?: LunoraClient;
1039
+ /** Awareness blob for the first heartbeat (selection, cursor, name, color…). */
1040
+ data?: Record<string, unknown>;
1041
+ /** `DestroyRef` whose `onDestroy` cleans up. Defaults to `inject(DestroyRef)`. */
1042
+ destroyRef?: DestroyRef;
1043
+ /** The `api.*` reference for the presence heartbeat mutation. */
1044
+ heartbeat: H;
1045
+ /** Heartbeat cadence in ms. Defaults to 10s (10000). */
1046
+ intervalMs?: number;
1047
+ /** The `api.*` reference for the presence listPresent query. */
1048
+ listPresent: L;
1049
+ /**
1050
+ * Called when the `listPresent` subscription reports an error (a session
1051
+ * expiry, an RLS denial). Without it — and without reading `error` — such a
1052
+ * failure is invisible and `present` is cleared until a later frame arrives.
1053
+ */
1054
+ onError?: SubscriptionErrorCallback;
1055
+ /**
1056
+ * Stable id for this presence row. Defaults to a fresh per-call id.
1057
+ * Pass a user/connection id to control deduping across tabs.
1058
+ */
1059
+ sessionId?: string;
1060
+ /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
1061
+ shardKey?: string;
1062
+ }
1063
+ /**
1064
+ * `PresenceResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1065
+ * @experimental
1066
+ */
1067
+ interface PresenceResult<L extends ListPresentReference> {
1068
+ /** The `listPresent` subscription's last error, or `undefined`. */
1069
+ error: Signal<SubscriptionError | undefined>;
1070
+ /** The present members for the room. `undefined` until the first push. */
1071
+ present: Signal<ReturnOf<L> | undefined>;
1072
+ /** This mount's session id (generated when not supplied). */
1073
+ sessionId: string;
1074
+ /** Replace the awareness `data` sent with subsequent heartbeats, and heartbeat immediately. */
1075
+ setData: (data: Record<string, unknown> | undefined) => void;
1076
+ }
1077
+ /**
1078
+ * `presence` — collaborative-awareness primitive, the client half of the
1079
+ * `@lunora/server` `definePresence` preset.
1080
+ *
1081
+ * Drives the heartbeat mutation (on mount, interval, and tab re-focus) and
1082
+ * subscribes to the live `listPresent` query for the given room.
1083
+ *
1084
+ * Call from an injection context (component/service field or constructor):
1085
+ * ```ts
1086
+ * readonly roomPresence = presence("room:general", {
1087
+ * heartbeat: api.presence.heartbeat,
1088
+ * listPresent: api.presence.listPresent,
1089
+ * });
1090
+ * ```
1091
+ * @experimental
1092
+ */
1093
+ declare const presence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: PresenceOptions<H, L>) => PresenceResult<L>;
1094
+ /**
1095
+ * `RateLimitOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1096
+ * @experimental
1097
+ */
1098
+ interface RateLimitOptions {
1099
+ /**
1100
+ * `DestroyRef` whose `onDestroy` clears the interval. Defaults to
1101
+ * `inject(DestroyRef)` — the calling component/service.
1102
+ */
1103
+ destroyRef?: DestroyRef;
1104
+ /** Clock injection for tests. Defaults to `Date.now`. */
1105
+ now?: () => number;
1106
+ /**
1107
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
1108
+ * down and `disabled` flips back automatically. Defaults to `1000`.
1109
+ */
1110
+ tickMs?: number;
1111
+ }
1112
+ /**
1113
+ * `RateLimitResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1114
+ * @experimental
1115
+ */
1116
+ interface RateLimitResult {
1117
+ /** Would consuming `count` (default 1) succeed right now? Does not consume. */
1118
+ check: (count?: number) => boolean;
1119
+ /** Optimistically consume `count` (default 1) locally; mirrors the server algorithm. */
1120
+ consume: (count?: number) => RateLimitStatus;
1121
+ /** `true` while a single unit cannot be consumed — convenient for disabling a control. */
1122
+ disabled: Signal<boolean>;
1123
+ /** `true` while a single unit can be consumed. */
1124
+ ok: Signal<boolean>;
1125
+ /** Clear local accounting (e.g. after the server confirms a reset). */
1126
+ reset: () => void;
1127
+ /** Milliseconds until the next unit is available. `0` when `ok`. */
1128
+ retryAfter: Signal<number>;
1129
+ }
1130
+ /**
1131
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
1132
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
1133
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
1134
+ * authoritative check; the server remains the source of truth.
1135
+ *
1136
+ * Requires an Angular injection context unless a `DestroyRef` is passed
1137
+ * explicitly via `options.destroyRef`.
1138
+ *
1139
+ * ```ts
1140
+ * readonly sendLimit = rateLimit({ kind: "token bucket", period: 1000, rate: 10 });
1141
+ * ```
1142
+ * @experimental
1143
+ */
1144
+ declare const rateLimit: (config: RateLimitConfig, options?: RateLimitOptions) => RateLimitResult;
1145
+ /**
1146
+ * `RunActionOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1147
+ * @experimental
1148
+ */
1149
+ interface RunActionOptions extends ActionCallOptions {
1150
+ /**
1151
+ * Client to run the action on. Defaults to the injected `LUNORA_CLIENT`.
1152
+ * Because actions usually fire from event handlers — which run *outside* an
1153
+ * injection context — capture the client once (`injectLunoraClient()` in a
1154
+ * field) and pass it here, or call `client.action(...)` directly.
1155
+ */
1156
+ client?: LunoraClient;
1157
+ }
1158
+ /**
1159
+ * Run a Lunora action and resolve with the server result (rejects on failure).
1160
+ *
1161
+ * The sibling of `mutate`, and a plain function for the same reason: Angular's
1162
+ * adapter models writes as calls rather than reactive handles, because they fire
1163
+ * from event handlers where a signal-returning primitive has nothing to bind to.
1164
+ * The other adapters return a reactive `{ call, pending, … }` handle because
1165
+ * their idioms make that natural; this one does not.
1166
+ *
1167
+ * Unlike `mutate` there are no `optimistic` / `optimisticUpdate` options. An
1168
+ * optimistic update patches the subscription cache on the assumption a write
1169
+ * will land; an action is not a write — it runs in the Worker, may call a third
1170
+ * party, and has no declared effect on any query.
1171
+ *
1172
+ * ```ts
1173
+ * private readonly client = injectLunoraClient();
1174
+ * verify = () => runAction(api.commands.run, { command: "lunora", args: ["verify"] }, { client: this.client });
1175
+ * ```
1176
+ *
1177
+ * When called from within an injection context you may omit `client` and let it
1178
+ * resolve from the injector.
1179
+ * @experimental
1180
+ */
1181
+ declare const runAction: <F extends FunctionReference>(reference: F, args: ArgsOf<F>, options?: RunActionOptions) => Promise<ReturnOf<F>>;
1182
+ /**
1183
+ * The lifecycle of a stream the primitive is observing.
1184
+ * @experimental
1185
+ */
1186
+ type StreamStatus = "complete" | "error" | "idle" | "streaming";
1187
+ /**
1188
+ * `StreamOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1189
+ * @experimental
1190
+ */
1191
+ interface StreamOptions {
1192
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
1193
+ client?: LunoraClient;
1194
+ /**
1195
+ * `DestroyRef` whose `onDestroy` cancels the stream. Defaults to
1196
+ * `inject(DestroyRef)` — the calling component/service.
1197
+ */
1198
+ destroyRef?: DestroyRef;
1199
+ /**
1200
+ * Opt into resume-on-reconnect for a stream the server declared `durable`.
1201
+ * The chunks already received are kept and the socket re-attaches to the same
1202
+ * run, so a dropped connection mid-generation continues instead of surfacing
1203
+ * `STREAM_DISCONNECTED`. Has no effect on an ephemeral stream.
1204
+ */
1205
+ durable?: boolean;
1206
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
1207
+ maxBuffer?: number;
1208
+ /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
1209
+ shardKey?: string;
1210
+ }
1211
+ /**
1212
+ * `StreamResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1213
+ * @experimental
1214
+ */
1215
+ interface StreamResult<T> {
1216
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
1217
+ cancel: () => void;
1218
+ /** Chunks the server has pushed so far, in arrival order. */
1219
+ chunks: Signal<ReadonlyArray<T>>;
1220
+ /** The stream error, or `undefined`. */
1221
+ error: Signal<Error | undefined>;
1222
+ /** The stream lifecycle. */
1223
+ status: Signal<StreamStatus>;
1224
+ }
1225
+ /**
1226
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
1227
+ * lifecycle status and a `cancel` function, all as signals.
1228
+ *
1229
+ * Unlike `subscription`, which tracks the latest value, `stream` accumulates every
1230
+ * chunk the server pushes — use it for token-by-token deltas and other append-only
1231
+ * feeds. Pass `"skip"` as `args` to keep the primitive mounted without opening a
1232
+ * stream (mirrors `subscription`); the stream tears down when the owning
1233
+ * `DestroyRef` fires. Nothing opens on the Angular server platform (SSR). The
1234
+ * Angular counterpart to React's `useStream`, re-expressed with signals.
1235
+ *
1236
+ * Call from an injection context (component/service field or constructor):
1237
+ * ```ts
1238
+ * readonly tokens = stream(api.chat.liveEvents, { key: "thread-1" });
1239
+ * ```
1240
+ * @experimental
1241
+ */
1242
+ declare const stream: <F extends FunctionReference<"stream">>(reference: F, args: ArgsOf<F> | "skip", options?: StreamOptions) => StreamResult<ReturnOf<F>>;
1243
+ /**
1244
+ * `SubscriptionOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1245
+ * @experimental
1246
+ */
1247
+ interface SubscriptionOptions {
1248
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
1249
+ client?: LunoraClient;
1250
+ /**
1251
+ * `DestroyRef` whose `onDestroy` tears the subscription down. Defaults to
1252
+ * `inject(DestroyRef)` — the calling component/service.
1253
+ */
1254
+ destroyRef?: DestroyRef;
1255
+ /**
1256
+ * `Injector` to create the reactive-args `effect()` from. Only needed when
1257
+ * `args` is a function/`Signal` AND `subscription` is called outside an
1258
+ * injection context (an explicit `destroyRef` is also being passed).
1259
+ * Defaults to the ambient injection context. Unused for the static `args`
1260
+ * form, which never creates an `effect()`.
1261
+ */
1262
+ injector?: Injector;
1263
+ /**
1264
+ * Called when the subscription errors after the initial attach. Without it,
1265
+ * a post-attach failure is dropped silently.
1266
+ */
1267
+ onError?: (error: SubscriptionError) => void;
1268
+ /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
1269
+ shardKey?: string;
1270
+ }
1271
+ /**
1272
+ * `SubscriptionResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1273
+ * @experimental
1274
+ */
1275
+ interface SubscriptionResult<T> {
1276
+ /** The latest value pushed by the server. `undefined` before the first frame. */
1277
+ data: Signal<T | undefined>;
1278
+ /** The latest error, or `undefined`. */
1279
+ error: Signal<SubscriptionError | undefined>;
1280
+ }
1281
+ /**
1282
+ * Subscribe to a reactive server push stream. Returns `{ data, error }` signals
1283
+ * that update whenever the server emits a new value.
1284
+ *
1285
+ * Unlike `liveQuery`, which tracks a single value, `subscription` also
1286
+ * exposes an `error` signal for the async error channel. Use it for ephemeral,
1287
+ * high-frequency streams where you need error visibility.
1288
+ *
1289
+ * Pass `"skip"` as `args` to short-circuit — no network call, no socket.
1290
+ * The subscription tears down when the owning `DestroyRef` fires.
1291
+ *
1292
+ * Call from an injection context (component/service field or constructor):
1293
+ * ```ts
1294
+ * readonly stream = subscription(api.events.stream, { roomId: "general" });
1295
+ * ```
1296
+ *
1297
+ * `args` also accepts a function/`Signal` to make the subscription reactive —
1298
+ * an args change tears the old subscription down and opens a fresh one for the
1299
+ * new args. A static (plain object) `args` resolves once and never re-runs.
1300
+ * @experimental
1301
+ */
1302
+ declare const subscription: <F extends FunctionReference>(reference: F, args: ArgsOf<F> | "skip" | (() => ArgsOf<F> | "skip"), options?: SubscriptionOptions) => SubscriptionResult<ReturnOf<F>>;
1303
+ /**
1304
+ * Browser Web Audio subsystems for `voiceAgent` — the default microphone capture
1305
+ * and speaker playback implementations injected into the primitive via its
1306
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
1307
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
1308
+ * primitive's transport + signal-state logic and remains mockable in a
1309
+ * non-browser test env.
1310
+ */
1311
+ /**
1312
+ * The negotiated audio format the voice DO streams back. Mirrors
1313
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
1314
+ * imported) so this Angular package never pulls in the server-only `@lunora/agent`
1315
+ * module graph.
1316
+ * @experimental
1317
+ */
1318
+ type VoiceAudioFormat = "mp3" | "wav";
1319
+ /** Captures microphone audio and reports level / turn boundaries back to the primitive. */
1320
+ interface VoiceMicrophone {
1321
+ /** Mute/unmute the mic without tearing down the capture graph. */
1322
+ setMuted: (muted: boolean) => void;
1323
+ /** Stop capture and release the media stream + audio graph. */
1324
+ stop: () => void;
1325
+ }
1326
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1327
+ interface VoiceSpeaker {
1328
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1329
+ enqueue: (audio: Uint8Array) => void;
1330
+ /** Drop everything queued and stop the current chunk (barge-in). */
1331
+ interrupt: () => void;
1332
+ /** Release the playback audio context. */
1333
+ stop: () => void;
1334
+ }
1335
+ /** Config passed to a {@link CreateMicrophone} factory. */
1336
+ interface MicrophoneConfig {
1337
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1338
+ interruptChunks: number;
1339
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1340
+ interruptThreshold: number;
1341
+ /**
1342
+ * `true` from the moment a turn is committed until it completes — the whole
1343
+ * `thinking` + `speaking` window, not just the audible half.
1344
+ *
1345
+ * It gates BOTH branches below, and the wider span is the point. Gated only
1346
+ * on "audibly speaking", turn detection kept running through the entire
1347
+ * STT+LLM window after a `commit`: room noise at the (deliberately low)
1348
+ * `silenceThreshold` re-armed `sawSpeech`, another quiet gap fired a SECOND
1349
+ * `commit`, and the DO refused it with "a turn is already in progress" —
1350
+ * a refusal that returns before draining the audio buffer, so the PCM
1351
+ * captured since the first commit leaked into the next utterance.
1352
+ *
1353
+ * A genuine barge-in still works in that window: it routes through the
1354
+ * `onInterrupt` branch, which needs `interruptChunks` consecutive chunks at
1355
+ * `interruptThreshold` — an order of magnitude above `silenceThreshold` —
1356
+ * and `interrupt` is exactly what the DO tells the client to send.
1357
+ */
1358
+ isTurnActive: () => boolean;
1359
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1360
+ onAudio: (pcm: Uint8Array) => void;
1361
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1362
+ onInterrupt: () => void;
1363
+ /** The current input RMS (0–1), for a level meter. */
1364
+ onLevel: (rms: number) => void;
1365
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1366
+ onSilence: () => void;
1367
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1368
+ silenceDurationMs: number;
1369
+ /** RMS below which audio counts as silence. */
1370
+ silenceThreshold: number;
1371
+ }
1372
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1373
+ type CreateSpeaker = (config: {
1374
+ audioFormat: VoiceAudioFormat;
1375
+ }) => VoiceSpeaker;
1376
+ /**
1377
+ * The `agents.<name>Voice` reference codegen emits for a voice-enabled agent — a
1378
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1379
+ * generated member, so passing `api.agents.<name>Voice` type-checks.
1380
+ * @experimental
1381
+ */
1382
+ type VoiceReference = FunctionReference<"stream", {
1383
+ threadKey: string;
1384
+ }, Record<string, unknown>>;
1385
+ /**
1386
+ * The lifecycle of a voice call, mirrored to the UI.
1387
+ * @experimental
1388
+ */
1389
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1390
+ /** A minimal structural subset of the DOM `WebSocket` the primitive drives. */
1391
+ interface VoiceSocket {
1392
+ binaryType: string;
1393
+ close: () => void;
1394
+ onclose: ((event: unknown) => void) | null;
1395
+ onerror: ((event: unknown) => void) | null;
1396
+ onmessage: ((event: {
1397
+ data: unknown;
1398
+ }) => void) | null;
1399
+ onopen: ((event: unknown) => void) | null;
1400
+ readonly readyState: number;
1401
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1402
+ }
1403
+ type CreateSocket = (url: string) => VoiceSocket;
1404
+ /**
1405
+ * `VoiceAgentOptions` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1406
+ * @experimental
1407
+ */
1408
+ interface VoiceAgentOptions {
1409
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
1410
+ client?: LunoraClient;
1411
+ /**
1412
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1413
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1414
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1415
+ */
1416
+ createMicrophone?: CreateMicrophone;
1417
+ /**
1418
+ * Advanced/test seam: open the transport. Defaults to the WebSocket
1419
+ * implementation the client was built with (`client.getWebSocketImpl()`),
1420
+ * NOT a raw `globalThis.WebSocket`.
1421
+ */
1422
+ createSocket?: CreateSocket;
1423
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1424
+ createSpeaker?: CreateSpeaker;
1425
+ /**
1426
+ * `DestroyRef` whose `onDestroy` tears the call down. Defaults to
1427
+ * `inject(DestroyRef)` — the calling component/service.
1428
+ */
1429
+ destroyRef?: DestroyRef;
1430
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1431
+ interruptChunks?: number;
1432
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1433
+ interruptThreshold?: number;
1434
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1435
+ silenceDurationMs?: number;
1436
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1437
+ silenceThreshold?: number;
1438
+ /**
1439
+ * The thread to converse on — shared with the agent's text turns. A plain
1440
+ * value, or a `Signal`/getter resolved afresh every time a call opens — the
1441
+ * reactive-args form the package's other primitives take.
1442
+ */
1443
+ threadKey: (() => string) | string;
1444
+ /** The generated `api.agents.<name>Voice` reference — identifies the voice DO endpoint. */
1445
+ voice: VoiceReference;
1446
+ }
1447
+ /**
1448
+ * `VoiceAgentResult` is part of the experimental `@lunora/angular` API and may change without a major version bump.
1449
+ * @experimental
1450
+ */
1451
+ interface VoiceAgentResult {
1452
+ /** The current input RMS (0–1) — drive a mic level meter. */
1453
+ audioLevel: Signal<number>;
1454
+ /** `true` once the WS `ready` handshake completed. */
1455
+ connected: Signal<boolean>;
1456
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1457
+ endCall: () => void;
1458
+ /** The last transport/pipeline error, or `undefined`. */
1459
+ error: Signal<Error | undefined>;
1460
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1461
+ interimTranscript: Signal<string>;
1462
+ /** `true` while the mic is muted. */
1463
+ isMuted: Signal<boolean>;
1464
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1465
+ sendText: (text: string) => void;
1466
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1467
+ startCall: () => Promise<void>;
1468
+ /** The current call lifecycle. */
1469
+ status: Signal<VoiceStatus>;
1470
+ /** Mute/unmute the microphone. Returns the new muted state. */
1471
+ toggleMute: () => boolean;
1472
+ /** The last finalized user utterance (STT result). */
1473
+ transcript: Signal<string>;
1474
+ }
1475
+ /**
1476
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1477
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1478
+ * streams the agent's synthesized speech back through the browser's audio output,
1479
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1480
+ * `audioLevel`) to Angular signals. Pass the generated `api.agents.<name>Voice`
1481
+ * reference (never a string), matching `agentChat`'s reference-passing style. The
1482
+ * Angular counterpart to React's `useVoiceAgent`, re-expressed with signals; the
1483
+ * per-call connection lives in a closure variable (the primitive runs once per
1484
+ * component, so no signal-of-connection indirection is needed).
1485
+ *
1486
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1487
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1488
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1489
+ * `createSocket`) so the primitive is drivable outside a browser.
1490
+ *
1491
+ * Call from an injection context (component/service field or constructor); pass an
1492
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
1493
+ * @experimental
1494
+ */
1495
+ declare const voiceAgent: (options: VoiceAgentOptions) => VoiceAgentResult;
1496
+ export { type AgentApi, type AgentChatApi, type AgentChatMessage, type AgentChatOptions, type AgentChatResult, type AgentLiveEvent, type AgentOptions, type AgentProgressEvent, type AgentResult, type AgentStateApi, type AgentStateOptions, type AgentStateResult, type AgentThreadRecord, type AgentThreadStatus, type AgentTokenDelta, type AgentTokenStreamReference, type AgentToolEvent, type AgentToolEventsApi, type AgentToolEventsOptions, type AgentToolEventsResult, type AuthGateResult, type AuthOptions, type AuthResult, type ConnectionStatusOptions, type FlagOptions, type FlagValue, type FlagsOptions, type HeartbeatReference, type HydratePreloadedOptions, type HydratePreloadedResult, type InfiniteQueryResult, LUNORA_CLIENT, type ListPresentReference, type LiveQueryOptions, type MutateOptions, type MutatorResult, type PaginatedQueryOptions, type PaginatedQueryResult, type PresenceOptions, type PresenceResult,
1497
+ /**
1498
+ * The Angular adapter for Lunora.
1499
+ *
1500
+ * Thin, idiomatic glue over the framework-neutral `@lunora/client`. Angular
1501
+ * signals map directly onto Lunora's per-subscription deltas, so a live query is
1502
+ * just a `signal` the WebSocket writes to.
1503
+ *
1504
+ * `provideLunora` / `LUNORA_CLIENT` / `injectLunoraClient` are the injectable
1505
+ * provider carrying one `LunoraClient` (opens its socket lazily), wired once in the
1506
+ * application config. `liveQuery` is a live-query `signal` that opens a
1507
+ * subscription and updates on every delta, torn down automatically on
1508
+ * `DestroyRef.onDestroy`. `mutate` runs a mutation (optimistic updates + offline
1509
+ * queue pass through to the client). `connectionStatus` is a `signal` of the
1510
+ * aggregate live-socket status.
1511
+ */
1512
+ type ProvideLunoraOptions, type RateLimitOptions, type RateLimitResult, type RunActionOptions, type StreamOptions, type StreamResult, type StreamStatus, type SubscriptionOptions, type SubscriptionResult, type VoiceAgentOptions, type VoiceAgentResult, type VoiceAudioFormat, type VoiceReference, type VoiceStatus, agent, agentChat, agentState, agentToolEvents, auth, authGate, connectionStatus, flag, flags, hydratePreloaded, infiniteQuery, injectLunoraClient, liveQuery, mutate, mutator, paginatedQuery, presence, provideLunora, rateLimit, runAction, stream, subscription, voiceAgent };