@anna-ai/app-runtime 0.20.0 → 0.21.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/dist/index.js +659 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Anna App Runtime SDK — v0.
|
|
2
|
+
* Anna App Runtime SDK — v0.21.0
|
|
3
|
+
*
|
|
4
|
+
* v0.21.0 — App realtime voice session (design:
|
|
5
|
+
* app-realtime-voice-session-and-executa-transcribe.md §5.2 / §5.3, PB2).
|
|
6
|
+
* Adds `anna.audio.session(config)` → `VoiceSession` handle over the host
|
|
7
|
+
* bridge relay (`audio.session.*` are handled IN the host page, which owns
|
|
8
|
+
* the `wss://…/anna-apps/runtime/voice` socket — the iframe never holds a
|
|
9
|
+
* token nor opens a network connection). Full-duplex pipeline: streaming
|
|
10
|
+
* ASR → LLM (`llm: "agent"` = this app's agent session, or `"none"`) →
|
|
11
|
+
* streaming TTS with barge-in. Handle API: `sendAudio(pcm16)` (16 kHz
|
|
12
|
+
* mono; auto-chunked ≤ 32 KB, fire-and-forget), `flushAudio()` (push-to-talk
|
|
13
|
+
* released → finalize the pending sentence), `setContext(text)`
|
|
14
|
+
* (≤ 4 KB live context injected into the NEXT turn's system prompt — not
|
|
15
|
+
* into history), `say(text, {priority, interrupt})` (TTS-only, no LLM),
|
|
16
|
+
* `interrupt()`, `end()`; events `asr_partial | asr_final | llm_start |
|
|
17
|
+
* llm_partial | llm_done | tts_audio | tts_done | interrupted | say_start |
|
|
18
|
+
* say_done | context_updated | asr_paused | asr_resumed | quota_warning |
|
|
19
|
+
* error | ended` (the host pauses ASR after `asrIdleTimeoutSec` without
|
|
20
|
+
* audio and reconnects on the next frame — push-to-talk is safe). Pure
|
|
21
|
+
* client helpers `anna.audio.mic({sampleRate})` (AudioWorklet 16 kHz PCM16
|
|
22
|
+
* capture, ScriptProcessor fallback) and `anna.audio.player({sampleRate})`
|
|
23
|
+
* (gapless 24 kHz PCM queue) share ONE source with the dashboard main-chat
|
|
24
|
+
* voice call (`static/js/anna-voice-client-core.js`, embedded below).
|
|
25
|
+
* Requires manifest `ui.host_api.audio ∋ "session"` (implies the outer
|
|
26
|
+
* iframe gets `allow="microphone"`) + user `media_grant.audio.{speak,
|
|
27
|
+
* transcribe}`; `llm:"agent"` additionally needs `host_api.agent.session`.
|
|
28
|
+
* Hosts without the relay reply `unknown_method`/`not_supported`.
|
|
29
|
+
* Additive — `audio.speak` / `audio.transcribe` unchanged.
|
|
3
30
|
*
|
|
4
31
|
* v0.20.0 — Media generation surface (design:
|
|
5
32
|
* platform-media-generation-video-audio.md §7/§9/§10).
|
|
@@ -741,6 +768,620 @@
|
|
|
741
768
|
// for await (const ev of sess.run({ content: "hi" })) {
|
|
742
769
|
// if (ev.event === "model_token") render(ev.text);
|
|
743
770
|
// }
|
|
771
|
+
// ==== BEGIN anna-voice-client-core ====
|
|
772
|
+
var AnnaVoiceClientCore = (function () {
|
|
773
|
+
"use strict";
|
|
774
|
+
|
|
775
|
+
const VERSION = "1.0.0";
|
|
776
|
+
const DEFAULT_MIC_SAMPLE_RATE = 16000;
|
|
777
|
+
const DEFAULT_FRAME_SIZE = 4096; // samples → 256 ms @ 16 kHz, 8 KB PCM16
|
|
778
|
+
const MAX_CHUNK_BYTES = 32 * 1024; // server-side single audio_data cap
|
|
779
|
+
|
|
780
|
+
// ───────────────────────── PCM / base64 helpers ─────────────────────────
|
|
781
|
+
|
|
782
|
+
/** Float32 [-1,1] → Int16 LE (clamped). */
|
|
783
|
+
function float32ToPcm16(float32) {
|
|
784
|
+
const out = new Int16Array(float32.length);
|
|
785
|
+
for (let i = 0; i < float32.length; i++) {
|
|
786
|
+
const s = Math.max(-1, Math.min(1, float32[i]));
|
|
787
|
+
out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
|
|
788
|
+
}
|
|
789
|
+
return out;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** Uint8Array → base64 (chunked String.fromCharCode to avoid arg limits). */
|
|
793
|
+
function bytesToBase64(bytes) {
|
|
794
|
+
let binary = "";
|
|
795
|
+
const STEP = 0x8000;
|
|
796
|
+
for (let i = 0; i < bytes.length; i += STEP) {
|
|
797
|
+
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + STEP));
|
|
798
|
+
}
|
|
799
|
+
return btoa(binary);
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** Int16Array | ArrayBuffer | Uint8Array → base64 of the raw little-endian bytes. */
|
|
803
|
+
function pcm16ToBase64(pcm) {
|
|
804
|
+
const bytes =
|
|
805
|
+
pcm instanceof Uint8Array
|
|
806
|
+
? pcm
|
|
807
|
+
: pcm instanceof ArrayBuffer
|
|
808
|
+
? new Uint8Array(pcm)
|
|
809
|
+
: new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength);
|
|
810
|
+
return bytesToBase64(bytes);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** base64 → Uint8Array. */
|
|
814
|
+
function base64ToBytes(b64) {
|
|
815
|
+
const binary = atob(b64);
|
|
816
|
+
const bytes = new Uint8Array(binary.length);
|
|
817
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
818
|
+
return bytes;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* Split PCM16 into ≤ `maxBytes` slices (even byte boundary) and base64 each.
|
|
823
|
+
* Returns `string[]`; an empty input yields `[]`.
|
|
824
|
+
*/
|
|
825
|
+
function chunkPcm16(pcm, maxBytes = MAX_CHUNK_BYTES) {
|
|
826
|
+
const bytes =
|
|
827
|
+
pcm instanceof Uint8Array
|
|
828
|
+
? pcm
|
|
829
|
+
: pcm instanceof ArrayBuffer
|
|
830
|
+
? new Uint8Array(pcm)
|
|
831
|
+
: new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength);
|
|
832
|
+
const step = Math.max(2, maxBytes - (maxBytes % 2));
|
|
833
|
+
const out = [];
|
|
834
|
+
for (let i = 0; i < bytes.length; i += step) {
|
|
835
|
+
out.push(bytesToBase64(bytes.subarray(i, Math.min(i + step, bytes.length))));
|
|
836
|
+
}
|
|
837
|
+
return out;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// ───────────────────────── MicCapture ─────────────────────────
|
|
841
|
+
|
|
842
|
+
// AudioWorkletProcessor source. Accumulates 128-frame render quanta into
|
|
843
|
+
// `frameSize` samples and posts one Float32Array per frame.
|
|
844
|
+
const WORKLET_SOURCE = `
|
|
845
|
+
class AnnaPcmCaptureProcessor extends AudioWorkletProcessor {
|
|
846
|
+
constructor(options) {
|
|
847
|
+
super();
|
|
848
|
+
const fs = (options && options.processorOptions && options.processorOptions.frameSize) || 4096;
|
|
849
|
+
this._fs = fs;
|
|
850
|
+
this._buf = new Float32Array(fs);
|
|
851
|
+
this._pos = 0;
|
|
852
|
+
}
|
|
853
|
+
process(inputs) {
|
|
854
|
+
const ch = inputs[0] && inputs[0][0];
|
|
855
|
+
if (!ch) return true;
|
|
856
|
+
let i = 0;
|
|
857
|
+
while (i < ch.length) {
|
|
858
|
+
const n = Math.min(ch.length - i, this._buf.length - this._pos);
|
|
859
|
+
this._buf.set(ch.subarray(i, i + n), this._pos);
|
|
860
|
+
this._pos += n; i += n;
|
|
861
|
+
if (this._pos === this._buf.length) {
|
|
862
|
+
const out = this._buf;
|
|
863
|
+
this.port.postMessage(out, [out.buffer]);
|
|
864
|
+
// out is detached after the transfer (length 0) — never size the
|
|
865
|
+
// next buffer from it, or process() spins forever on a 0-length buf.
|
|
866
|
+
this._buf = new Float32Array(this._fs);
|
|
867
|
+
this._pos = 0;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return true;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
registerProcessor("anna-pcm-capture", AnnaPcmCaptureProcessor);
|
|
874
|
+
`;
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* Microphone → PCM16 frames.
|
|
878
|
+
*
|
|
879
|
+
* const mic = new MicCapture({ onChunk(pcm16, float32) { ... } });
|
|
880
|
+
* await mic.start(); // prompts for permission
|
|
881
|
+
* mic.setMuted(true); // keeps the stream, stops emitting
|
|
882
|
+
* mic.analyser // AnalyserNode (fftSize 256) for visualizers
|
|
883
|
+
* mic.stop(); // releases tracks + closes the AudioContext
|
|
884
|
+
*
|
|
885
|
+
* `onChunk(pcm16: Int16Array, float32: Float32Array)` fires once per
|
|
886
|
+
* `frameSize` samples at `sampleRate`. `onLevel(rms)` is optional cheap VAD
|
|
887
|
+
* input (RMS of the frame). Errors from the browser surface via `onError`
|
|
888
|
+
* and the rejected `start()` promise.
|
|
889
|
+
*/
|
|
890
|
+
class MicCapture {
|
|
891
|
+
constructor(opts = {}) {
|
|
892
|
+
this.sampleRate = opts.sampleRate || DEFAULT_MIC_SAMPLE_RATE;
|
|
893
|
+
this.frameSize = opts.frameSize || DEFAULT_FRAME_SIZE;
|
|
894
|
+
this.onChunk = opts.onChunk || null;
|
|
895
|
+
this.onLevel = opts.onLevel || null;
|
|
896
|
+
this.onError = opts.onError || null;
|
|
897
|
+
this.preferWorklet = opts.preferWorklet !== false;
|
|
898
|
+
this.constraints = opts.constraints || {
|
|
899
|
+
echoCancellation: true,
|
|
900
|
+
noiseSuppression: true,
|
|
901
|
+
autoGainControl: true,
|
|
902
|
+
};
|
|
903
|
+
this.stream = null;
|
|
904
|
+
this.ctx = null;
|
|
905
|
+
this.analyser = null;
|
|
906
|
+
this.muted = false;
|
|
907
|
+
this.active = false;
|
|
908
|
+
this.mode = null; // "worklet" | "script"
|
|
909
|
+
this._source = null;
|
|
910
|
+
this._node = null;
|
|
911
|
+
this._workletUrl = null;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
async start() {
|
|
915
|
+
if (this.active) return this;
|
|
916
|
+
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
|
917
|
+
// `navigator.mediaDevices` is [SecureContext]-only: on http://<lan-ip>
|
|
918
|
+
// (RN dev builds, LAN testing) it is simply undefined. Say so, instead
|
|
919
|
+
// of a generic "not available" that reads like a missing device.
|
|
920
|
+
const insecure = typeof window !== "undefined" && window.isSecureContext === false;
|
|
921
|
+
throw new Error(
|
|
922
|
+
insecure
|
|
923
|
+
? "getUserMedia unavailable: insecure context (page must be served over https or from localhost)"
|
|
924
|
+
: "getUserMedia not available"
|
|
925
|
+
);
|
|
926
|
+
}
|
|
927
|
+
this.stream = await navigator.mediaDevices.getUserMedia({
|
|
928
|
+
audio: Object.assign({ sampleRate: this.sampleRate }, this.constraints),
|
|
929
|
+
});
|
|
930
|
+
try {
|
|
931
|
+
const Ctx = window.AudioContext || window.webkitAudioContext;
|
|
932
|
+
this.ctx = new Ctx({ sampleRate: this.sampleRate });
|
|
933
|
+
if (this.ctx.state === "suspended") {
|
|
934
|
+
try { await this.ctx.resume(); } catch (_) {}
|
|
935
|
+
}
|
|
936
|
+
this._source = this.ctx.createMediaStreamSource(this.stream);
|
|
937
|
+
this.analyser = this.ctx.createAnalyser();
|
|
938
|
+
this.analyser.fftSize = 256;
|
|
939
|
+
this.analyser.smoothingTimeConstant = 0.7;
|
|
940
|
+
this._source.connect(this.analyser);
|
|
941
|
+
|
|
942
|
+
let ok = false;
|
|
943
|
+
if (this.preferWorklet && this.ctx.audioWorklet && typeof Blob !== "undefined") {
|
|
944
|
+
ok = await this._startWorklet();
|
|
945
|
+
}
|
|
946
|
+
if (!ok) this._startScriptProcessor();
|
|
947
|
+
} catch (e) {
|
|
948
|
+
// Never leave the mic indicator on after a failed start.
|
|
949
|
+
this.stop();
|
|
950
|
+
throw e;
|
|
951
|
+
}
|
|
952
|
+
this.active = true;
|
|
953
|
+
return this;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
async _startWorklet() {
|
|
957
|
+
try {
|
|
958
|
+
this._workletUrl = URL.createObjectURL(
|
|
959
|
+
new Blob([WORKLET_SOURCE], { type: "application/javascript" })
|
|
960
|
+
);
|
|
961
|
+
await this.ctx.audioWorklet.addModule(this._workletUrl);
|
|
962
|
+
const node = new AudioWorkletNode(this.ctx, "anna-pcm-capture", {
|
|
963
|
+
numberOfInputs: 1,
|
|
964
|
+
numberOfOutputs: 0,
|
|
965
|
+
channelCount: 1,
|
|
966
|
+
processorOptions: { frameSize: this.frameSize },
|
|
967
|
+
});
|
|
968
|
+
node.port.onmessage = (ev) => this._emit(ev.data);
|
|
969
|
+
this._source.connect(node);
|
|
970
|
+
this._node = node;
|
|
971
|
+
this.mode = "worklet";
|
|
972
|
+
return true;
|
|
973
|
+
} catch (e) {
|
|
974
|
+
// CSP without blob: workers, old WebViews, … → ScriptProcessor.
|
|
975
|
+
if (this._workletUrl) { try { URL.revokeObjectURL(this._workletUrl); } catch (_) {} }
|
|
976
|
+
this._workletUrl = null;
|
|
977
|
+
return false;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
_startScriptProcessor() {
|
|
982
|
+
const node = this.ctx.createScriptProcessor(this.frameSize, 1, 1);
|
|
983
|
+
node.onaudioprocess = (e) => {
|
|
984
|
+
// Copy: the input buffer is reused by the engine.
|
|
985
|
+
this._emit(new Float32Array(e.inputBuffer.getChannelData(0)));
|
|
986
|
+
};
|
|
987
|
+
this._source.connect(node);
|
|
988
|
+
node.connect(this.ctx.destination); // required for onaudioprocess to fire
|
|
989
|
+
this._node = node;
|
|
990
|
+
this.mode = "script";
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
_emit(float32) {
|
|
994
|
+
if (!this.active || this.muted) return;
|
|
995
|
+
if (this.onLevel) {
|
|
996
|
+
let sumSq = 0;
|
|
997
|
+
for (let i = 0; i < float32.length; i++) sumSq += float32[i] * float32[i];
|
|
998
|
+
try { this.onLevel(Math.sqrt(sumSq / (float32.length || 1)), float32); } catch (e) { this._err(e); }
|
|
999
|
+
}
|
|
1000
|
+
if (this.onChunk) {
|
|
1001
|
+
try { this.onChunk(float32ToPcm16(float32), float32); } catch (e) { this._err(e); }
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
_err(e) {
|
|
1006
|
+
if (this.onError) { try { this.onError(e); } catch (_) {} }
|
|
1007
|
+
else console.warn("[anna-voice-core] MicCapture handler error", e);
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** Mute keeps the track live (fast unmute) but stops emitting frames. */
|
|
1011
|
+
setMuted(muted) {
|
|
1012
|
+
this.muted = !!muted;
|
|
1013
|
+
if (this.stream) this.stream.getAudioTracks().forEach((t) => { t.enabled = !this.muted; });
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
stop() {
|
|
1017
|
+
this.active = false;
|
|
1018
|
+
if (this._node) {
|
|
1019
|
+
try { this._node.disconnect(); } catch (_) {}
|
|
1020
|
+
if (this._node.port) this._node.port.onmessage = null;
|
|
1021
|
+
this._node = null;
|
|
1022
|
+
}
|
|
1023
|
+
if (this._source) { try { this._source.disconnect(); } catch (_) {} this._source = null; }
|
|
1024
|
+
if (this.stream) { this.stream.getTracks().forEach((t) => t.stop()); this.stream = null; }
|
|
1025
|
+
if (this.ctx) { this.ctx.close().catch(() => {}); this.ctx = null; }
|
|
1026
|
+
if (this._workletUrl) { try { URL.revokeObjectURL(this._workletUrl); } catch (_) {} this._workletUrl = null; }
|
|
1027
|
+
this.analyser = null;
|
|
1028
|
+
this.muted = false;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
// ───────────────────────── VoiceAudioPlayer ─────────────────────────
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Gapless audio player for streamed TTS. Sample-accurate
|
|
1036
|
+
* AudioBufferSourceNode scheduling eliminates gaps between chunks.
|
|
1037
|
+
* Supports PCM (Int16 LE) and MP3 with a small jitter buffer.
|
|
1038
|
+
*
|
|
1039
|
+
* const player = new VoiceAudioPlayer({ sampleRate: 24000 });
|
|
1040
|
+
* player.onPlaybackEnd = () => ...;
|
|
1041
|
+
* player.enqueue(base64Chunk); // per tts_audio
|
|
1042
|
+
* player.flush(); // on tts_done
|
|
1043
|
+
* player.stop(); // on interrupted / barge-in
|
|
1044
|
+
*/
|
|
1045
|
+
class VoiceAudioPlayer {
|
|
1046
|
+
constructor(opts = {}) {
|
|
1047
|
+
this.ctx = null;
|
|
1048
|
+
this.nextPlayTime = 0;
|
|
1049
|
+
this.pendingChunks = []; // jitter buffer
|
|
1050
|
+
this.started = false;
|
|
1051
|
+
this.playing = false;
|
|
1052
|
+
this.activeSources = []; // scheduled sources (for stop)
|
|
1053
|
+
this.onPlaybackEnd = opts.onPlaybackEnd || null;
|
|
1054
|
+
this.format = opts.format || "pcm";
|
|
1055
|
+
this.sampleRate = opts.sampleRate || 24000;
|
|
1056
|
+
this.channels = opts.channels || 1;
|
|
1057
|
+
this.JITTER_CHUNKS = opts.jitterChunks || 3;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/** Apply `session_started.audio_config` ({format, sample_rate, channels}). */
|
|
1061
|
+
configure(config) {
|
|
1062
|
+
if (!config) return;
|
|
1063
|
+
if (config.format) this.format = config.format;
|
|
1064
|
+
if (config.sample_rate) this.sampleRate = config.sample_rate;
|
|
1065
|
+
if (config.sampleRate) this.sampleRate = config.sampleRate;
|
|
1066
|
+
if (config.channels) this.channels = config.channels;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
_ensureContext() {
|
|
1070
|
+
if (!this.ctx || this.ctx.state === "closed") {
|
|
1071
|
+
this.ctx = new (window.AudioContext || window.webkitAudioContext)();
|
|
1072
|
+
}
|
|
1073
|
+
if (this.ctx.state === "suspended") this.ctx.resume();
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
_decodePCM(base64Data) {
|
|
1077
|
+
const bytes = base64ToBytes(base64Data);
|
|
1078
|
+
const int16 = new Int16Array(bytes.buffer, 0, bytes.byteLength >> 1);
|
|
1079
|
+
const float32 = new Float32Array(int16.length);
|
|
1080
|
+
for (let i = 0; i < int16.length; i++) float32[i] = int16[i] / 32768;
|
|
1081
|
+
return float32;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
_onSourceEnded(source) {
|
|
1085
|
+
const idx = this.activeSources.indexOf(source);
|
|
1086
|
+
if (idx !== -1) this.activeSources.splice(idx, 1);
|
|
1087
|
+
if (this.activeSources.length === 0 && this.pendingChunks.length === 0) {
|
|
1088
|
+
this.playing = false;
|
|
1089
|
+
if (this.onPlaybackEnd) this.onPlaybackEnd();
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
_scheduleBuffer(buffer) {
|
|
1094
|
+
const source = this.ctx.createBufferSource();
|
|
1095
|
+
source.buffer = buffer;
|
|
1096
|
+
source.connect(this.ctx.destination);
|
|
1097
|
+
const startTime = Math.max(this.nextPlayTime, this.ctx.currentTime);
|
|
1098
|
+
source.start(startTime);
|
|
1099
|
+
this.nextPlayTime = startTime + buffer.duration;
|
|
1100
|
+
this.activeSources.push(source);
|
|
1101
|
+
source.onended = () => this._onSourceEnded(source);
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
_scheduleFloat32(float32Data) {
|
|
1105
|
+
this._ensureContext();
|
|
1106
|
+
const buffer = this.ctx.createBuffer(this.channels, float32Data.length, this.sampleRate);
|
|
1107
|
+
buffer.copyToChannel(float32Data, 0);
|
|
1108
|
+
this._scheduleBuffer(buffer);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
_scheduleMP3(base64Data) {
|
|
1112
|
+
this._ensureContext();
|
|
1113
|
+
const bytes = base64ToBytes(base64Data);
|
|
1114
|
+
this.ctx
|
|
1115
|
+
.decodeAudioData(bytes.buffer.slice(0))
|
|
1116
|
+
.then((audioBuffer) => this._scheduleBuffer(audioBuffer))
|
|
1117
|
+
.catch((err) => console.warn("VoiceAudioPlayer: MP3 decode error, skipping chunk", err));
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
_flushPending() {
|
|
1121
|
+
this.started = true;
|
|
1122
|
+
this.playing = true;
|
|
1123
|
+
this._ensureContext();
|
|
1124
|
+
this.nextPlayTime = this.ctx.currentTime + 0.05; // jitter headroom
|
|
1125
|
+
const chunks = this.pendingChunks.splice(0);
|
|
1126
|
+
for (const chunk of chunks) this._scheduleChunk(chunk);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
_scheduleChunk(base64Audio) {
|
|
1130
|
+
if (this.format === "pcm") this._scheduleFloat32(this._decodePCM(base64Audio));
|
|
1131
|
+
else this._scheduleMP3(base64Audio);
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
/** Enqueue a base64 audio chunk (jitter-buffered until JITTER_CHUNKS). */
|
|
1135
|
+
enqueue(base64Audio) {
|
|
1136
|
+
if (!base64Audio) return;
|
|
1137
|
+
if (!this.started) {
|
|
1138
|
+
this.pendingChunks.push(base64Audio);
|
|
1139
|
+
if (this.pendingChunks.length >= this.JITTER_CHUNKS) this._flushPending();
|
|
1140
|
+
} else {
|
|
1141
|
+
this.playing = true;
|
|
1142
|
+
this._scheduleChunk(base64Audio);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/** Flush the jitter buffer (call when the TTS stream ends). */
|
|
1147
|
+
flush() {
|
|
1148
|
+
if (this.pendingChunks.length > 0) this._flushPending();
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/** Stop everything immediately (barge-in / interrupt). */
|
|
1152
|
+
stop() {
|
|
1153
|
+
for (const source of this.activeSources) {
|
|
1154
|
+
try { source.onended = null; source.stop(); } catch (_) {}
|
|
1155
|
+
}
|
|
1156
|
+
this.activeSources = [];
|
|
1157
|
+
this.pendingChunks = [];
|
|
1158
|
+
this.started = false;
|
|
1159
|
+
this.playing = false;
|
|
1160
|
+
this.nextPlayTime = 0;
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
/** Full cleanup (closes the AudioContext). */
|
|
1164
|
+
destroy() {
|
|
1165
|
+
this.stop();
|
|
1166
|
+
if (this.ctx) { this.ctx.close().catch(() => {}); this.ctx = null; }
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
get isPlaying() {
|
|
1170
|
+
return this.playing;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
return {
|
|
1175
|
+
VERSION,
|
|
1176
|
+
DEFAULT_MIC_SAMPLE_RATE,
|
|
1177
|
+
DEFAULT_FRAME_SIZE,
|
|
1178
|
+
MAX_CHUNK_BYTES,
|
|
1179
|
+
float32ToPcm16,
|
|
1180
|
+
bytesToBase64,
|
|
1181
|
+
pcm16ToBase64,
|
|
1182
|
+
base64ToBytes,
|
|
1183
|
+
chunkPcm16,
|
|
1184
|
+
MicCapture,
|
|
1185
|
+
VoiceAudioPlayer,
|
|
1186
|
+
};
|
|
1187
|
+
})();
|
|
1188
|
+
// ==== END anna-voice-client-core ====
|
|
1189
|
+
|
|
1190
|
+
// ───────────────────────── audio namespace (v0.21.0) ─────────────────────────
|
|
1191
|
+
|
|
1192
|
+
const VOICE_SESSION_EVENTS = new Set([
|
|
1193
|
+
"asr_partial", "asr_final", "llm_start", "llm_partial", "llm_done",
|
|
1194
|
+
"tts_audio", "tts_done", "interrupted", "say_start", "say_done",
|
|
1195
|
+
"context_updated", "quota_warning", "error", "session_ended",
|
|
1196
|
+
"asr_paused", "asr_resumed",
|
|
1197
|
+
]);
|
|
1198
|
+
const VOICE_MAX_CONTEXT_CHARS = 4 * 1024;
|
|
1199
|
+
const VOICE_MAX_SAY_CHARS = 1000;
|
|
1200
|
+
|
|
1201
|
+
/**
|
|
1202
|
+
* App realtime voice session handle (design §5.2). Obtained via
|
|
1203
|
+
* `await anna.audio.session({...})`; the host bridge owns the WebSocket.
|
|
1204
|
+
*
|
|
1205
|
+
* const vs = await anna.audio.session({ llm: "agent", context: "..." });
|
|
1206
|
+
* vs.on("asr_final", ({text}) => ...);
|
|
1207
|
+
* vs.on("tts_audio", ({audio}) => player.enqueue(audio));
|
|
1208
|
+
* vs.on("tts_done", () => player.flush());
|
|
1209
|
+
* vs.on("interrupted", () => player.stop());
|
|
1210
|
+
* mic.onChunk = (pcm16) => vs.sendAudio(pcm16); // push-to-talk: only while pressed!
|
|
1211
|
+
* vs.setContext("hp=30% gold=1200"); // replaces; next turn
|
|
1212
|
+
* await vs.say("小心上路", { priority: "high" }); // TTS-only, preempts
|
|
1213
|
+
* await vs.end();
|
|
1214
|
+
*
|
|
1215
|
+
* ASR is billed per second of audio you send — gate `sendAudio` behind
|
|
1216
|
+
* push-to-talk / a wake word instead of streaming continuously.
|
|
1217
|
+
*/
|
|
1218
|
+
class VoiceSession {
|
|
1219
|
+
constructor(rt, info) {
|
|
1220
|
+
this._rt = rt;
|
|
1221
|
+
this.sessionId = info.sessionId || null;
|
|
1222
|
+
this.audioConfig = info.audio_config || null;
|
|
1223
|
+
this.models = info.models || null;
|
|
1224
|
+
this.maxDurationSec = info.max_duration_sec ?? null;
|
|
1225
|
+
// Host pauses the ASR connection after this many idle seconds (no
|
|
1226
|
+
// sendAudio); the next frame reconnects transparently (`asr_paused` /
|
|
1227
|
+
// `asr_resumed` events). Expect the first word after a long pause to be
|
|
1228
|
+
// ~0.3–0.6 s slower. null on hosts without idle management.
|
|
1229
|
+
this.asrIdleTimeoutSec = info.asr_idle_timeout_sec ?? null;
|
|
1230
|
+
this.ended = false;
|
|
1231
|
+
this.usage = null;
|
|
1232
|
+
this._handlers = new Map();
|
|
1233
|
+
this._endResolvers = [];
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
on(event, fn) {
|
|
1237
|
+
let set = this._handlers.get(event);
|
|
1238
|
+
if (!set) { set = new Set(); this._handlers.set(event, set); }
|
|
1239
|
+
set.add(fn);
|
|
1240
|
+
return () => set.delete(fn);
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
off(event, fn) {
|
|
1244
|
+
const set = this._handlers.get(event);
|
|
1245
|
+
if (set) set.delete(fn);
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
_emit(event, payload) {
|
|
1249
|
+
const set = this._handlers.get(event);
|
|
1250
|
+
if (set) for (const fn of set) try { fn(payload); } catch (e) { console.warn("[anna-sdk] voice handler threw", e); }
|
|
1251
|
+
const all = this._handlers.get("*");
|
|
1252
|
+
if (all) for (const fn of all) try { fn(event, payload); } catch (_) {}
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
/** Bridge → SDK dispatch (payload = raw server event + sessionId). */
|
|
1256
|
+
_dispatch(payload) {
|
|
1257
|
+
if (this.ended) return;
|
|
1258
|
+
const type = payload.type;
|
|
1259
|
+
if (type === "session_ended") {
|
|
1260
|
+
this.ended = true;
|
|
1261
|
+
this.usage = {
|
|
1262
|
+
duration: payload.duration ?? null,
|
|
1263
|
+
total_asr_seconds: payload.total_asr_seconds ?? null,
|
|
1264
|
+
total_tts_characters: payload.total_tts_characters ?? null,
|
|
1265
|
+
reason: payload.reason || null,
|
|
1266
|
+
};
|
|
1267
|
+
this._emit("ended", Object.assign({ sessionId: this.sessionId }, this.usage));
|
|
1268
|
+
for (const r of this._endResolvers.splice(0)) r(this.usage);
|
|
1269
|
+
this._rt._voiceSessions.delete(this.sessionId || "__single__");
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
if (!VOICE_SESSION_EVENTS.has(type)) return; // forward-compat: ignore unknown
|
|
1273
|
+
this._emit(type, payload);
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* Send 16 kHz mono PCM16 (`Int16Array` | `ArrayBuffer` | `Uint8Array`).
|
|
1278
|
+
* Auto-chunked to ≤ 32 KB; fire-and-forget (no per-chunk round trip).
|
|
1279
|
+
* Returns the number of chunks posted.
|
|
1280
|
+
*/
|
|
1281
|
+
sendAudio(pcm16) {
|
|
1282
|
+
if (this.ended || !pcm16) return 0;
|
|
1283
|
+
const chunks = AnnaVoiceClientCore.chunkPcm16(pcm16);
|
|
1284
|
+
for (const b64 of chunks) {
|
|
1285
|
+
this._rt._post({
|
|
1286
|
+
kind: "req",
|
|
1287
|
+
id: uuid(),
|
|
1288
|
+
ns: "audio",
|
|
1289
|
+
method: "session.send",
|
|
1290
|
+
args: { sessionId: this.sessionId, audio_b64: b64 },
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
return chunks.length;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* Signal end of the current utterance (push-to-talk released). Streaming
|
|
1298
|
+
* ASR only finalizes a sentence after enough trailing *silence frames*;
|
|
1299
|
+
* once you stop calling `sendAudio` the pending sentence would never
|
|
1300
|
+
* finalize — `flushAudio()` asks the host to finalize it now
|
|
1301
|
+
* (`asr_final` follows, then `asr_paused{reason:"flushed"}`; the next
|
|
1302
|
+
* `sendAudio` reconnects transparently). Fire-and-forget.
|
|
1303
|
+
*/
|
|
1304
|
+
flushAudio() {
|
|
1305
|
+
if (this.ended) return;
|
|
1306
|
+
this._rt._post({ kind: "req", id: uuid(), ns: "audio", method: "session.flush", args: { sessionId: this.sessionId } });
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/** Replace the live context (≤ 4 KB); takes effect from the next utterance. */
|
|
1310
|
+
setContext(text) {
|
|
1311
|
+
const t = text == null ? "" : String(text);
|
|
1312
|
+
if (t.length > VOICE_MAX_CONTEXT_CHARS) {
|
|
1313
|
+
return Promise.reject(Object.assign(new Error(`context exceeds ${VOICE_MAX_CONTEXT_CHARS} chars`), { code: "context_too_large" }));
|
|
1314
|
+
}
|
|
1315
|
+
return this._rt.call("audio", "session.context", { sessionId: this.sessionId, text: t });
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* Speak `text` through the session's streaming TTS without the LLM.
|
|
1320
|
+
* `priority:"high"` or `interrupt:true` preempts the current reply;
|
|
1321
|
+
* `"normal"` queues in the server's single pending slot (newer replaces
|
|
1322
|
+
* older — `say_done{status:"replaced"}`). Resolves `{sayId}` once queued;
|
|
1323
|
+
* listen to `say_start` / `say_done` for playback lifecycle.
|
|
1324
|
+
*/
|
|
1325
|
+
say(text, opts = {}) {
|
|
1326
|
+
const t = text == null ? "" : String(text);
|
|
1327
|
+
if (!t.trim()) return Promise.reject(Object.assign(new Error("say: text required"), { code: "invalid_request" }));
|
|
1328
|
+
if (t.length > VOICE_MAX_SAY_CHARS) {
|
|
1329
|
+
return Promise.reject(Object.assign(new Error(`say exceeds ${VOICE_MAX_SAY_CHARS} chars`), { code: "say_too_long" }));
|
|
1330
|
+
}
|
|
1331
|
+
return this._rt
|
|
1332
|
+
.call("audio", "session.say", {
|
|
1333
|
+
sessionId: this.sessionId,
|
|
1334
|
+
text: t,
|
|
1335
|
+
priority: opts.priority || "normal",
|
|
1336
|
+
interrupt: !!opts.interrupt,
|
|
1337
|
+
say_id: opts.sayId || opts.say_id || undefined,
|
|
1338
|
+
})
|
|
1339
|
+
.then((r) => ({ sayId: r && r.sayId }));
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
/** Stop the current LLM reply + TTS playback server-side. */
|
|
1343
|
+
interrupt() {
|
|
1344
|
+
return this._rt.call("audio", "session.interrupt", { sessionId: this.sessionId });
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
/** End the session; resolves with the usage summary (`session_ended`). */
|
|
1348
|
+
end() {
|
|
1349
|
+
if (this.ended) return Promise.resolve(this.usage);
|
|
1350
|
+
if (this._ending) return this._ending; // concurrent end() share one close
|
|
1351
|
+
this._ending = (async () => {
|
|
1352
|
+
const done = new Promise((resolve) => this._endResolvers.push(resolve));
|
|
1353
|
+
const res = await this._rt.call("audio", "session.close", { sessionId: this.sessionId }, { timeoutMs: 10000 });
|
|
1354
|
+
if (!this.ended) {
|
|
1355
|
+
// Bridge timed out waiting for session_ended — synthesize from the close reply.
|
|
1356
|
+
this._dispatch(Object.assign({ type: "session_ended", reason: "closed" }, res || {}));
|
|
1357
|
+
}
|
|
1358
|
+
return done;
|
|
1359
|
+
})();
|
|
1360
|
+
return this._ending;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
function buildAudioNamespace(rt) {
|
|
1365
|
+
const ns = buildNamespace(rt, "audio"); // speak / transcribe (v0.20.0)
|
|
1366
|
+
return {
|
|
1367
|
+
speak: ns.speak,
|
|
1368
|
+
transcribe: ns.transcribe,
|
|
1369
|
+
/** Open a realtime voice session (see VoiceSession). */
|
|
1370
|
+
session: async (config = {}) => {
|
|
1371
|
+
const result = await rt.call("audio", "session.open", { config: config || {} }, { timeoutMs: 20000 });
|
|
1372
|
+
const vs = new VoiceSession(rt, result || {});
|
|
1373
|
+
rt._voiceSessions.set(vs.sessionId || "__single__", vs);
|
|
1374
|
+
return vs;
|
|
1375
|
+
},
|
|
1376
|
+
/** Microphone → PCM16 frames (`MicCapture`, see anna-voice-client-core). */
|
|
1377
|
+
mic: (opts = {}) => new AnnaVoiceClientCore.MicCapture(opts),
|
|
1378
|
+
/** Gapless streamed-TTS player (`VoiceAudioPlayer`). */
|
|
1379
|
+
player: (opts = {}) => new AnnaVoiceClientCore.VoiceAudioPlayer(opts),
|
|
1380
|
+
/** Low-level helpers (chunking / base64 / PCM conversion). */
|
|
1381
|
+
core: AnnaVoiceClientCore,
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
|
|
744
1385
|
function buildAgentNamespace(rt) {
|
|
745
1386
|
const sessionRpcs = new Proxy(
|
|
746
1387
|
{},
|
|
@@ -1236,7 +1877,11 @@
|
|
|
1236
1877
|
// Capability discovery: anna.llm.catalog({serviceType?}).
|
|
1237
1878
|
// Requires manifest ui.host_api.video / .audio + per-app media_grant.
|
|
1238
1879
|
this.video = buildVideoNamespace(this);
|
|
1239
|
-
|
|
1880
|
+
// v0.21.0: + anna.audio.session(config) → VoiceSession (host-bridge
|
|
1881
|
+
// relayed realtime ASR→LLM→TTS, barge-in, setContext/say),
|
|
1882
|
+
// anna.audio.mic() / anna.audio.player() client helpers.
|
|
1883
|
+
this.audio = buildAudioNamespace(this);
|
|
1884
|
+
this._voiceSessions = new Map(); // sessionId -> VoiceSession
|
|
1240
1885
|
|
|
1241
1886
|
// ---- credentials namespace (v0.11.0; multi-account) ----
|
|
1242
1887
|
// anna.credentials.list_accounts({provider}) — metadata only, no tokens
|
|
@@ -1300,6 +1945,8 @@
|
|
|
1300
1945
|
// Reassembly buffers for `rpc.stream` events. Map<stream_id, AgentRunStream>.
|
|
1301
1946
|
this._streams = new Map();
|
|
1302
1947
|
this.on("rpc.stream", (payload) => this._onStreamFrame(payload || {}));
|
|
1948
|
+
// Voice relay events from the host bridge: {sessionId, type, ...}
|
|
1949
|
+
this.on("audio.session", (payload) => this._onVoiceEvent(payload || {}));
|
|
1303
1950
|
|
|
1304
1951
|
window.addEventListener("message", (ev) => this._onMessage(ev));
|
|
1305
1952
|
window.addEventListener("error", (ev) => {
|
|
@@ -1412,6 +2059,13 @@
|
|
|
1412
2059
|
}, 10000);
|
|
1413
2060
|
}
|
|
1414
2061
|
|
|
2062
|
+
_onVoiceEvent(payload) {
|
|
2063
|
+
const vs =
|
|
2064
|
+
(payload.sessionId && this._voiceSessions.get(payload.sessionId)) ||
|
|
2065
|
+
this._voiceSessions.get("__single__");
|
|
2066
|
+
if (vs) vs._dispatch(payload);
|
|
2067
|
+
}
|
|
2068
|
+
|
|
1415
2069
|
_onStreamFrame(payload) {
|
|
1416
2070
|
const sid = payload.stream_id;
|
|
1417
2071
|
if (!sid) return;
|
|
@@ -1479,6 +2133,8 @@
|
|
|
1479
2133
|
// v0.4.0; apps should now branch on the standard RPC error `.code`.
|
|
1480
2134
|
AnnaAppRuntime.AgentSession = AgentSession;
|
|
1481
2135
|
AnnaAppRuntime.AgentRunStream = AgentRunStream;
|
|
2136
|
+
AnnaAppRuntime.VoiceSession = VoiceSession;
|
|
2137
|
+
AnnaAppRuntime.VoiceClientCore = AnnaVoiceClientCore;
|
|
1482
2138
|
|
|
1483
|
-
export { AnnaAppRuntime, AgentSession, AgentRunStream };
|
|
2139
|
+
export { AnnaAppRuntime, AgentSession, AgentRunStream, VoiceSession, AnnaVoiceClientCore };
|
|
1484
2140
|
export default AnnaAppRuntime;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anna-ai/app-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "Anna App browser runtime SDK. Loaded by every Anna App iframe; provides typed proxy over the postMessage RPC bridge to the host (Anna dashboard / `anna-app dev` harness).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|