@startsimpli/integrations 0.2.164 → 0.2.165

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.
@@ -1,20 +1,20 @@
1
1
  /**
2
- * THE CONVERSE PAGE (bd startsim-tgiwj): talk to Tandem and hear it answer, from a phone browser.
2
+ * THE CONVERSE PAGE: opening it is being in a meeting (bd startsim-1jqce, startsim-tgiwj).
3
3
  *
4
- * One big button: tap to talk, tap again to send. The reply plays by itself (see `SILENCE_WAV` for the iOS
5
- * rule that makes that work), Repeat says it again, a text box does the same thing without a microphone,
6
- * and End saves the conversation. Mounted by the app; the model, voice and keys all live behind
7
- * /corpus/converse, never here.
8
- *
9
- * A turn that failed to send keeps its recording and its `turn_id`: Try again resends the SAME press, so the
10
- * server replays it instead of adding a second one.
4
+ * One tap on Start opens the microphone and unlocks sound (a phone only allows that inside a tap). From
5
+ * there it listens, notices the end of what you said by itself, sends it, speaks the reply and goes straight
6
+ * back to listening until you tap End, which saves the conversation. The state (Listening / Thinking /
7
+ * Speaking), the reply text, a Play reply button and a typing box are always on screen, so it is never
8
+ * silent without saying why. The loop itself is `createMeetingController`, shared with the native app;
9
+ * silence length, utterance limits and interrupt-on-speech are `meeting` config with defaults.
11
10
  */
12
11
  import * as React from 'react';
13
12
 
14
- import { ConverseClientError, type ConverseClient } from '../../corpus/converse/client';
13
+ import type { ConverseClient } from '../../corpus/converse/client';
14
+ import { createMeetingController, type MeetingController, type MeetingState } from '../../corpus/converse/meeting';
15
+ import type { MeetingConfig } from '../../corpus/converse/meeting-config';
15
16
  import type { ConverseEndResult } from '../../corpus/converse/types';
16
- import { SILENCE_WAV } from './converse/silence';
17
- import { useRecorder, type RecorderOptions } from './converse/useRecorder';
17
+ import { createBrowserMeetingIO, type BrowserMeetingIO } from './converse/browserIO';
18
18
 
19
19
  export type ConverseSlot = 'root' | 'talk' | 'talking' | 'secondary' | 'bubbleUser' | 'bubbleReply' | 'muted' | 'error' | 'input';
20
20
  export type ConverseClassNames = Partial<Record<ConverseSlot, string>>;
@@ -25,150 +25,105 @@ const FALLBACK: Record<ConverseSlot, string> = {
25
25
  muted: 'text-sm opacity-70', error: 'rounded-md border p-3 text-sm', input: 'rounded-md border px-3 py-2 text-base',
26
26
  };
27
27
 
