@adea-ai/voice 0.4.3 → 0.5.0

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/README.md CHANGED
@@ -110,6 +110,12 @@ of the shared contract (`WebTranscriptionSessionOptions`):
110
110
  - **Barge-in**: `onSpeechStart` fires on the recognizer's `speechstart` (or the first words).
111
111
  `VoiceTurnManager` wires it to `notifySpeechDetected()` itself; hosts with their own sessions
112
112
  spread `bargeInOnSpeechStart(manager)` into the session options.
113
+ - **Turn metrics**: `VoiceTurnManager` emits one `metrics` event per turn, before the turn's
114
+ terminal event, with `firstPartialMs`, `transcriptMs`, `firstAudioMs` and `speechFinishedMs`
115
+ measured from the moment the microphone opens (the same shape the desktop conversation reports).
116
+ Timings only, never text or audio. A `SpeechSink` reports its first audio by calling the
117
+ `onAudioStart` option it is given (wire Phonon's `onFirstAudio` or a platform voice's `onstart`
118
+ to it); a sink that never calls it reports `firstAudioMs: null`. Pass `now` to use another clock.
113
119
 
114
120
  ## Pinning the helpers in an app
115
121
 
package/dist/web/index.js CHANGED
@@ -1512,6 +1512,7 @@ class VoiceTurnManager {
1512
1512
  speech;
1513
1513
  generation = 0;
1514
1514
  finished = false;
1515
+ turn;
1515
1516
  constructor(options) {
1516
1517
  this.options = options;
1517
1518
  }
@@ -1525,8 +1526,8 @@ class VoiceTurnManager {
1525
1526
  const generation = ++this.generation;
1526
1527
  const previous = this.session;
1527
1528
  this.session = undefined;
1528
- if (this.speech)
1529
- this.stopSpeech("barge-in");
1529
+ if (!this.stopSpeech("barge-in"))
1530
+ this.closeTurn();
1530
1531
  if (previous)
1531
1532
  await previous.cancel();
1532
1533
  if (this.finished)
@@ -1558,6 +1559,7 @@ class VoiceTurnManager {
1558
1559
  return;
1559
1560
  }
1560
1561
  this.session = session;
1562
+ this.openTurn();
1561
1563
  this.emit({ type: "listening" });
1562
1564
  this.consume(session);
1563
1565
  }
@@ -1570,28 +1572,51 @@ class VoiceTurnManager {
1570
1572
  }
1571
1573
  if (this.speech)
1572
1574
  this.stopSpeech("replaced");
1573
- const handle = this.options.synthesis.speak(text);
1574
- this.speech = handle;
1575
- this.emit({ type: "speaking", text });
1576
- handle.done.then(() => {
1575
+ const turn = this.turn ?? this.openTurn();
1576
+ let handle;
1577
+ let startedBeforeReturn;
1578
+ const audioStarted = (at) => {
1577
1579
  if (this.speech !== handle)
1578
1580
  return;
1581
+ if (turn.firstAudio === null)
1582
+ turn.firstAudio = at;
1583
+ this.emit({ type: "speech-started" });
1584
+ };
1585
+ const onAudioStart = () => {
1586
+ if (handle === undefined)
1587
+ startedBeforeReturn ??= this.now();
1588
+ else
1589
+ audioStarted(this.now());
1590
+ };
1591
+ const current = this.options.synthesis.speak(text, { onAudioStart });
1592
+ handle = current;
1593
+ this.speech = current;
1594
+ this.emit({ type: "speaking", text });
1595
+ if (startedBeforeReturn !== undefined)
1596
+ audioStarted(startedBeforeReturn);
1597
+ current.done.then(() => {
1598
+ if (this.speech !== current)
1599
+ return;
1579
1600
  this.speech = undefined;
1601
+ if (this.turn === turn)
1602
+ turn.speechFinished = this.now();
1603
+ this.closeTurn(turn);
1580
1604
  this.emit({ type: "speech-finished" });
1581
1605
  }).catch((error) => {
1582
- if (this.speech !== handle)
1606
+ if (this.speech !== current)
1583
1607
  return;
1584
1608
  this.speech = undefined;
1585
1609
  const wrapped = VoiceError2.wrapping(error);
1610
+ this.closeTurn(turn);
1586
1611
  this.emit(wrapped.code === "cancelled" ? { type: "speech-cancelled" } : { type: "failed", error: wrapped });
1587
1612
  });
1588
1613
  return {
1589
- done: handle.done,
1614
+ done: current.done,
1590
1615
  cancel: () => {
1591
- if (this.speech === handle)
1592
- this.stopSpeech("replaced");
1616
+ if (this.speech === current)
1617
+ this.stopSpeech("answer-cancelled");
1593
1618
  else
1594
- handle.cancel();
1619
+ current.cancel();
1595
1620
  }
1596
1621
  };
1597
1622
  }
@@ -1606,6 +1631,7 @@ class VoiceTurnManager {
1606
1631
  this.finished = true;
1607
1632
  this.generation += 1;
1608
1633
  this.stopSpeech("cancel");
1634
+ this.closeTurn();
1609
1635
  const session = this.session;
1610
1636
  this.session = undefined;
1611
1637
  await session?.cancel();
@@ -1614,13 +1640,45 @@ class VoiceTurnManager {
1614
1640
  stopSpeech(reason) {
1615
1641
  const speech = this.speech;
1616
1642
  if (speech === undefined)
1617
- return;
1643
+ return false;
1618
1644
  this.speech = undefined;
1645
+ const turn = this.turn;
1619
1646
  speech.cancel();
1647
+ if (turn && (reason === "barge-in" || reason === "answer-cancelled"))
1648
+ this.closeTurn(turn);
1620
1649
  if (reason === "barge-in")
1621
1650
  this.emit({ type: "barge-in" });
1622
1651
  if (reason !== "cancel")
1623
1652
  this.emit({ type: "speech-cancelled" });
1653
+ return true;
1654
+ }
1655
+ now() {
1656
+ return (this.options.now ?? defaultNow2)();
1657
+ }
1658
+ openTurn() {
1659
+ const turn = {
1660
+ start: this.now(),
1661
+ firstPartial: null,
1662
+ transcript: null,
1663
+ firstAudio: null,
1664
+ speechFinished: null
1665
+ };
1666
+ this.turn = turn;
1667
+ return turn;
1668
+ }
1669
+ closeTurn(only) {
1670
+ const turn = this.turn;
1671
+ if (turn === undefined || only !== undefined && turn !== only)
1672
+ return;
1673
+ this.turn = undefined;
1674
+ const since = (at) => at === null ? null : Math.max(0, at - turn.start);
1675
+ const metrics = {
1676
+ firstPartialMs: since(turn.firstPartial),
1677
+ transcriptMs: since(turn.transcript),
1678
+ firstAudioMs: since(turn.firstAudio),
1679
+ speechFinishedMs: since(turn.speechFinished)
1680
+ };
1681
+ this.emit({ type: "metrics", metrics });
1624
1682
  }
1625
1683
  async consume(session) {
1626
1684
  try {
@@ -1633,24 +1691,31 @@ class VoiceTurnManager {
1633
1691
  if (this.session !== session)
1634
1692
  return;
1635
1693
  this.session = undefined;
1694
+ this.closeTurn();
1636
1695
  this.emit({ type: "failed", error: VoiceError2.wrapping(error) });
1637
1696
  }
1638
1697
  }
1639
1698
  forward(event) {
1640
1699
  switch (event.type) {
1641
1700
  case "partial":
1701
+ if (this.turn && this.turn.firstPartial === null)
1702
+ this.turn.firstPartial = this.now();
1642
1703
  this.emit({ type: "partial", partial: event.partial });
1643
1704
  return;
1644
1705
  case "final":
1645
1706
  this.session = undefined;
1707
+ if (this.turn && this.turn.transcript === null)
1708
+ this.turn.transcript = this.now();
1646
1709
  this.emit({ type: "transcript", text: event.text });
1647
1710
  return;
1648
1711
  case "failed":
1649
1712
  this.session = undefined;
1713
+ this.closeTurn();
1650
1714
  this.emit({ type: "failed", error: event.error });
1651
1715
  return;
1652
1716
  case "cancelled":
1653
1717
  this.session = undefined;
1718
+ this.closeTurn();
1654
1719
  this.emit({ type: "cancelled" });
1655
1720
  return;
1656
1721
  }
@@ -1665,6 +1730,9 @@ class VoiceTurnManager {
1665
1730
  }
1666
1731
  }
1667
1732
  }
1733
+ function defaultNow2() {
1734
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
1735
+ }
1668
1736
  function defaultListenerError(error) {
1669
1737
  console.error("voice turn listener threw", error);
1670
1738
  }
@@ -11,14 +11,24 @@
11
11
  * The rule that matters: **barge-in stops speech with a request cancel, not a mute**, and a turn
12
12
  * always ends in exactly one terminal event. Starting a new turn while the assistant is still
13
13
  * talking is the common case on a page, so it is the default, not an option.
14
+ *
15
+ * Every turn also reports one `metrics` event when it closes: first partial, transcript, first
16
+ * audio and speech finished, in milliseconds from the turn's start. Timings only, never text or
17
+ * audio, so a host can log them without collecting anything private.
14
18
  */
15
19
  import type { TranscriptionProvider } from "./stt/speech-recognition";
16
20
  import type { TurnEvent } from "../contract/turns";
21
+ export interface SpeechSinkOptions {
22
+ readonly signal?: AbortSignal;
23
+ /**
24
+ * Call when the answer's first audio plays (Phonon's `onFirstAudio`, a platform voice's
25
+ * `onstart`). Optional: a sink that never calls it reports `firstAudioMs: null`.
26
+ */
27
+ readonly onAudioStart?: () => void;
28
+ }
17
29
  /** What the assistant does with its answer. The manager never knows which engine is behind it. */
18
30
  export interface SpeechSink {
19
- speak(text: string, options?: {
20
- signal?: AbortSignal;
21
- }): {
31
+ speak(text: string, options?: SpeechSinkOptions): {
22
32
  done: Promise<unknown>;
23
33
  cancel(): void;
24
34
  };
@@ -36,6 +46,8 @@ export interface TurnManagerOptions {
36
46
  readonly bargeInOnSpeech?: boolean;
37
47
  /** Receives an error thrown by an event listener. Default: `console.error`. */
38
48
  readonly onListenerError?: (error: unknown) => void;
49
+ /** Monotonic clock in milliseconds for turn metrics. Default: `performance.now()`. */
50
+ readonly now?: () => number;
39
51
  }
40
52
  /**
41
53
  * One conversation's turns. `startListening()` and `speak()` are the two entry points a page
@@ -49,6 +61,8 @@ export declare class VoiceTurnManager {
49
61
  /** Bumped by every `startListening()` and by `cancel()`: an older start that resumes is stale. */
50
62
  private generation;
51
63
  private finished;
64
+ /** The turn whose metrics are still being collected. */
65
+ private turn;
52
66
  constructor(options: TurnManagerOptions);
53
67
  /** Subscribes to turn events. Returns an unsubscribe function. */
54
68
  onEvent(listener: (event: TurnEvent) => void): () => void;
@@ -70,10 +84,18 @@ export declare class VoiceTurnManager {
70
84
  cancel(): Promise<void>;
71
85
  /**
72
86
  * `barge-in`: the person talked over the answer (`barge-in` + `speech-cancelled`).
73
- * `replaced`: a newer answer or the host stopped it (`speech-cancelled`).
87
+ * `replaced`: a newer answer takes over (`speech-cancelled`), but the turn continues.
88
+ * `answer-cancelled`: the host stopped the current answer, ending its turn.
74
89
  * `cancel`: the manager is tearing down; its own `cancelled` is the terminal event.
75
90
  */
76
91
  private stopSpeech;
92
+ private now;
93
+ private openTurn;
94
+ /**
95
+ * Emits the turn's one `metrics` event and forgets it. With `only`, closes that turn and nothing
96
+ * newer: a late callback from an answer a new turn replaced must not close the new turn.
97
+ */
98
+ private closeTurn;
77
99
  private consume;
78
100
  private forward;
79
101
  private emit;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adea-ai/voice",
3
- "version": "0.4.3",
3
+ "version": "0.5.0",
4
4
  "description": "The Adea Voice SDK: the shared speech provider contract, unified per-device voice settings, the desktop client for the pinned Apple/transcribe.cpp/audio.cpp helpers, and the browser providers.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/src/web/turns.ts CHANGED
@@ -11,14 +11,36 @@
11
11
  * The rule that matters: **barge-in stops speech with a request cancel, not a mute**, and a turn
12
12
  * always ends in exactly one terminal event. Starting a new turn while the assistant is still
13
13
  * talking is the common case on a page, so it is the default, not an option.
14
+ *
15
+ * Every turn also reports one `metrics` event when it closes: first partial, transcript, first
16
+ * audio and speech finished, in milliseconds from the turn's start. Timings only, never text or
17
+ * audio, so a host can log them without collecting anything private.
14
18
  */
15
19
  import type { SessionEvent, TranscriptionProvider, TranscriptionSession } from "./stt/speech-recognition";
16
20
  import { VoiceError } from "../contract/errors";
17
- import type { TurnEvent } from "../contract/turns";
21
+ import type { TurnEvent, TurnMetrics } from "../contract/turns";
22
+
23
+ export interface SpeechSinkOptions {
24
+ readonly signal?: AbortSignal;
25
+ /**
26
+ * Call when the answer's first audio plays (Phonon's `onFirstAudio`, a platform voice's
27
+ * `onstart`). Optional: a sink that never calls it reports `firstAudioMs: null`.
28
+ */
29
+ readonly onAudioStart?: () => void;
30
+ }
18
31
 
19
32
  /** What the assistant does with its answer. The manager never knows which engine is behind it. */
20
33
  export interface SpeechSink {
21
- speak(text: string, options?: { signal?: AbortSignal }): { done: Promise<unknown>; cancel(): void };
34
+ speak(text: string, options?: SpeechSinkOptions): { done: Promise<unknown>; cancel(): void };
35
+ }
36
+
37
+ /** The open turn's timings, as clock readings. */
38
+ interface TurnClock {
39
+ readonly start: number;
40
+ firstPartial: number | null;
41
+ transcript: number | null;
42
+ firstAudio: number | null;
43
+ speechFinished: number | null;
22
44
  }
23
45
 
24
46
  /** The shared turn vocabulary (`@adea-ai/voice/contract`), re-exported for existing imports. */
@@ -35,6 +57,8 @@ export interface TurnManagerOptions {
35
57
  readonly bargeInOnSpeech?: boolean;
36
58
  /** Receives an error thrown by an event listener. Default: `console.error`. */
37
59
  readonly onListenerError?: (error: unknown) => void;
60
+ /** Monotonic clock in milliseconds for turn metrics. Default: `performance.now()`. */
61
+ readonly now?: () => number;
38
62
  }
39
63
 
40
64
  /**
@@ -50,6 +74,8 @@ export class VoiceTurnManager {
50
74
  /** Bumped by every `startListening()` and by `cancel()`: an older start that resumes is stale. */
51
75
  private generation = 0;
52
76
  private finished = false;
77
+ /** The turn whose metrics are still being collected. */
78
+ private turn: TurnClock | undefined;
53
79
 
54
80
  constructor(options: TurnManagerOptions) {
55
81
  this.options = options;
@@ -71,7 +97,7 @@ export class VoiceTurnManager {
71
97
  const previous = this.session;
72
98
  // Detach first, so the previous session's own `cancelled` event is not reported as this turn's.
73
99
  this.session = undefined;
74
- if (this.speech) this.stopSpeech("barge-in");
100
+ if (!this.stopSpeech("barge-in")) this.closeTurn();
75
101
  if (previous) await previous.cancel();
76
102
  if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
77
103
  if (generation !== this.generation) return; // a newer startListening() owns the turn now
@@ -99,6 +125,8 @@ export class VoiceTurnManager {
99
125
  return;
100
126
  }
101
127
  this.session = session;
128
+ // The turn's clock starts when the microphone is open.
129
+ this.openTurn();
102
130
  this.emit({ type: "listening" });
103
131
  void this.consume(session);
104
132
  }
@@ -113,28 +141,47 @@ export class VoiceTurnManager {
113
141
  if (this.finished) {
114
142
  return { done: Promise.reject(new VoiceError("cancelled")), cancel: () => {} };
115
143
  }
144
+ // A replaced answer stays in its turn; an answer with no turn open starts one.
116
145
  if (this.speech) this.stopSpeech("replaced");
117
- const handle = this.options.synthesis.speak(text);
118
- this.speech = handle;
146
+ const turn = this.turn ?? this.openTurn();
147
+ let handle: { done: Promise<unknown>; cancel(): void } | undefined;
148
+ let startedBeforeReturn: number | undefined;
149
+ const audioStarted = (at: number) => {
150
+ if (this.speech !== handle) return; // replaced, cancelled, or stale
151
+ if (turn.firstAudio === null) turn.firstAudio = at;
152
+ this.emit({ type: "speech-started" });
153
+ };
154
+ const onAudioStart = () => {
155
+ // A sink may report audio while `speak()` is still returning: report it after `speaking`.
156
+ if (handle === undefined) startedBeforeReturn ??= this.now();
157
+ else audioStarted(this.now());
158
+ };
159
+ const current = this.options.synthesis.speak(text, { onAudioStart });
160
+ handle = current;
161
+ this.speech = current;
119
162
  this.emit({ type: "speaking", text });
120
- void handle.done
163
+ if (startedBeforeReturn !== undefined) audioStarted(startedBeforeReturn);
164
+ void current.done
121
165
  .then(() => {
122
- if (this.speech !== handle) return;
166
+ if (this.speech !== current) return;
123
167
  this.speech = undefined;
168
+ if (this.turn === turn) turn.speechFinished = this.now();
169
+ this.closeTurn(turn);
124
170
  this.emit({ type: "speech-finished" });
125
171
  })
126
172
  .catch((error) => {
127
- if (this.speech !== handle) return;
173
+ if (this.speech !== current) return;
128
174
  this.speech = undefined;
129
175
  const wrapped = VoiceError.wrapping(error);
176
+ this.closeTurn(turn);
130
177
  this.emit(wrapped.code === "cancelled" ? { type: "speech-cancelled" } : { type: "failed", error: wrapped });
131
178
  });
132
179
  return {
133
- done: handle.done,
180
+ done: current.done,
134
181
  // Only this answer: cancelling a handle that was already replaced must not stop the new one.
135
182
  cancel: () => {
136
- if (this.speech === handle) this.stopSpeech("replaced");
137
- else handle.cancel();
183
+ if (this.speech === current) this.stopSpeech("answer-cancelled");
184
+ else current.cancel();
138
185
  },
139
186
  };
140
187
  }
@@ -142,6 +189,7 @@ export class VoiceTurnManager {
142
189
  /** The person started talking (voice detector, key press, or a new session). */
143
190
  notifySpeechDetected(): void {
144
191
  if (this.options.bargeInOnSpeech === false) return;
192
+ // The person talking over the answer ends that turn; their next one starts with `startListening()`.
145
193
  this.stopSpeech("barge-in");
146
194
  }
147
195
 
@@ -151,6 +199,7 @@ export class VoiceTurnManager {
151
199
  this.finished = true;
152
200
  this.generation += 1;
153
201
  this.stopSpeech("cancel");
202
+ this.closeTurn();
154
203
  const session = this.session;
155
204
  this.session = undefined;
156
205
  await session?.cancel();
@@ -159,16 +208,54 @@ export class VoiceTurnManager {
159
208
 
160
209
  /**
161
210
  * `barge-in`: the person talked over the answer (`barge-in` + `speech-cancelled`).
162
- * `replaced`: a newer answer or the host stopped it (`speech-cancelled`).
211
+ * `replaced`: a newer answer takes over (`speech-cancelled`), but the turn continues.
212
+ * `answer-cancelled`: the host stopped the current answer, ending its turn.
163
213
  * `cancel`: the manager is tearing down; its own `cancelled` is the terminal event.
164
214
  */
165
- private stopSpeech(reason: "barge-in" | "replaced" | "cancel"): void {
215
+ private stopSpeech(reason: "barge-in" | "replaced" | "answer-cancelled" | "cancel"): boolean {
166
216
  const speech = this.speech;
167
- if (speech === undefined) return;
217
+ if (speech === undefined) return false;
168
218
  this.speech = undefined;
219
+ const turn = this.turn;
169
220
  speech.cancel();
221
+ if (turn && (reason === "barge-in" || reason === "answer-cancelled")) this.closeTurn(turn);
170
222
  if (reason === "barge-in") this.emit({ type: "barge-in" });
171
223
  if (reason !== "cancel") this.emit({ type: "speech-cancelled" });
224
+ return true;
225
+ }
226
+
227
+ private now(): number {
228
+ return (this.options.now ?? defaultNow)();
229
+ }
230
+
231
+ private openTurn(): TurnClock {
232
+ const turn: TurnClock = {
233
+ start: this.now(),
234
+ firstPartial: null,
235
+ transcript: null,
236
+ firstAudio: null,
237
+ speechFinished: null,
238
+ };
239
+ this.turn = turn;
240
+ return turn;
241
+ }
242
+
243
+ /**
244
+ * Emits the turn's one `metrics` event and forgets it. With `only`, closes that turn and nothing
245
+ * newer: a late callback from an answer a new turn replaced must not close the new turn.
246
+ */
247
+ private closeTurn(only?: TurnClock): void {
248
+ const turn = this.turn;
249
+ if (turn === undefined || (only !== undefined && turn !== only)) return;
250
+ this.turn = undefined;
251
+ const since = (at: number | null) => (at === null ? null : Math.max(0, at - turn.start));
252
+ const metrics: TurnMetrics = {
253
+ firstPartialMs: since(turn.firstPartial),
254
+ transcriptMs: since(turn.transcript),
255
+ firstAudioMs: since(turn.firstAudio),
256
+ speechFinishedMs: since(turn.speechFinished),
257
+ };
258
+ this.emit({ type: "metrics", metrics });
172
259
  }
173
260
 
174
261
  private async consume(session: TranscriptionSession): Promise<void> {
@@ -180,6 +267,7 @@ export class VoiceTurnManager {
180
267
  } catch (error) {
181
268
  if (this.session !== session) return;
182
269
  this.session = undefined;
270
+ this.closeTurn();
183
271
  this.emit({ type: "failed", error: VoiceError.wrapping(error) });
184
272
  }
185
273
  }
@@ -187,18 +275,22 @@ export class VoiceTurnManager {
187
275
  private forward(event: SessionEvent): void {
188
276
  switch (event.type) {
189
277
  case "partial":
278
+ if (this.turn && this.turn.firstPartial === null) this.turn.firstPartial = this.now();
190
279
  this.emit({ type: "partial", partial: event.partial });
191
280
  return;
192
281
  case "final":
193
282
  this.session = undefined;
283
+ if (this.turn && this.turn.transcript === null) this.turn.transcript = this.now();
194
284
  this.emit({ type: "transcript", text: event.text });
195
285
  return;
196
286
  case "failed":
197
287
  this.session = undefined;
288
+ this.closeTurn();
198
289
  this.emit({ type: "failed", error: event.error });
199
290
  return;
200
291
  case "cancelled":
201
292
  this.session = undefined;
293
+ this.closeTurn();
202
294
  this.emit({ type: "cancelled" });
203
295
  return;
204
296
  }
@@ -216,6 +308,10 @@ export class VoiceTurnManager {
216
308
  }
217
309
  }
218
310
 
311
+ function defaultNow(): number {
312
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
313
+ }
314
+
219
315
  function defaultListenerError(error: unknown): void {
220
316
  console.error("voice turn listener threw", error);
221
317
  }