@anna-ai/app-runtime 0.18.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/README.md +32 -0
- package/dist/index.js +894 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -100,3 +100,35 @@ procedure.
|
|
|
100
100
|
Single file `dist/index.js`. Native ES module (ends in
|
|
101
101
|
`export { AnnaAppRuntime, ... }`), no build step, runs directly in any modern
|
|
102
102
|
browser via `<script type="module">` / `import`.
|
|
103
|
+
|
|
104
|
+
## Media generation (v0.20.0)
|
|
105
|
+
|
|
106
|
+
Async video jobs + sync audio, gated by the per-app `media_grant`
|
|
107
|
+
(manifest must declare `ui.host_api.video` / `.audio`):
|
|
108
|
+
|
|
109
|
+
```js
|
|
110
|
+
// One-shot sugar: submit + media_job events + getJob polling fallback
|
|
111
|
+
const job = await anna.video.generateAwait(
|
|
112
|
+
{ prompt: "Aerial drone shot over a misty pine forest", durationSec: 5,
|
|
113
|
+
resolution: "768p", clientTag: "scene-3-broll" },
|
|
114
|
+
{ onProgress: (p) => bar.update(p), signal: abortController.signal }
|
|
115
|
+
);
|
|
116
|
+
video.src = job.result.url; // presigned GET, ~30 min TTL
|
|
117
|
+
|
|
118
|
+
// URL expired (403)? Re-sign via getJob:
|
|
119
|
+
const fresh = await anna.video.getJob({ jobId: job.jobId });
|
|
120
|
+
|
|
121
|
+
// Raw job API: generate / getJob / cancelJob / listJobs
|
|
122
|
+
const { jobId, estimatedCostCU } = await anna.video.generate({ prompt: "..." });
|
|
123
|
+
|
|
124
|
+
// Sync TTS / STT
|
|
125
|
+
const speech = await anna.audio.speak({ text: "Welcome!", voice: "Cherry" });
|
|
126
|
+
const { text } = await anna.audio.transcribe({ audioUrl: "https://..." });
|
|
127
|
+
|
|
128
|
+
// Capability discovery: models, parameter space, CU pricing, remaining quota
|
|
129
|
+
const catalog = await anna.llm.catalog({ serviceType: "video_gen" });
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Costs are **pre-charged** from the estimate shown in `estimatedCostCU` and
|
|
133
|
+
fully refunded on failure/cancel/expiry. Aborting `generateAwait` cancels
|
|
134
|
+
the job (queued = full refund; running cancel is best-effort).
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,49 @@
|
|
|
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.
|
|
30
|
+
*
|
|
31
|
+
* v0.20.0 — Media generation surface (design:
|
|
32
|
+
* platform-media-generation-video-audio.md §7/§9/§10).
|
|
33
|
+
* Adds `anna.video.{generate,getJob,cancelJob,listJobs}` (async video
|
|
34
|
+
* jobs; `generate` returns `{jobId, state, estimatedCostCU, deadlineAt}`),
|
|
35
|
+
* `anna.video.generateAwait(args, {onProgress, signal, timeoutMs})` —
|
|
36
|
+
* submit + `media_job` host-event subscription + adaptive `getJob`
|
|
37
|
+
* polling fallback, mirroring `tools.invokeAsyncAwait`; resolves with the
|
|
38
|
+
* terminal job view (`result.url` = presigned GET, ~30 min TTL — re-sign
|
|
39
|
+
* by calling `getJob` again on 403). AbortSignal → `video.cancelJob`
|
|
40
|
+
* (queued = full refund; running cancel is best-effort).
|
|
41
|
+
* Adds `anna.audio.{speak,transcribe}` (sync TTS ≤ model char cap / STT
|
|
42
|
+
* ≤10 min) and `anna.llm.catalog({serviceType?})` capability discovery
|
|
43
|
+
* (models + CU pricing + remaining quota). All gated by the per-app
|
|
44
|
+
* `media_grant`; manifest must declare `ui.host_api.video` / `.audio`.
|
|
45
|
+
* Coordinated versions: dispatcher_version 0.26.0 + schema 0.26.0.
|
|
46
|
+
* Additive: old hosts reject the new namespaces with `unknown_method`.
|
|
3
47
|
*
|
|
4
48
|
* v0.18.0 — Run-recovery pull surface (forum #341 P3: push pairs with pull).
|
|
5
49
|
* Adds `anna.agent.session.runStatus({app_session_uuid, run_id})` →
|
|
@@ -220,6 +264,9 @@
|
|
|
220
264
|
* });
|
|
221
265
|
* await anna.window.set_title({ title: "My App" });
|
|
222
266
|
* anna.on("entry_payload", (p) => console.log(p));
|
|
267
|
+
* // Host pushes `entry_payload` when a single-instance view is re-invoked
|
|
268
|
+
* // with a fresh payload (forum #376); `p` is the full merged payload and
|
|
269
|
+
* // `anna.entryPayload` is refreshed automatically (SDK >= 0.19.0).
|
|
223
270
|
*/
|
|
224
271
|
|
|
225
272
|
// ---- Internals ----
|
|
@@ -522,6 +569,194 @@
|
|
|
522
569
|
);
|
|
523
570
|
}
|
|
524
571
|
|
|
572
|
+
// ---- Video namespace (v0.20.0) ----
|
|
573
|
+
//
|
|
574
|
+
// `anna.video.generateAwait(args, {onProgress, signal, timeoutMs})` =
|
|
575
|
+
// video.generate + `media_job` host-event subscription + adaptive
|
|
576
|
+
// video.getJob polling fallback — the media twin of
|
|
577
|
+
// `tools.invokeAsyncAwait`. Resolves with the terminal job view
|
|
578
|
+
// ({jobId, state:"succeeded", result:{url, mimeType, durationSec, ...},
|
|
579
|
+
// billedCostCU}); `result.url` is a ~30 min presigned GET — call
|
|
580
|
+
// `anna.video.getJob({jobId})` again to re-sign after expiry.
|
|
581
|
+
|
|
582
|
+
function mediaJobErrorFromView(view) {
|
|
583
|
+
const e = view.error || {};
|
|
584
|
+
const code =
|
|
585
|
+
e.code ||
|
|
586
|
+
(view.state === "expired"
|
|
587
|
+
? "video_timeout"
|
|
588
|
+
: view.state === "cancelled"
|
|
589
|
+
? "cancelled"
|
|
590
|
+
: "video_failed");
|
|
591
|
+
const err = new Error(
|
|
592
|
+
e.message || `media job ${view.jobId} ended as ${view.state}`
|
|
593
|
+
);
|
|
594
|
+
err.code = code;
|
|
595
|
+
err.jobId = view.jobId;
|
|
596
|
+
err.state = view.state;
|
|
597
|
+
return err;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function videoGenerateAwaitImpl(rt, args, opts = {}) {
|
|
601
|
+
const onProgress =
|
|
602
|
+
typeof opts.onProgress === "function" ? opts.onProgress : null;
|
|
603
|
+
const signal = opts.signal || null;
|
|
604
|
+
|
|
605
|
+
return new Promise((resolve, reject) => {
|
|
606
|
+
let settled = false;
|
|
607
|
+
let jobId = null;
|
|
608
|
+
let lastSeq = 0;
|
|
609
|
+
let eventSeen = false;
|
|
610
|
+
let pollTimer = null;
|
|
611
|
+
let wallTimer = null;
|
|
612
|
+
let pollInFlight = false;
|
|
613
|
+
let offEvent = null;
|
|
614
|
+
let onAbort = null;
|
|
615
|
+
|
|
616
|
+
const cleanup = () => {
|
|
617
|
+
if (pollTimer) clearTimeout(pollTimer);
|
|
618
|
+
if (wallTimer) clearTimeout(wallTimer);
|
|
619
|
+
if (offEvent) offEvent();
|
|
620
|
+
if (signal && onAbort) signal.removeEventListener("abort", onAbort);
|
|
621
|
+
};
|
|
622
|
+
const settleOk = (v) => {
|
|
623
|
+
if (settled) return;
|
|
624
|
+
settled = true;
|
|
625
|
+
cleanup();
|
|
626
|
+
resolve(v);
|
|
627
|
+
};
|
|
628
|
+
const settleErr = (e) => {
|
|
629
|
+
if (settled) return;
|
|
630
|
+
settled = true;
|
|
631
|
+
cleanup();
|
|
632
|
+
if (jobId && e && typeof e === "object" && !e.jobId) e.jobId = jobId;
|
|
633
|
+
reject(e);
|
|
634
|
+
};
|
|
635
|
+
|
|
636
|
+
const deliverProgress = (seq, progress, state) => {
|
|
637
|
+
if (typeof seq !== "number" || seq <= lastSeq) return;
|
|
638
|
+
lastSeq = seq;
|
|
639
|
+
if (onProgress) {
|
|
640
|
+
try {
|
|
641
|
+
onProgress({ seq, state: state || null, ...(progress || {}) });
|
|
642
|
+
} catch (_) {}
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
const schedulePoll = (delayMs) => {
|
|
647
|
+
if (settled) return;
|
|
648
|
+
if (pollTimer) clearTimeout(pollTimer);
|
|
649
|
+
const delay = Number.isFinite(delayMs)
|
|
650
|
+
? delayMs
|
|
651
|
+
: eventSeen
|
|
652
|
+
? JOB_POLL_WITH_EVENTS_MS
|
|
653
|
+
: JOB_POLL_NO_EVENTS_MS;
|
|
654
|
+
pollTimer = setTimeout(poll, delay);
|
|
655
|
+
};
|
|
656
|
+
|
|
657
|
+
const poll = async () => {
|
|
658
|
+
if (settled || pollInFlight || !jobId) return;
|
|
659
|
+
pollInFlight = true;
|
|
660
|
+
try {
|
|
661
|
+
const view = await rt.call("video", "getJob", { jobId });
|
|
662
|
+
if (view.progress) {
|
|
663
|
+
deliverProgress(view.progress.seq, view.progress, view.state);
|
|
664
|
+
}
|
|
665
|
+
if (JOB_TERMINAL_STATES.has(view.state)) {
|
|
666
|
+
if (view.state === "succeeded") settleOk(view);
|
|
667
|
+
else settleErr(mediaJobErrorFromView(view));
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
} catch (e) {
|
|
671
|
+
if (e && (e.code === "VIDEO_JOB_NOT_FOUND" || e.code === "job_not_found")) {
|
|
672
|
+
settleErr(e);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
// transient RPC errors: wait for the next cycle
|
|
676
|
+
} finally {
|
|
677
|
+
pollInFlight = false;
|
|
678
|
+
}
|
|
679
|
+
schedulePoll();
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
const onJobEvent = (payload) => {
|
|
683
|
+
if (settled || !payload || payload.jobId !== jobId) return;
|
|
684
|
+
eventSeen = true;
|
|
685
|
+
deliverProgress(payload.seq, payload.progress, payload.state);
|
|
686
|
+
// Terminal push → fetch the authoritative view immediately (the
|
|
687
|
+
// forwarded event never carries the result / re-signed URL).
|
|
688
|
+
schedulePoll(payload.terminal ? 0 : JOB_POLL_WITH_EVENTS_MS);
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
const start = async () => {
|
|
692
|
+
if (signal && signal.aborted) {
|
|
693
|
+
const err = new Error("video.generateAwait aborted before start");
|
|
694
|
+
err.code = "cancelled";
|
|
695
|
+
settleErr(err);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
let created;
|
|
699
|
+
try {
|
|
700
|
+
created = await rt.call("video", "generate", args || {});
|
|
701
|
+
} catch (e) {
|
|
702
|
+
settleErr(e);
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
jobId = created.jobId;
|
|
706
|
+
const deadlineMs = created.deadlineAt
|
|
707
|
+
? Date.parse(created.deadlineAt)
|
|
708
|
+
: NaN;
|
|
709
|
+
const wallMs = Number.isFinite(opts.timeoutMs)
|
|
710
|
+
? opts.timeoutMs
|
|
711
|
+
: Number.isFinite(deadlineMs)
|
|
712
|
+
? Math.max(0, deadlineMs - Date.now()) + 30000
|
|
713
|
+
: 35 * 60 * 1000;
|
|
714
|
+
wallTimer = setTimeout(() => {
|
|
715
|
+
const err = new Error(
|
|
716
|
+
`video.generateAwait wall clock elapsed after ${wallMs}ms; ` +
|
|
717
|
+
`job ${jobId} may still be rendering — recover it with ` +
|
|
718
|
+
`anna.video.getJob({jobId})`
|
|
719
|
+
);
|
|
720
|
+
err.code = "wait_timeout";
|
|
721
|
+
settleErr(err);
|
|
722
|
+
}, wallMs);
|
|
723
|
+
offEvent = rt.on("media_job", onJobEvent);
|
|
724
|
+
if (signal) {
|
|
725
|
+
onAbort = () => {
|
|
726
|
+
// queued cancel = full refund; running cancel is best-effort
|
|
727
|
+
// (provider may refuse — the job then runs to terminal).
|
|
728
|
+
rt.call("video", "cancelJob", { jobId }).catch(() => {});
|
|
729
|
+
schedulePoll(0);
|
|
730
|
+
};
|
|
731
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
732
|
+
}
|
|
733
|
+
schedulePoll(JOB_POLL_NO_EVENTS_MS);
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
start();
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function buildVideoNamespace(rt) {
|
|
741
|
+
return new Proxy(
|
|
742
|
+
{},
|
|
743
|
+
{
|
|
744
|
+
get(_, method) {
|
|
745
|
+
if (typeof method !== "string") return undefined;
|
|
746
|
+
if (method === "onJobEvent") {
|
|
747
|
+
// Raw `media_job` host events ({jobId, state, seq, progress,
|
|
748
|
+
// error, terminal}). Most apps should prefer generateAwait.
|
|
749
|
+
return (fn) => rt.on("media_job", fn);
|
|
750
|
+
}
|
|
751
|
+
if (method === "generateAwait") {
|
|
752
|
+
return (args, opts) => videoGenerateAwaitImpl(rt, args, opts || {});
|
|
753
|
+
}
|
|
754
|
+
return (args, opts) => rt.call("video", method, args || {}, opts);
|
|
755
|
+
},
|
|
756
|
+
}
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
|
|
525
760
|
// ---- Agent namespace (v0.2.0) ----
|
|
526
761
|
//
|
|
527
762
|
// Exposes both raw RPCs (`anna.agent.session.create({submode, ...})`,
|
|
@@ -533,6 +768,620 @@
|
|
|
533
768
|
// for await (const ev of sess.run({ content: "hi" })) {
|
|
534
769
|
// if (ev.event === "model_token") render(ev.text);
|
|
535
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
|
+
|
|
536
1385
|
function buildAgentNamespace(rt) {
|
|
537
1386
|
const sessionRpcs = new Proxy(
|
|
538
1387
|
{},
|
|
@@ -988,6 +1837,7 @@
|
|
|
988
1837
|
this.capabilities = null;
|
|
989
1838
|
this.viewMeta = null;
|
|
990
1839
|
this.entryPayload = null;
|
|
1840
|
+
this.app = null;
|
|
991
1841
|
this.runtimeState = null;
|
|
992
1842
|
this.geometry = null;
|
|
993
1843
|
|
|
@@ -1016,6 +1866,23 @@
|
|
|
1016
1866
|
this.image = buildNamespace(this, "image");
|
|
1017
1867
|
this.upload = buildNamespace(this, "upload");
|
|
1018
1868
|
|
|
1869
|
+
// ---- video / audio namespaces (v0.20.0; media generation) ----
|
|
1870
|
+
// anna.video.generate({prompt, imageUrl?, durationSec?, resolution?,
|
|
1871
|
+
// aspectRatio?, generateAudio?, model?, clientTag?}) → {jobId, ...}
|
|
1872
|
+
// anna.video.{getJob,cancelJob,listJobs}({jobId|filters})
|
|
1873
|
+
// anna.video.generateAwait(args, {onProgress, signal, timeoutMs})
|
|
1874
|
+
// anna.audio.speak({text, voice?, language?, format?, speed?,
|
|
1875
|
+
// delivery?}) → {url|audioBase64, mimeType, charCount, billedCostCU}
|
|
1876
|
+
// anna.audio.transcribe({audioUrl|audioBase64, language?}) → {text, ...}
|
|
1877
|
+
// Capability discovery: anna.llm.catalog({serviceType?}).
|
|
1878
|
+
// Requires manifest ui.host_api.video / .audio + per-app media_grant.
|
|
1879
|
+
this.video = buildVideoNamespace(this);
|
|
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
|
|
1885
|
+
|
|
1019
1886
|
// ---- credentials namespace (v0.11.0; multi-account) ----
|
|
1020
1887
|
// anna.credentials.list_accounts({provider}) — metadata only, no tokens
|
|
1021
1888
|
// anna.credentials.get_token({provider, account_id?}) — short-lived
|
|
@@ -1078,6 +1945,8 @@
|
|
|
1078
1945
|
// Reassembly buffers for `rpc.stream` events. Map<stream_id, AgentRunStream>.
|
|
1079
1946
|
this._streams = new Map();
|
|
1080
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 || {}));
|
|
1081
1950
|
|
|
1082
1951
|
window.addEventListener("message", (ev) => this._onMessage(ev));
|
|
1083
1952
|
window.addEventListener("error", (ev) => {
|
|
@@ -1134,6 +2003,16 @@
|
|
|
1134
2003
|
this.token = msg.token;
|
|
1135
2004
|
return;
|
|
1136
2005
|
}
|
|
2006
|
+
// forum #376: keep the runtime mirrors fresh before dispatching so
|
|
2007
|
+
// handlers (and later reads) observe the updated values.
|
|
2008
|
+
if (msg.event === "entry_payload") {
|
|
2009
|
+
this.entryPayload = msg.payload || {};
|
|
2010
|
+
} else if (msg.event === "runtime_state_synced") {
|
|
2011
|
+
const patch = msg.payload && msg.payload.patch;
|
|
2012
|
+
if (patch) {
|
|
2013
|
+
this.runtimeState = Object.assign({}, this.runtimeState, patch);
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
1137
2016
|
const set = this._handlers.get(msg.event);
|
|
1138
2017
|
if (set) for (const fn of set) try { fn(msg.payload); } catch (_) {}
|
|
1139
2018
|
}
|
|
@@ -1180,6 +2059,13 @@
|
|
|
1180
2059
|
}, 10000);
|
|
1181
2060
|
}
|
|
1182
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
|
+
|
|
1183
2069
|
_onStreamFrame(payload) {
|
|
1184
2070
|
const sid = payload.stream_id;
|
|
1185
2071
|
if (!sid) return;
|
|
@@ -1228,6 +2114,10 @@
|
|
|
1228
2114
|
const hello = await rt.call("window", "hello", {});
|
|
1229
2115
|
rt.capabilities = hello.capabilities;
|
|
1230
2116
|
rt.viewMeta = hello.view_meta;
|
|
2117
|
+
// forum #376 DX: the app's own identity — `{id, slug, name}`. `id` is
|
|
2118
|
+
// the numeric AnnaApp.id used by `open_app_view`; null on hosts older
|
|
2119
|
+
// than dispatcher 0.25.0.
|
|
2120
|
+
rt.app = hello.app || null;
|
|
1231
2121
|
rt.entryPayload = hello.entry_payload || {};
|
|
1232
2122
|
rt.runtimeState = hello.runtime_state || {};
|
|
1233
2123
|
rt.geometry = hello.geometry || {};
|
|
@@ -1243,6 +2133,8 @@
|
|
|
1243
2133
|
// v0.4.0; apps should now branch on the standard RPC error `.code`.
|
|
1244
2134
|
AnnaAppRuntime.AgentSession = AgentSession;
|
|
1245
2135
|
AnnaAppRuntime.AgentRunStream = AgentRunStream;
|
|
2136
|
+
AnnaAppRuntime.VoiceSession = VoiceSession;
|
|
2137
|
+
AnnaAppRuntime.VoiceClientCore = AnnaVoiceClientCore;
|
|
1246
2138
|
|
|
1247
|
-
export { AnnaAppRuntime, AgentSession, AgentRunStream };
|
|
2139
|
+
export { AnnaAppRuntime, AgentSession, AgentRunStream, VoiceSession, AnnaVoiceClientCore };
|
|
1248
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",
|