@lunora/angular 0.0.1 → 1.0.0-alpha.10

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