28
- type Phase = 'idle' | 'recording' | 'sending' | 'speaking' | 'ending';
29
- interface Line { role: 'user' | 'assistant'; text: string }
30
- interface Pending { blob?: Blob; text?: string; turnId: string }
31
-
32
- const freshId = () => `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
28
+ const EMPTY: MeetingState = { phase: 'idle', retryable: false, lines: [], error: null, noAudio: null, conversationId: null, saved: null };
33
29
 
34
- export interface ConversePageProps extends RecorderOptions {
30
+ export interface ConversePageProps {
35
31
  client: ConverseClient;
36
32
  classNames?: ConverseClassNames;
37
- /** Injectable for tests. */
38
- createAudio?: () => HTMLAudioElement;
33
+ /** Meeting settings; every one has a default. */
34
+ meeting?: Partial<MeetingConfig>;
35
+ /** Injectable for tests; defaults to the browser's microphone and audio element. */
36
+ createIO?: () => BrowserMeetingIO;
39
37
  /** Where the saved conversation can be read; given the End result. */
40
38
  savedLink?: (saved: ConverseEndResult) => React.ReactNode;
41
39
  }
42
40
 
43
- export function ConversePage({ client, classNames, mediaDevices, recorderFactory, createAudio, savedLink }: ConversePageProps) {
41
+ const STATUS: Record<string, string> = {
42
+ idle: 'Tap Start. Then just talk: it listens, answers out loud, and listens again.',
43
+ listening: 'Listening… speak whenever you are ready.',
44
+ thinking: 'Thinking…',
45
+ speaking: 'Speaking…',
46
+ ending: 'Saving…',
47
+ ended: '',
48
+ stopped: 'The meeting stopped.',
49
+ };
50
+
51
+ export function ConversePage({ client, classNames, meeting, createIO, savedLink }: ConversePageProps) {
44
52
  const cx = (slot: ConverseSlot) => classNames?.[slot] ?? FALLBACK[slot];
45
- const [phase, setPhase] = React.useState<Phase>('idle');
46
- const [lines, setLines] = React.useState<Line[]>([]);
47
- const [error, setError] = React.useState<string | null>(null);
48
- const [saved, setSaved] = React.useState<ConverseEndResult | null>(null);
53
+ const [state, setState] = React.useState<MeetingState>(EMPTY);
54
+ const [startError, setStartError] = React.useState<string | null>(null);
49
55
  const [draft, setDraft] = React.useState('');
50
- const [retry, setRetry] = React.useState<Pending | null>(null);
51
- const [replyUrl, setReplyUrl] = React.useState<string | null>(null);
52
- const conversationId = React.useRef<string | undefined>(undefined);
53
- const audioRef = React.useRef<HTMLAudioElement | null>(null);
54
- const recorder = useRecorder({ mediaDevices, recorderFactory });
56
+ const ctl = React.useRef<MeetingController | null>(null);
57
+ const io = React.useRef<BrowserMeetingIO | null>(null);
55
58
  const endRef = React.useRef<HTMLDivElement | null>(null);
56
59
 
57
- React.useEffect(() => { endRef.current?.scrollIntoView?.({ block: 'end' }); }, [lines, phase]);
60
+ React.useEffect(() => { endRef.current?.scrollIntoView?.({ block: 'end' }); }, [state.lines, state.phase]);
61
+ React.useEffect(() => () => { void ctl.current?.end(); io.current?.close(); }, []);
58
62
 
59
- /** Called inside a tap: makes the one audio element allowed to play later, after the network call. */
60
- function unlockAudio() {
61
- if (!audioRef.current) audioRef.current = createAudio ? createAudio() : new Audio();
62
- const el = audioRef.current;
63
- el.src = SILENCE_WAV;
64
- void el.play()?.catch(() => undefined);
65
- }
66
-
67
- async function play(url: string) {
68
- const el = audioRef.current ?? (audioRef.current = createAudio ? createAudio() : new Audio());
69
- el.src = url;
70
- el.onended = () => setPhase((p) => (p === 'speaking' ? 'idle' : p));
71
- setPhase('speaking');
72
- try { await el.play(); } catch { setPhase('idle'); setError('The reply is ready but this browser would not play it. Tap Repeat.'); }
73
- }
63
+ const live = state.phase !== 'idle' && state.phase !== 'ended' && state.phase !== 'stopped';
74
64
 
75
- async function send(pending: Pending) {
76
- setPhase('sending');
77
- setError(null);
78
- setRetry(null);
65
+ /** `typing`: carry on without the microphone (the reason stays on screen) instead of refusing to start. */
66
+ async function onStart(typing = false) {
67
+ setStartError(null);
68
+ const browserIO = createIO ? createIO() : createBrowserMeetingIO({ resolveAudio: (u) => client.audioUrl(u) });
79
69
  try {
80
- const out = await client.turn({ audio: pending.blob, text: pending.text, conversationId: conversationId.current, turnId: pending.turnId });
81
- conversationId.current = out.conversation_id;
82
- setLines((l) => [...l, { role: 'user', text: out.transcript }, { role: 'assistant', text: out.reply_text }]);
83
- if (out.audio_url) {
84
- const url = await client.audioUrl(out.audio_url).catch(() => null);
85
- if (url) { setReplyUrl(url); await play(url); return; }
86
- }
87
- setReplyUrl(null);
88
- setPhase('idle');
70
+ await browserIO.open(); // inside the tap
89
71
  } catch (e) {
90
- setRetry(pending);
91
- setPhase('idle');
92
- setError(e instanceof ConverseClientError && e.retryable ? `${e.message} Try again.` : e instanceof Error ? e.message : 'That turn failed.');
72
+ setStartError(e instanceof Error ? e.message : 'Could not start.');
73
+ if (!typing) return;
93
74
  }
75
+ io.current = browserIO;
76
+ ctl.current = createMeetingController({ client, io: browserIO, config: meeting, onChange: setState });
77
+ setState({ ...EMPTY, phase: 'listening' });
78
+ ctl.current.start();
94
79
  }
95
80
 
96
- async function onTalk() {
97
- if (phase === 'recording') {
98
- const blob = await recorder.stop();
99
- if (!blob.size) { setPhase('idle'); setError('Nothing was recorded.'); return; }
100
- await send({ blob, turnId: freshId() });
101
- return;
102
- }
103
- if (phase !== 'idle' && phase !== 'speaking') return;
104
- audioRef.current?.pause();
105
- unlockAudio();
106
- setError(null);
107
- setSaved(null);
108
- try { await recorder.start(); setPhase('recording'); } catch (e) { setError(e instanceof Error ? e.message : 'Could not start recording.'); }
81
+ async function onEnd() {
82
+ await ctl.current?.end();
83
+ io.current?.close();
109
84
  }
110
85
 
111
86
  async function onSendText(event: React.FormEvent) {
112
87
  event.preventDefault();
113
88
  const text = draft.trim();
114
- if (!text || (phase !== 'idle' && phase !== 'speaking')) return;
115
- audioRef.current?.pause();
116
- unlockAudio();
89
+ if (!text) return;
117
90
  setDraft('');
118
- await send({ text, turnId: freshId() });
119
- }
120
-
121
- async function onEnd() {
122
- if (!conversationId.current) return;
123
- if (phase === 'recording') await recorder.stop();
124
- audioRef.current?.pause();
125
- setPhase('ending');
126
- setError(null);
127
- try {
128
- setSaved(await client.end(conversationId.current));
129
- conversationId.current = undefined;
130
- setLines([]);
131
- setReplyUrl(null);
132
- } catch (e) {
133
- setError(e instanceof Error ? e.message : 'Saving the conversation failed.');
134
- } finally {
135
- setPhase('idle');
136
- }
91
+ if (!ctl.current || !live) await onStart(true);
92
+ await ctl.current?.sendText(text);
137
93
  }
138
94
 
139
- const label = phase === 'recording' ? 'Tap to send' : phase === 'sending' ? 'Thinking…' : phase === 'speaking' ? 'Speaking… tap to talk' : phase === 'ending' ? 'Saving…' : 'Tap to talk';
95
+ const status = startError && live
96
+ ? 'No microphone, so typing only. Type below; the reply is spoken.'
97
+ : state.noAudio && state.lines.length && state.phase === 'listening'
98
+ ? `No spoken reply: ${state.noAudio}. The text is above. ${STATUS.listening}`
99
+ : STATUS[state.phase];
100
+ const hasReply = state.lines.some((l) => l.role === 'assistant');
140
101
 
141
102
  return (
142
103
  <div className={cx('root')}>
143
- <button
144
- type="button" onClick={onTalk} disabled={phase === 'sending' || phase === 'ending'}
145
- className={phase === 'recording' ? cx('talking') : cx('talk')} aria-pressed={phase === 'recording'} data-testid="converse-talk"
146
- >
147
- {label}
148
- </button>
149
- <p className={cx('muted')} role="status" aria-live="polite">
150
- {phase === 'recording' ? 'Listening. Tap again when you are done.' : phase === 'sending' ? 'Working on it…' : lines.length ? '' : 'Tap, say what you need, tap again. The answer plays by itself.'}
151
- </p>
152
- {error ? (
153
- <div className={cx('error')} role="alert">
154
- {error}
155
- {retry ? <> <button type="button" className={cx('secondary')} onClick={() => void send(retry)}>Try again</button></> : null}
156
- </div>
157
- ) : null}
104
+ {live ? (
105
+ <button type="button" onClick={() => void onEnd()} disabled={state.phase === 'ending'} className={cx('talking')} data-testid="converse-end">
106
+ {state.phase === 'ending' ? 'Saving…' : 'End and save'}
107
+ </button>
108
+ ) : (
109
+ <button type="button" onClick={() => void onStart()} className={cx('talk')} data-testid="converse-start">Start talking</button>
110
+ )}
111
+ <p className={cx('muted')} role="status" aria-live="polite" data-testid="converse-status">{status}</p>
112
+ {startError || state.error ? <div className={cx('error')} role="alert">{startError ?? state.error}</div> : null}
113
+ {live ? <p className={cx('muted')}>Keep this screen on: a web page cannot listen once the phone locks or you switch apps.</p> : null}
158
114
  <div className="flex gap-2">
159
- <button type="button" className={cx('secondary')} onClick={() => replyUrl && void play(replyUrl)} disabled={!replyUrl || phase === 'sending' || phase === 'recording'}>Repeat</button>
160
- <button type="button" className={cx('secondary')} onClick={() => void onEnd()} disabled={!lines.length || phase === 'sending' || phase === 'ending'}>End and save</button>
115
+ <button type="button" className={cx('secondary')} onClick={() => void ctl.current?.replay()} disabled={!hasReply || !live || state.phase === 'thinking'}>Play reply</button>
161
116
  </div>
162
117
  <ol className="space-y-2" aria-label="Conversation">
163
- {lines.map((line, i) => (
118
+ {state.lines.map((line, i) => (
164
119
  <li key={i} className={line.role === 'user' ? cx('bubbleUser') : cx('bubbleReply')}>
165
120
  <span className="sr-only">{line.role === 'user' ? 'You: ' : 'Tandem: '}</span>{line.text}
166
121
  </li>
167
122
  ))}
168
123
  </ol>
169
- {saved ? (
124
+ {state.saved ? (
170
125
  <p className={cx('muted')} role="status" data-testid="converse-saved">
171
- Saved {saved.turns} turn{saved.turns === 1 ? '' : 's'}. {savedLink?.(saved)}
126
+ Saved {state.saved.turns} turn{state.saved.turns === 1 ? '' : 's'}. {savedLink?.(state.saved)}
172
127
  </p>
173
128
  ) : null}
174
129
  <form onSubmit={onSendText} className="flex gap-2">
@@ -176,7 +131,7 @@ export function ConversePage({ client, classNames, mediaDevices, recorderFactory
176
131
  className={`${cx('input')} flex-1`} value={draft} onChange={(e) => setDraft(e.target.value)}
177
132
  placeholder="Or type it" aria-label="Type a message" enterKeyHint="send"
178
133
  />
179
- <button type="submit" className={cx('secondary')} disabled={!draft.trim() || (phase !== 'idle' && phase !== 'speaking')}>Send</button>
134
+ <button type="submit" className={cx('secondary')} disabled={!draft.trim()}>Send</button>
180
135
  </form>
181
136
  <div ref={endRef} />
182
137
  </div>
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The browser's half of the meeting: ONE open microphone stream and ONE <audio> element, both unlocked inside
3
+ * the Start tap (iOS only lets a gesture start them), then `listen` records one utterance per call using the
4
+ * shared end-of-speech detector, and `speak` plays a reply and resolves when it ends.
5
+ *
6
+ * The mic is only evaluated between replies, so Tandem's own voice is not heard as speech. With
7
+ * `interruptOnSpeech` a separate watcher stops the reply when the person talks over it.
8
+ */
9
+ import { createUtteranceDetector } from '../../../corpus/converse/vad';
10
+ import type { MeetingConfig } from '../../../corpus/converse/meeting-config';
11
+ import type { MeetingIO, MeetingReply } from '../../../corpus/converse/meeting';
12
+ import { pickMimeType } from '../VoiceRecordButton';
13
+ import { SILENCE_WAV } from './silence';
14
+
15
+ export interface LevelMeter { read(): number; close(): void }
16
+ const TICK_MS = 50;
17
+
18
+ export interface BrowserIOOptions {
19
+ mediaDevices?: Pick<MediaDevices, 'getUserMedia'>;
20
+ recorderFactory?: (stream: MediaStream, mimeType: string) => MediaRecorder;
21
+ /** Builds the mic level reader (RMS 0..1) for a stream. Default: Web Audio analyser. */
22
+ levelMeter?: (stream: MediaStream) => LevelMeter;
23
+ createAudio?: () => HTMLAudioElement;
24
+ /** Turns the reply's `audioUrl` (needs the bearer) into something an <audio> can play, e.g. an object URL. Default: the url itself. */
25
+ /** Screen Wake Lock (default: the browser's). Best effort: a refusal never blocks the meeting. */
26
+ wakeLock?: { request(type: 'screen'): Promise<{ release(): Promise<void> }> } | null;
27
+ resolveAudio?: (audioUrl: string) => Promise<string>;
28
+ now?: () => number;
29
+ setTimer?: (fn: () => void, ms: number) => ReturnType<typeof setInterval>;
30
+ clearTimer?: (id: ReturnType<typeof setInterval>) => void;
31
+ }
32
+
33
+ export interface BrowserMeetingIO extends MeetingIO {
34
+ /** Call inside the Start tap: opens the mic, resumes audio, unlocks playback. Throws a readable Error. */
35
+ open(): Promise<void>;
36
+ close(): void;
37
+ }
38
+
39
+ function webAudioMeter(stream: MediaStream): LevelMeter {
40
+ const Ctx: typeof AudioContext = (window as unknown as { AudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext }).AudioContext
41
+ ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
42
+ const ctx = new Ctx();
43
+ void ctx.resume();
44
+ const analyser = ctx.createAnalyser();
45
+ analyser.fftSize = 1024;
46
+ ctx.createMediaStreamSource(stream).connect(analyser);
47
+ const buf = new Float32Array(analyser.fftSize);
48
+ return {
49
+ read() {
50
+ analyser.getFloatTimeDomainData(buf);
51
+ let sum = 0;
52
+ for (let i = 0; i < buf.length; i += 1) sum += buf[i] * buf[i];
53
+ return Math.sqrt(sum / buf.length);
54
+ },
55
+ close() { void ctx.close(); },
56
+ };
57
+ }
58
+
59
+ export function createBrowserMeetingIO(options: BrowserIOOptions = {}): BrowserMeetingIO {
60
+ const now = options.now ?? (() => Date.now());
61
+ const setTimer = options.setTimer ?? ((fn, ms) => setInterval(fn, ms));
62
+ const clearTimer = options.clearTimer ?? ((id) => clearInterval(id));
63
+ let stream: MediaStream | null = null;
64
+ let meter: LevelMeter | null = null;
65
+ let audio: HTMLAudioElement | null = null;
66
+ let lock: { release(): Promise<void> } | null = null;
67
+ const wakeLock = () => (options.wakeLock !== undefined ? options.wakeLock : (typeof navigator !== 'undefined' ? (navigator as unknown as { wakeLock?: BrowserIOOptions['wakeLock'] }).wakeLock ?? null : null));
68
+ const holdScreen = async () => { try { lock = (await wakeLock()?.request('screen')) ?? null; } catch { lock = null; } };
69
+ const onVisible = () => { if (typeof document !== 'undefined' && document.visibilityState === 'visible' && stream && !lock) void holdScreen(); };
70
+
71
+ const newRecorder = (s: MediaStream) => {
72
+ const mimeType = pickMimeType((t) => typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(t));
73
+ return options.recorderFactory ? options.recorderFactory(s, mimeType) : new MediaRecorder(s, mimeType ? { mimeType } : undefined);
74
+ };
75
+
76
+ return {
77
+ async open() {
78
+ audio = options.createAudio ? options.createAudio() : new Audio();
79
+ audio.src = SILENCE_WAV;
80
+ void audio.play()?.catch(() => undefined);
81
+ const devices = options.mediaDevices ?? navigator.mediaDevices;
82
+ if (!devices?.getUserMedia) {
83
+ throw new Error(typeof window !== 'undefined' && !window.isSecureContext ? 'The microphone needs a secure (https) page.' : 'This browser cannot record audio.');
84
+ }
85
+ try {
86
+ stream = await devices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } as MediaTrackConstraints });
87
+ } catch (e) {
88
+ throw new Error(e instanceof Error && e.name === 'NotAllowedError' ? 'Microphone access was blocked. Allow it in the browser and try again.' : e instanceof Error ? e.message : 'Could not open the microphone.');
89
+ }
90
+ meter = (options.levelMeter ?? webAudioMeter)(stream);
91
+ await holdScreen();
92
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible);
93
+ },
94
+
95
+ close() {
96
+ meter?.close();
97
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible);
98
+ void lock?.release().catch(() => undefined);
99
+ lock = null;
100
+ stream?.getTracks().forEach((t) => t.stop());
101
+ audio?.pause();
102
+ meter = null; stream = null;
103
+ },
104
+
105
+ listen(signal, config: MeetingConfig) {
106
+ return new Promise((resolve) => {
107
+ if (!stream || !meter || signal.aborted) { resolve({ audio: null, cancelled: true }); return; }
108
+ const detector = createUtteranceDetector(config);
109
+ let recorder = newRecorder(stream);
110
+ let chunks: Blob[] = [];
111
+ let segmentStart = now();
112
+ let speaking = false;
113
+ const wire = (r: MediaRecorder) => { r.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); }; };
114
+ const begin = () => { chunks = []; recorder = newRecorder(stream as MediaStream); wire(recorder); recorder.start(1000); segmentStart = now(); };
115
+ wire(recorder);
116
+ recorder.start(1000);
117
+
118
+ const finish = (blobOut: Blob | null, cancelled = false) => {
119
+ clearTimer(timer);
120
+ signal.removeEventListener('abort', onAbort);
121
+ resolve(blobOut ? { audio: blobOut } : { audio: null, ...(cancelled ? { cancelled: true } : {}) });
122
+ };
123
+ const stopRecorder = (then: (blob: Blob) => void) => {
124
+ recorder.onstop = () => then(new Blob(chunks, { type: recorder.mimeType || 'audio/webm' }));
125
+ if (recorder.state !== 'inactive') recorder.stop(); else recorder.onstop?.(new Event('stop'));
126
+ };
127
+ const onAbort = () => stopRecorder(() => finish(null, true));
128
+ signal.addEventListener('abort', onAbort);
129
+
130
+ const timer = setTimer(() => {
131
+ const t = now();
132
+ const event = detector.feed((meter as LevelMeter).read(), t);
133
+ if (event?.type === 'start') speaking = true;
134
+ else if (event?.type === 'discard') { speaking = false; recorder.onstop = () => begin(); recorder.stop(); }
135
+ else if (event?.type === 'end') { clearTimer(timer); stopRecorder((blob) => finish(blob)); }
136
+ else if (!speaking && t - segmentStart >= config.idleRotateMs) { recorder.onstop = () => begin(); recorder.stop(); }
137
+ }, TICK_MS);
138
+ });
139
+ },
140
+
141
+ async speak(reply: MeetingReply, signal, config) {
142
+ let url = reply.audioUrl;
143
+ try { if (options.resolveAudio) url = await options.resolveAudio(reply.audioUrl); } catch { return; }
144
+ return new Promise<void>((resolve) => {
145
+ const el = audio;
146
+ if (!el || signal.aborted) { resolve(); return; }
147
+ let watch: ReturnType<typeof setInterval> | null = null;
148
+ const done = () => {
149
+ if (watch) clearTimer(watch);
150
+ signal.removeEventListener('abort', onAbort);
151
+ el.onended = null; el.onerror = null;
152
+ resolve();
153
+ };
154
+ const onAbort = () => { el.pause(); done(); };
155
+ signal.addEventListener('abort', onAbort);
156
+ el.onended = done;
157
+ el.onerror = () => done();
158
+ el.src = url;
159
+ void el.play().catch(() => done());
160
+ if (config.interruptOnSpeech && meter) {
161
+ const detector = createUtteranceDetector(config);
162
+ watch = setTimer(() => { if (detector.feed((meter as LevelMeter).read(), now())?.type === 'start') { el.pause(); done(); } }, TICK_MS);
163
+ }
164
+ });
165
+ },
166
+ };
167
+ }
@@ -26,6 +26,7 @@ const resultOf = (id: string, turn: ConverseTurn): ConverseTurnResult => ({
26
26
  transcript: turn.user.text,
27
27
  reply_text: turn.assistant.text,
28
28
  audio_url: turn.assistant.audio_ref ? turnAudioPath(id, turn.n) : null,
29
+ audio_reason: turn.assistant.audio_ref ? null : (turn.assistant.audio_reason ?? 'no audio was produced'),
29
30
  });
30
31
 
31
32
  function validate(req: ConverseTurnRequest) {
@@ -15,3 +15,9 @@ export { converseEnv } from './config';
15
15
  export { createConverseExtractor, parseExtract } from './extract';
16
16
  export type { ConverseExtract } from './extract';
17
17
  export { CANNOT_SEE } from './brain';
18
+ export { MEETING_DEFAULTS, resolveMeetingConfig } from './meeting-config';
19
+ export type { MeetingConfig } from './meeting-config';
20
+ export { createUtteranceDetector } from './vad';
21
+ export type { UtteranceDetector, UtteranceEvent } from './vad';
22
+ export { createMeetingController } from './meeting';
23
+ export type { ListenReason, MeetingApi, MeetingController, MeetingIO, MeetingLine, MeetingPhase, MeetingReply, MeetingState } from './meeting';
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Meeting-mode settings: CONFIGURATION with defaults, never hard-coded in a screen. Every value can be
3
+ * overridden by the app (props, env, a tenant setting); nonsense falls back to the default.
4
+ */
5
+ export interface MeetingConfig {
6
+ /** How long the voice must stay quiet before the utterance is over. */
7
+ silenceMs: number;
8
+ /** Shorter than this is a noise or a cough: dropped, not sent. */
9
+ minUtteranceMs: number;
10
+ /** Cut a monologue here and send it. */
11
+ maxUtteranceMs: number;
12
+ /** Mic level (0..1 RMS) that counts as speech. */
13
+ speechLevel: number;
14
+ /** The level must hold this long to count as the start of speech. */
15
+ speechStartMs: number;
16
+ /** Speaking during Tandem's reply stops the reply and listens. Default off: the mic ignores the speaker. */
17
+ interruptOnSpeech: boolean;
18
+ /** While nobody speaks, throw the recorded silence away this often so it never grows. */
19
+ idleRotateMs: number;
20
+ }
21
+
22
+ export const MEETING_DEFAULTS: MeetingConfig = {
23
+ silenceMs: 1200, minUtteranceMs: 400, maxUtteranceMs: 60_000, speechLevel: 0.02, speechStartMs: 150,
24
+ interruptOnSpeech: false, idleRotateMs: 30_000,
25
+ };
26
+
27
+ export function resolveMeetingConfig(over: Partial<MeetingConfig> = {}): MeetingConfig {
28
+ const out: MeetingConfig = { ...MEETING_DEFAULTS };
29
+ for (const key of ['silenceMs', 'minUtteranceMs', 'maxUtteranceMs', 'speechLevel', 'speechStartMs', 'idleRotateMs'] as const) {
30
+ const v = over[key];
31
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) out[key] = v;
32
+ }
33
+ if (typeof over.interruptOnSpeech === 'boolean') out.interruptOnSpeech = over.interruptOnSpeech;
34
+ return out;
35
+ }