@lunora/angular 1.0.0-alpha.6 → 1.0.0-alpha.8

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.
package/dist/index.d.mts CHANGED
@@ -1,9 +1,442 @@
1
1
  import { DestroyRef, Signal, InjectionToken, EnvironmentProviders } from '@angular/core';
2
- import { LunoraClient, User, LunoraClientOptions, ConnectionStatus, SubscriptionError, Preloaded, FunctionReference, ArgsOf, ReturnOf, MutationCallOptions, MutatorHandle } from '@lunora/client';
2
+ import { FunctionReference, LunoraClient, SubscriptionError, User, LunoraClientOptions, ConnectionStatus, Preloaded, ArgsOf, ReturnOf, MutationCallOptions, MutatorHandle } from '@lunora/client';
3
3
  export type { ArgsOf, ConnectionStatus, FunctionReference, LunoraClient, LunoraClientOptions, MutationCallOptions, Preloaded, ReturnOf, SubscriptionError, Unsubscribe } from '@lunora/client';
4
4
  import { PaginationStatus } from '@lunora/client/pagination';
5
5
  import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
6
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
+ */
14
+ type AgentThreadStatus = "awaiting_input" | "cancelled" | "error" | "idle" | "running";
15
+ /**
16
+ * The live thread record surfaced by the `agents:agentThread` query. A structural
17
+ * subset of the persisted thread row — every field beyond `status` is optional so
18
+ * the shape stays forgiving as the server schema grows. Keep in sync with the
19
+ * `agent_threads` table in `packages/agent/src/component.ts`.
20
+ */
21
+ interface AgentThreadRecord {
22
+ createdAt?: number;
23
+ /** The failure message when `status === "error"`. */
24
+ error?: string;
25
+ /** The workflow instance id of the in-flight run — the handle `cancel` targets. */
26
+ instanceId?: string;
27
+ messageCount?: number;
28
+ /** The verified thread owner, when the run was started with one. */
29
+ owner?: string;
30
+ status: AgentThreadStatus;
31
+ title?: string;
32
+ updatedAt?: number;
33
+ }
34
+ /**
35
+ * One persisted (or optimistic) thread message, as `agents:agentMessages`
36
+ * surfaces it. Client-safe mirror of `@lunora/agent`'s `AgentMessageRow` —
37
+ * re-declared here (rather than imported) so this Angular entry never pulls in the
38
+ * server-only `@lunora/agent` module graph. Keep in sync with the
39
+ * `agent_messages` table in `packages/agent/src/component.ts`.
40
+ */
41
+ interface AgentChatMessage {
42
+ content: string;
43
+ createdAt?: number;
44
+ /**
45
+ * `true` for a client-side optimistic user message not yet acknowledged by
46
+ * the server. Cleared once the durable history carries the matching user turn.
47
+ */
48
+ optimistic?: boolean;
49
+ role: "assistant" | "system" | "tool" | "user";
50
+ seq: number;
51
+ /** Approval lifecycle marker on a human-in-the-loop tool message. */
52
+ status?: "approved" | "awaiting_approval" | "rejected";
53
+ toolCallId?: string;
54
+ toolCalls?: ReadonlyArray<{
55
+ id: string;
56
+ input: unknown;
57
+ name: string;
58
+ }>;
59
+ toolName?: string;
60
+ }
61
+ /**
62
+ * A live token delta streamed while a turn is generating. Client-safe mirror of
63
+ * `@lunora/agent`'s `AgentTokenDelta`. Ephemeral — deltas feed the chat surface's
64
+ * streaming text live and are never replayed; the persisted assistant message
65
+ * stays the single source of truth.
66
+ */
67
+ interface AgentTokenDelta {
68
+ /** Discriminates the token arm of {@link AgentLiveEvent}; unset on the wire (token is the default). */
69
+ kind?: "token";
70
+ /** The incremental text chunk the model just produced. */
71
+ text: string;
72
+ /** The thread this delta belongs to. */
73
+ threadKey: string;
74
+ /** The zero-based index of the turn producing the delta. */
75
+ turn: number;
76
+ }
77
+ /**
78
+ * A live tool-progress event streamed via `ctx.reportProgress(...)`. Client-safe
79
+ * mirror of `@lunora/agent`'s `AgentProgressEvent`. Ephemeral and `toolCallId`-keyed;
80
+ * surfaced by `agentToolEvents`, ignored by the chat surface's streaming text.
81
+ */
82
+ interface AgentProgressEvent {
83
+ /** The arbitrary, JSON-serializable payload the tool reported. */
84
+ data: unknown;
85
+ /** Discriminates the progress arm of {@link AgentLiveEvent}. */
86
+ kind: "progress";
87
+ /** The thread this event belongs to. */
88
+ threadKey: string;
89
+ /** The tool call this progress belongs to. */
90
+ toolCallId: string;
91
+ }
92
+ /**
93
+ * A single event on the agent's live-only channel — a streamed token delta or a
94
+ * tool progress event. Client-safe mirror of `@lunora/agent`'s `AgentLiveEvent`.
95
+ * Discriminate on `kind` (`"progress"` for the progress arm; token deltas leave
96
+ * it unset).
97
+ */
98
+ type AgentLiveEvent = AgentProgressEvent | AgentTokenDelta;
99
+ /**
100
+ * The `agents.agentThread` reference the primitive subscribes to for live thread
101
+ * state (status + the in-flight `instanceId`). A structural subset of the
102
+ * generated `api.agents` surface, so the whole generated `api` object is
103
+ * assignable.
104
+ */
105
+ interface AgentApi {
106
+ agents: {
107
+ agentThread: FunctionReference<"query", {
108
+ key: string;
109
+ }, Record<string, unknown> | undefined>;
110
+ };
111
+ }
112
+ interface AgentOptions {
113
+ /** The generated `api` — its `agents.agentThread` query drives live thread state. */
114
+ api: AgentApi;
115
+ /**
116
+ * Optional app mutation over the agent's cancel path
117
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
118
+ * When omitted (or no run is in flight) {@link AgentResult.cancel} is a no-op.
119
+ */
120
+ cancel?: FunctionReference<"mutation">;
121
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
122
+ client?: LunoraClient;
123
+ /**
124
+ * `DestroyRef` whose `onDestroy` tears the live subscription down. Defaults to
125
+ * `inject(DestroyRef)` — the calling component/service.
126
+ */
127
+ destroyRef?: DestroyRef;
128
+ /**
129
+ * The app mutation that starts (or continues) a run — a thin wrapper over
130
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
131
+ * {@link AgentOptions.runArgs} and the per-call args.
132
+ */
133
+ run: FunctionReference<"mutation">;
134
+ /** Extra args merged into every `run` call (e.g. an `owner` or `title`). */
135
+ runArgs?: Record<string, unknown>;
136
+ /** The thread to observe and drive. */
137
+ threadKey: string;
138
+ }
139
+ interface AgentResult {
140
+ /**
141
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
142
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
143
+ */
144
+ cancel: () => Promise<void>;
145
+ /** `true` while a `run` invocation is in flight. */
146
+ pending: Signal<boolean>;
147
+ /** Start (or continue) a run with a user message; extra args merge over `runArgs`. */
148
+ run: (input: string, args?: Record<string, unknown>) => Promise<void>;
149
+ /** The live thread status, or `undefined` before the thread exists. */
150
+ status: Signal<AgentThreadStatus | undefined>;
151
+ /** The live thread record (status, `instanceId`, …), or `undefined` before it exists. */
152
+ thread: Signal<AgentThreadRecord | undefined>;
153
+ }
154
+ /**
155
+ * A thin agent handle: live thread `status` plus `run` / `cancel`, without the
156
+ * chat message surface. Composes `subscription(api.agents.agentThread)` for live
157
+ * state and drives the run/cancel writes straight on the client — the Angular
158
+ * counterpart to React's `useAgent`, re-expressed with signals. For the full
159
+ * conversation surface (durable history + streaming + approvals) use `agentChat`.
160
+ *
161
+ * `run` and `cancel` stay generic over the app-defined mutations that wrap
162
+ * `ctx.agents.&lt;name>.run` / `.cancel`, so the primitive hard-codes no function
163
+ * names beyond the `agents:*` surface.
164
+ *
165
+ * Call from an injection context (component/service field or constructor); pass an
166
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
167
+ */
168
+ declare const agent: (options: AgentOptions) => AgentResult;
169
+ /** The `agents:agentMessages` reference — live durable thread history. */
170
+ type AgentMessagesReference$1 = FunctionReference<"query", {
171
+ key: string;
172
+ limit?: number;
173
+ }, ReadonlyArray<Record<string, unknown>>>;
174
+ /** The `agents:agentResolveApproval` reference — resolves a human-in-the-loop tool approval. */
175
+ type AgentApprovalReference = FunctionReference<"mutation", {
176
+ decision: "approve" | "reject";
177
+ instanceId: string;
178
+ note?: string;
179
+ threadKey: string;
180
+ toolCallId: string;
181
+ }, {
182
+ resolved: boolean;
183
+ }>;
184
+ /** The `agents:agentThread` reference — live thread status + in-flight `instanceId`. */
185
+ type AgentThreadReference = FunctionReference<"query", {
186
+ key: string;
187
+ }, Record<string, unknown> | undefined>;
188
+ /**
189
+ * An app stream reference that tees the agent's in-flight live events, keyed by
190
+ * thread. Carries token deltas and — since `ctx.reportProgress` rides the same
191
+ * sink — tool progress events; this primitive consumes only the token arm.
192
+ */
193
+ type AgentTokenStreamReference = FunctionReference<"stream", {
194
+ key: string;
195
+ }, AgentLiveEvent>;
196
+ /**
197
+ * The `agents.*` reference surface the chat primitive reads. A structural subset
198
+ * of the generated `api.agents`, so the whole generated `api` object is
199
+ * assignable.
200
+ */
201
+ interface AgentChatApi {
202
+ agents: {
203
+ agentMessages: AgentMessagesReference$1;
204
+ agentResolveApproval: AgentApprovalReference;
205
+ agentThread: AgentThreadReference;
206
+ };
207
+ }
208
+ interface AgentChatOptions {
209
+ /** The generated `api` — its `agents.*` surface provides history, thread state, and approval resolution. */
210
+ api: AgentChatApi;
211
+ /**
212
+ * Optional app mutation over the agent's cancel path
213
+ * (`ctx.agents.&lt;name>.cancel(id)`). Called with `{ instanceId, threadKey }`.
214
+ * When omitted (or no run is in flight) {@link AgentChatResult.cancel} is a
215
+ * no-op.
216
+ */
217
+ cancel?: FunctionReference<"mutation">;
218
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
219
+ client?: LunoraClient;
220
+ /**
221
+ * `DestroyRef` whose `onDestroy` tears the subscriptions + stream down. Defaults
222
+ * to `inject(DestroyRef)` — the calling component/service.
223
+ */
224
+ destroyRef?: DestroyRef;
225
+ /** History depth forwarded to `agents:agentMessages`. */
226
+ limit?: number;
227
+ /**
228
+ * The app mutation that starts (or continues) a run — a thin wrapper over
229
+ * `ctx.agents.&lt;name>.run(...)`. Called with `{ threadKey, input }` merged with
230
+ * {@link AgentChatOptions.sendArgs} and the per-call args.
231
+ */
232
+ send: FunctionReference<"mutation">;
233
+ /** Extra args merged into every `send` call (e.g. an `owner` or `title`). */
234
+ sendArgs?: Record<string, unknown>;
235
+ /**
236
+ * Optional live token-delta stream — an app stream function that tees the
237
+ * agent's in-flight deltas. When omitted {@link AgentChatResult.streamingText}
238
+ * stays empty and the UI updates message-by-message from durable history.
239
+ */
240
+ stream?: AgentTokenStreamReference;
241
+ /** The thread to observe and continue. */
242
+ threadKey: string;
243
+ }
244
+ interface AgentChatResult {
245
+ /** Approve a paused human-in-the-loop tool call (optionally with a note). */
246
+ approve: (toolCallId: string, note?: string) => Promise<void>;
247
+ /**
248
+ * Terminate the in-flight run and mark its thread `"cancelled"`. Resolves as a
249
+ * no-op when no `cancel` mutation was supplied or no run is in flight.
250
+ */
251
+ cancel: () => Promise<void>;
252
+ /** Durable thread history (oldest first) plus any un-acknowledged optimistic user turns. */
253
+ messages: Signal<ReadonlyArray<AgentChatMessage>>;
254
+ /** Reject a paused human-in-the-loop tool call (optionally with a reason). */
255
+ reject: (toolCallId: string, note?: string) => Promise<void>;
256
+ /** Start (or continue) a run with a user message; extra args merge over `sendArgs`. Appends an optimistic user turn. */
257
+ send: (input: string, args?: Record<string, unknown>) => Promise<void>;
258
+ /** The live thread status, or `undefined` before the thread exists. */
259
+ status: Signal<AgentThreadStatus | undefined>;
260
+ /** The in-flight turn's streamed text — live-only, empty once the turn persists to `messages`. */
261
+ streamingText: Signal<string>;
262
+ }
263
+ /**
264
+ * A first-class agent chat surface: live durable history + in-flight token
265
+ * streaming + the send / approve / reject / cancel writes, keyed by `threadKey` —
266
+ * the Angular counterpart to React's `useAgentChat`, re-expressed with signals.
267
+ *
268
+ * It composes the existing primitives rather than adding transport:
269
+ * `subscription(api.agents.agentMessages)` for durable history,
270
+ * `subscription(api.agents.agentThread)` for live status + the in-flight
271
+ * `instanceId`, {@link stream} over an app token stream for in-flight deltas, and
272
+ * the client's own `mutation` for the writes (`api.agents.agentResolveApproval` for
273
+ * approvals; app-defined wrappers for `send`/`cancel`). Only the `agents:*` surface
274
+ * is hard-coded — `send`/`cancel`/`stream` stay generic references.
275
+ *
276
+ * A `send` optimistically appends the user turn so it renders immediately; the
277
+ * optimistic row clears once the durable history carries the acknowledged turn.
278
+ * `streamingText` is live-only: it holds the current turn's streamed text and
279
+ * empties as soon as that turn's assistant message lands in `messages` (the
280
+ * persisted message is the source of truth), consistent with the loop's
281
+ * replay-safe, live-only delta design.
282
+ *
283
+ * Call from an injection context (component/service field or constructor); pass an
284
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
285
+ */
286
+ declare const agentChat: (options: AgentChatOptions) => AgentChatResult;
287
+ /**
288
+ * The `agents.agentState` reference the primitive subscribes to for the thread's
289
+ * live synced state. A structural subset of the generated `api.agents` surface
290
+ * (like `AgentApi` for `agentThread`), so the whole generated `api` object is
291
+ * assignable. Client-safe: no `@lunora/agent` import — the per-agent state type is
292
+ * mirrored by the primitive's generic `T`, since codegen pins the reference return
293
+ * as an optional record (it never evaluates agent config).
294
+ */
295
+ interface AgentStateApi {
296
+ agents: {
297
+ agentState: FunctionReference<"query", {
298
+ key: string;
299
+ }, Record<string, unknown> | undefined>;
300
+ };
301
+ }
302
+ interface AgentStateOptions {
303
+ /** The generated `api` — its `agents.agentState` query drives live thread state. */
304
+ api: AgentStateApi;
305
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
306
+ client?: LunoraClient;
307
+ /**
308
+ * `DestroyRef` whose `onDestroy` tears the subscription down. Defaults to
309
+ * `inject(DestroyRef)` — the calling component/service.
310
+ */
311
+ destroyRef?: DestroyRef;
312
+ /** The thread whose synced state to observe. */
313
+ threadKey: string;
314
+ }
315
+ interface AgentStateResult<T> {
316
+ /** The subscription error, if the live channel reported one. */
317
+ error: Signal<SubscriptionError | undefined>;
318
+ /** The live synced state, or `undefined` before it is seeded/first pushed. */
319
+ state: Signal<T | undefined>;
320
+ }
321
+ /**
322
+ * Subscribe to an agent thread's synced state — the `setState`-style value a tool
323
+ * writes with `ctx.setState(...)`, seeded by `defineAgent({ initialState })`. A
324
+ * thin wrapper over `subscription(api.agents.agentState, { key })`: the server
325
+ * pushes a fresh frame whenever the state changes (the dedicated query's per-socket
326
+ * JSON memo suppresses no-op pushes on unrelated thread writes), so `state` updates
327
+ * only on a real `setState`. The Angular counterpart to React's `useAgentState`,
328
+ * re-expressed with signals.
329
+ *
330
+ * Generic over the app's state shape (`agentState&lt;SupportState>(...)`, itself a
331
+ * record) — the reference is typed as an optional record because codegen cannot see
332
+ * the per-agent state type; the generic casts to `T`. The `extends` bound (not a
333
+ * bare unbounded type parameter) is required: this `.ts` file is parsed JSX-aware by
334
+ * the bundler, where an unbounded type-param arrow is ambiguous with a JSX element.
335
+ *
336
+ * Call from an injection context (component/service field or constructor); pass an
337
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
338
+ */
339
+ declare const agentState: <T extends Record<string, unknown> = Record<string, unknown>>(options: AgentStateOptions) => AgentStateResult<T>;
340
+ /** The `agents:agentMessages` reference — live durable thread history. */
341
+ type AgentMessagesReference = FunctionReference<"query", {
342
+ key: string;
343
+ limit?: number;
344
+ }, ReadonlyArray<Record<string, unknown>>>;
345
+ /**
346
+ * An app stream reference that tees the agent's in-flight live events, keyed by
347
+ * thread. Carries token deltas and tool progress events; this primitive consumes
348
+ * only the progress arm (`kind === "progress"`).
349
+ */
350
+ type AgentLiveStreamReference = FunctionReference<"stream", {
351
+ key: string;
352
+ }, AgentLiveEvent>;
353
+ /**
354
+ * The `agents.*` reference surface the tool-events primitive reads. A structural
355
+ * subset of the generated `api.agents`, so the whole generated `api` object is
356
+ * assignable.
357
+ */
358
+ interface AgentToolEventsApi {
359
+ agents: {
360
+ agentMessages: AgentMessagesReference;
361
+ };
362
+ }
363
+ interface AgentToolEventsOptions {
364
+ /** The generated `api` — its `agents.agentMessages` query provides the durable tool lifecycle. */
365
+ api: AgentToolEventsApi;
366
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
367
+ client?: LunoraClient;
368
+ /**
369
+ * `DestroyRef` whose `onDestroy` tears the subscription + stream down. Defaults
370
+ * to `inject(DestroyRef)` — the calling component/service.
371
+ */
372
+ destroyRef?: DestroyRef;
373
+ /** History depth forwarded to `agents:agentMessages`. */
374
+ limit?: number;
375
+ /**
376
+ * Optional live event stream — the same app stream function `agentChat` uses.
377
+ * When supplied, ephemeral `ctx.reportProgress(...)` events for the thread are
378
+ * surfaced as `{ type: "progress" }` entries; when omitted only the durable
379
+ * lifecycle (call / result / awaiting-approval) is returned.
380
+ */
381
+ stream?: AgentLiveStreamReference;
382
+ /** The thread whose tool activity to observe. */
383
+ threadKey: string;
384
+ }
385
+ /**
386
+ * A single tool-lifecycle event for a thread. The durable arms
387
+ * (`call`/`result`/`awaiting-approval`) are derived from `agents:agentMessages`
388
+ * and carry the persisted `seq`; the ephemeral `progress` arm comes live off the
389
+ * stream and has no `seq`. Discriminate on `type`.
390
+ */
391
+ type AgentToolEvent = {
392
+ data: unknown;
393
+ toolCallId: string;
394
+ type: "progress";
395
+ } | {
396
+ input: unknown;
397
+ seq: number;
398
+ toolCallId: string;
399
+ toolName: string;
400
+ type: "call";
401
+ } | {
402
+ output: string;
403
+ seq: number;
404
+ status?: "approved" | "rejected";
405
+ toolCallId?: string;
406
+ toolName?: string;
407
+ type: "result";
408
+ } | {
409
+ seq: number;
410
+ toolCallId?: string;
411
+ toolName?: string;
412
+ type: "awaiting-approval";
413
+ };
414
+ interface AgentToolEventsResult {
415
+ /**
416
+ * The thread's tool events: the durable lifecycle (oldest first, by `seq`)
417
+ * followed by any in-flight ephemeral progress events, recomputed from the live
418
+ * subscription + stream. Treat as derived, not identity-stable.
419
+ */
420
+ events: Signal<ReadonlyArray<AgentToolEvent>>;
421
+ }
422
+ /**
423
+ * A focused view of a thread's tool activity: tool calls, their results,
424
+ * human-in-the-loop approval pauses, and live `ctx.reportProgress(...)` events —
425
+ * without the full chat message surface. The Angular counterpart to React's
426
+ * `useAgentToolEvents`, re-expressed as a `computed` signal.
427
+ *
428
+ * It composes the existing primitives rather than adding transport:
429
+ * `subscription(api.agents.agentMessages)` for the durable lifecycle and
430
+ * {@link stream} over the optional app event stream for ephemeral progress.
431
+ * Progress events are live-only (the durable path never emits them): they ride the
432
+ * same sink as token deltas and are surfaced here, correlated to their tool call by
433
+ * `toolCallId`. For the conversational surface (messages + streaming text +
434
+ * approvals) use `agentChat`; this primitive is the tool-observability slice.
435
+ *
436
+ * Call from an injection context (component/service field or constructor); pass an
437
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
438
+ */
439
+ declare const agentToolEvents: (options: AgentToolEventsOptions) => AgentToolEventsResult;
7
440
  interface AuthOptions {
8
441
  /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
9
442
  client?: LunoraClient;
@@ -460,6 +893,48 @@ interface RateLimitResult {
460
893
  * ```
461
894
  */
462
895
  declare const rateLimit: (config: RateLimitConfig, options?: RateLimitOptions) => RateLimitResult;
896
+ /** The lifecycle of a stream the primitive is observing. */
897
+ type StreamStatus = "complete" | "error" | "idle" | "streaming";
898
+ interface StreamOptions {
899
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
900
+ client?: LunoraClient;
901
+ /**
902
+ * `DestroyRef` whose `onDestroy` cancels the stream. Defaults to
903
+ * `inject(DestroyRef)` — the calling component/service.
904
+ */
905
+ destroyRef?: DestroyRef;
906
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
907
+ maxBuffer?: number;
908
+ /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
909
+ shardKey?: string;
910
+ }
911
+ interface StreamResult<T> {
912
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
913
+ cancel: () => void;
914
+ /** Chunks the server has pushed so far, in arrival order. */
915
+ chunks: Signal<ReadonlyArray<T>>;
916
+ /** The stream error, or `undefined`. */
917
+ error: Signal<Error | undefined>;
918
+ /** The stream lifecycle. */
919
+ status: Signal<StreamStatus>;
920
+ }
921
+ /**
922
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
923
+ * lifecycle status and a `cancel` function, all as signals.
924
+ *
925
+ * Unlike `subscription`, which tracks the latest value, `stream` accumulates every
926
+ * chunk the server pushes — use it for token-by-token deltas and other append-only
927
+ * feeds. Pass `"skip"` as `args` to keep the primitive mounted without opening a
928
+ * stream (mirrors `subscription`); the stream tears down when the owning
929
+ * `DestroyRef` fires. The Angular counterpart to React's `useStream`, re-expressed
930
+ * with signals.
931
+ *
932
+ * Call from an injection context (component/service field or constructor):
933
+ * ```ts
934
+ * readonly tokens = stream(api.chat.liveEvents, { key: "thread-1" });
935
+ * ```
936
+ */
937
+ declare const stream: <F extends FunctionReference<"stream">>(reference: F, args: ArgsOf<F> | "skip", options?: StreamOptions) => StreamResult<ReturnOf<F>>;
463
938
  interface SubscriptionOptions {
464
939
  /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
465
940
  client?: LunoraClient;
@@ -499,4 +974,164 @@ interface SubscriptionResult<T> {
499
974
  * ```
500
975
  */
501
976
  declare const subscription: <F extends FunctionReference>(reference: F, args: ArgsOf<F> | "skip", options?: SubscriptionOptions) => SubscriptionResult<ReturnOf<F>>;
502
- export { 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 SubscriptionOptions, type SubscriptionResult, auth, connectionStatus, flag, flags, hydratePreloaded, infiniteQuery, injectLunoraClient, liveQuery, mutate, mutator, paginatedQuery, presence, provideLunora, rateLimit, subscription };
977
+ /**
978
+ * Browser Web Audio subsystems for `voiceAgent` — the default microphone capture
979
+ * and speaker playback implementations injected into the primitive via its
980
+ * `createMicrophone` / `createSpeaker` seams. Kept in a sibling module so the
981
+ * heavy Web Audio graph (and its structural DOM typings) stays isolated from the
982
+ * primitive's transport + signal-state logic and remains mockable in a
983
+ * non-browser test env.
984
+ */
985
+ /**
986
+ * The negotiated audio format the voice DO streams back. Mirrors
987
+ * `@lunora/agent`'s `VoiceServerFrame` `ready.audioFormat` — re-declared (not
988
+ * imported) so this Angular package never pulls in the server-only `@lunora/agent`
989
+ * module graph.
990
+ */
991
+ type VoiceAudioFormat = "mp3" | "wav";
992
+ /** Captures microphone audio and reports level / turn boundaries back to the primitive. */
993
+ interface VoiceMicrophone {
994
+ /** Mute/unmute the mic without tearing down the capture graph. */
995
+ setMuted: (muted: boolean) => void;
996
+ /** Stop capture and release the media stream + audio graph. */
997
+ stop: () => void;
998
+ }
999
+ /** Plays the server's streamed audio chunks and supports a mid-utterance barge-in. */
1000
+ interface VoiceSpeaker {
1001
+ /** Queue a decoded audio chunk for gap-minimized playback. */
1002
+ enqueue: (audio: Uint8Array) => void;
1003
+ /** Drop everything queued and stop the current chunk (barge-in). */
1004
+ interrupt: () => void;
1005
+ /** Release the playback audio context. */
1006
+ stop: () => void;
1007
+ }
1008
+ /** Config passed to a {@link CreateMicrophone} factory. */
1009
+ interface MicrophoneConfig {
1010
+ /** The consecutive above-threshold chunk count that counts as a barge-in. */
1011
+ interruptChunks: number;
1012
+ /** RMS above which the user is considered to be barging in while the agent speaks. */
1013
+ interruptThreshold: number;
1014
+ /** `true` while `status === "speaking"` — gates barge-in detection. */
1015
+ isSpeaking: () => boolean;
1016
+ /** One 16 kHz mono 16-bit little-endian PCM frame captured from the mic. */
1017
+ onAudio: (pcm: Uint8Array) => void;
1018
+ /** A barge-in was detected (RMS spike while the agent is speaking). */
1019
+ onInterrupt: () => void;
1020
+ /** The current input RMS (0–1), for a level meter. */
1021
+ onLevel: (rms: number) => void;
1022
+ /** A spoken utterance ended (speech followed by `silenceDurationMs` of silence). */
1023
+ onSilence: () => void;
1024
+ /** Milliseconds of sub-threshold audio (after speech) that closes an utterance. */
1025
+ silenceDurationMs: number;
1026
+ /** RMS below which audio counts as silence. */
1027
+ silenceThreshold: number;
1028
+ }
1029
+ type CreateMicrophone = (config: MicrophoneConfig) => Promise<VoiceMicrophone>;
1030
+ type CreateSpeaker = (config: {
1031
+ audioFormat: VoiceAudioFormat;
1032
+ }) => VoiceSpeaker;
1033
+ /**
1034
+ * The default browser microphone: `getUserMedia` → a Web Audio `ScriptProcessor`
1035
+ * that tees 16 kHz PCM frames, tracks input RMS, auto-commits an utterance after
1036
+ * a silence gap, and flags a barge-in while the agent is speaking.
1037
+ */
1038
+ /**
1039
+ * The `agents.&lt;name>Voice` reference codegen emits for a voice-enabled agent — a
1040
+ * live, WS-backed session keyed by `threadKey`. A structural subset of the
1041
+ * generated member, so passing `api.agents.&lt;name>Voice` type-checks.
1042
+ */
1043
+ type VoiceReference = FunctionReference<"stream", {
1044
+ threadKey: string;
1045
+ }, Record<string, unknown>>;
1046
+ /** The lifecycle of a voice call, mirrored to the UI. */
1047
+ type VoiceStatus = "idle" | "listening" | "speaking" | "thinking";
1048
+ /** A minimal structural subset of the DOM `WebSocket` the primitive drives. */
1049
+ interface VoiceSocket {
1050
+ binaryType: string;
1051
+ close: () => void;
1052
+ onclose: ((event: unknown) => void) | null;
1053
+ onerror: ((event: unknown) => void) | null;
1054
+ onmessage: ((event: {
1055
+ data: unknown;
1056
+ }) => void) | null;
1057
+ onopen: ((event: unknown) => void) | null;
1058
+ readonly readyState: number;
1059
+ send: (data: ArrayBufferView | ArrayBufferLike | string) => void;
1060
+ }
1061
+ type CreateSocket = (url: string) => VoiceSocket;
1062
+ interface VoiceAgentOptions {
1063
+ /** Client to bind to. Defaults to the injected `LUNORA_CLIENT`. */
1064
+ client?: LunoraClient;
1065
+ /**
1066
+ * Advanced/test seam: build the microphone capture subsystem. Defaults to a
1067
+ * `getUserMedia` + Web Audio implementation. Injected wholesale so the Web
1068
+ * Audio graph stays isolated (and mockable in a non-browser test env).
1069
+ */
1070
+ createMicrophone?: CreateMicrophone;
1071
+ /** Advanced/test seam: open the transport. Defaults to `new WebSocket(url)`. */
1072
+ createSocket?: CreateSocket;
1073
+ /** Advanced/test seam: build the audio playback subsystem. Defaults to a Web Audio implementation. */
1074
+ createSpeaker?: CreateSpeaker;
1075
+ /**
1076
+ * `DestroyRef` whose `onDestroy` tears the call down. Defaults to
1077
+ * `inject(DestroyRef)` — the calling component/service.
1078
+ */
1079
+ destroyRef?: DestroyRef;
1080
+ /** Consecutive above-`interruptThreshold` chunks that trigger a barge-in. Default `3`. */
1081
+ interruptChunks?: number;
1082
+ /** Input RMS above which the user is treated as barging in while the agent speaks. Default `0.15`. */
1083
+ interruptThreshold?: number;
1084
+ /** Milliseconds of silence (after speech) that auto-commits an utterance. Default `1200`. */
1085
+ silenceDurationMs?: number;
1086
+ /** Input RMS below which audio counts as silence. Default `0.01`. */
1087
+ silenceThreshold?: number;
1088
+ /** The thread to converse on — shared with the agent's text turns. Resolved when the call opens. */
1089
+ threadKey: string;
1090
+ /** The generated `api.agents.&lt;name>Voice` reference — identifies the voice DO endpoint. */
1091
+ voice: VoiceReference;
1092
+ }
1093
+ interface VoiceAgentResult {
1094
+ /** The current input RMS (0–1) — drive a mic level meter. */
1095
+ audioLevel: Signal<number>;
1096
+ /** `true` once the WS `ready` handshake completed. */
1097
+ connected: Signal<boolean>;
1098
+ /** Tear down the call: close the socket, stop the mic, release audio. Idempotent. */
1099
+ endCall: () => void;
1100
+ /** The last transport/pipeline error, or `undefined`. */
1101
+ error: Signal<Error | undefined>;
1102
+ /** The live assistant text for the in-flight turn (grows via deltas; finalized on done). */
1103
+ interimTranscript: Signal<string>;
1104
+ /** `true` while the mic is muted. */
1105
+ isMuted: Signal<boolean>;
1106
+ /** Send a typed turn (no audio) — a text message spoken back by the agent. */
1107
+ sendText: (text: string) => void;
1108
+ /** Open the mic, connect the socket, and start the conversation. Idempotent while active. */
1109
+ startCall: () => Promise<void>;
1110
+ /** The current call lifecycle. */
1111
+ status: Signal<VoiceStatus>;
1112
+ /** Mute/unmute the microphone. Returns the new muted state. */
1113
+ toggleMute: () => boolean;
1114
+ /** The last finalized user utterance (STT result). */
1115
+ transcript: Signal<string>;
1116
+ }
1117
+ /**
1118
+ * A first-class voice-call surface for a voice-enabled agent: it opens a
1119
+ * WebSocket to the agent's `VoiceSessionDO`, captures mic audio as 16 kHz PCM,
1120
+ * streams the agent's synthesized speech back through the browser's audio output,
1121
+ * and mirrors the call lifecycle (`status`, `transcript`, `interimTranscript`,
1122
+ * `audioLevel`) to Angular signals. Pass the generated `api.agents.&lt;name>Voice`
1123
+ * reference (never a string), matching `agentChat`'s reference-passing style. The
1124
+ * Angular counterpart to React's `useVoiceAgent`, re-expressed with signals; the
1125
+ * per-call connection lives in a closure variable (the primitive runs once per
1126
+ * component, so no signal-of-connection indirection is needed).
1127
+ *
1128
+ * v1 transport is plain binary WebSocket frames with push-to-talk / silence-timer
1129
+ * turn detection and client-side RMS barge-in. The heavy Web Audio capture and
1130
+ * playback subsystems are injectable (`createMicrophone` / `createSpeaker` /
1131
+ * `createSocket`) so the primitive is drivable outside a browser.
1132
+ *
1133
+ * Call from an injection context (component/service field or constructor); pass an
1134
+ * explicit `client` / `destroyRef` to drive it outside one (e.g. in a test).
1135
+ */
1136
+ declare const voiceAgent: (options: VoiceAgentOptions) => VoiceAgentResult;
1137
+ 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 };