@anna-ai/app-runtime 0.20.0 → 0.23.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.
Files changed (3) hide show
  1. package/README.md +67 -0
  2. package/dist/index.js +776 -24
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -129,6 +129,73 @@ const { text } = await anna.audio.transcribe({ audioUrl: "https://..." });
129
129
  const catalog = await anna.llm.catalog({ serviceType: "video_gen" });
130
130
  ```
131
131
 
132
+ ### Music generation (v0.23.0)
133
+
134
+ Async music jobs (`mjob_…`) with the exact same job API, `media_job` events and
135
+ pre-hold → settle → refund billing as video. Requires `ui.host_api.music` +
136
+ per-app `media_grant.music`.
137
+
138
+ ```js
139
+ // Capability discovery first — models differ (lyrics vs prompt-embedded lyrics,
140
+ // fixed vs range length, mp3 vs wav, reference image …). Nothing is silently
141
+ // downgraded: an unsupported field fails with MUSIC_FEATURE_UNSUPPORTED (-32165)
142
+ // and error.data.alternatives lists models that do support it.
143
+ const { models } = await anna.llm.catalog({ serviceType: "music_gen" });
144
+ const m = models.find(x => x.isPlatformDefault); // fal-ai/minimax-music/v2.6
145
+
146
+ const song = await anna.music.generateAwait(
147
+ { prompt: "melancholic cinematic piano, slow ~70 BPM, rainy night",
148
+ lyrics: "[Verse 1]\n…\n[Chorus]\n…", // only when m.capabilities.lyrics
149
+ model: m.modelName,
150
+ clientTag: "scene-3-score",
151
+ idempotencyKey: "canvas-node-8f3a-v2" }, // 24h replay → same job, no re-charge
152
+ { onProgress: (p) => bar.update(p), signal: abortController.signal }
153
+ );
154
+ audio.src = song.result.url; // presigned GET, ~30 min TTL; song.result.lyrics when returned
155
+ song.idempotentReplay; // true when the key hit an existing job
156
+
157
+ // Range-length models (ElevenLabs / Stable Audio / ACE-Step) take durationSec;
158
+ // fixed-length models (MiniMax / Lyria) reject it. Instrumental-only models
159
+ // (Stable Audio) reject lyrics and instrumental:false.
160
+ await anna.music.generate({ prompt: "ambient pad", model: "fal-ai/ace-step", durationSec: 30, instrumental: true });
161
+ ```
162
+
163
+ ### Model-aware options (v0.22.0)
164
+
165
+ Every TTS / image model describes its knobs in `capabilities.options`
166
+ (schema v2: `{type, min, max, step, values, default, scope, …}`). Pass any of
167
+ them in `params`; keys a model does not declare are dropped and echoed in
168
+ `ignoredParams`, never surcharged.
169
+
170
+ ```js
171
+ const { models } = await anna.llm.catalog({ serviceType: "tts", voiceLanguage: "zh" });
172
+ const tts = models.find(m => m.isUserPreferred) ?? models.find(m => m.isPlatformDefault);
173
+ const out = await anna.audio.speak({
174
+ text: "Welcome!",
175
+ model: tts.modelName,
176
+ voice: tts.capabilities.defaultVoice,
177
+ params: { stability: 0.3, similarity_boost: 0.8 }, // keys from capabilities.options
178
+ });
179
+ out.params; // what reached the provider
180
+ out.ignoredParams; // e.g. ["similarity_boost"] on a model that only exposes stability
181
+
182
+ // Image: explicit model + size policy. `fit: "strict"` fails with
183
+ // IMAGE_SIZE_UNSUPPORTED (+ data.allowed) instead of snapping to the nearest size.
184
+ const img = await anna.image.generate({
185
+ prompt: "A bold art-deco poster of the planet Mars",
186
+ model: "fal-ai/nano-banana-2",
187
+ aspect_ratio: "9:16",
188
+ params: { resolution: "2K" },
189
+ fit: "strict",
190
+ });
191
+ img.size; img.sizeAdjusted; img.images[0].width; // real decoded dimensions
192
+ ```
193
+
194
+ Render `capabilities.options` as a form with the shared
195
+ [`ModelOptionsForm`](https://anna.partners/developers/reference/model-options-form)
196
+ component — the same file the platform uses on `/llm` and in the Developer
197
+ Console Playground.
198
+
132
199
  Costs are **pre-charged** from the estimate shown in `estimatedCostCU` and
133
200
  fully refunded on failure/cancel/expiry. Aborting `generateAwait` cancels
134
201
  the job (queued = full refund; running cancel is best-effort).
package/dist/index.js CHANGED
@@ -1,5 +1,88 @@
1
1
  /**
2
- * Anna App Runtime SDK — v0.20.0
2
+ * Anna App Runtime SDK — v0.23.0
3
+ *
4
+ * v0.23.0 — Music generation surface (design:
5
+ * platform-media-generation-music.md §7/§9/§12.1).
6
+ * Adds `anna.music.{generate,getJob,cancelJob,listJobs}` (async music
7
+ * jobs, `mjob_…` ids; same state machine / `media_job` events /
8
+ * pre-hold→settle→refund billing as video) and
9
+ * `anna.music.generateAwait(args, {onProgress, signal, timeoutMs})` —
10
+ * the music twin of `video.generateAwait` (shared implementation).
11
+ * `music.generate` args: `{prompt, lyrics?, instrumental?, durationSec?,
12
+ * format?, referenceImageUrl?, options?, model?, clientTag?,
13
+ * idempotencyKey?}`; replies carry `idempotentReplay` — when a replay is
14
+ * already terminal, `generateAwait` resolves immediately without polling.
15
+ * Unsupported features raise `MUSIC_FEATURE_UNSUPPORTED` (-32165) with
16
+ * `error.data.alternatives` (model names that support the feature) —
17
+ * never a silent downgrade. Terminal result: `{url, mimeType,
18
+ * durationSec|null, lyrics|null, seed, expiresIn}`.
19
+ * `video.generate` additionally accepts `idempotencyKey` (same 24h replay
20
+ * semantics). Requires manifest `ui.host_api.music` + per-app
21
+ * `media_grant.music`. Coordinated versions: dispatcher_version 0.28.0 +
22
+ * schema 0.28.0 + anna-app-core 0.25.0. Additive: old hosts reject the new
23
+ * namespace with `unknown_method`.
24
+ *
25
+ * v0.22.0 — Schema-driven media options (design:
26
+ * developer-model-playground-and-tts-options-schema.md §5.12, PR1/PR2).
27
+ * Contract-only release — every namespace is a pass-through proxy, so no
28
+ * runtime code changes; this documents the new wire fields:
29
+ * • `anna.llm.catalog()` models carry `isPlatformDefault` (who the host
30
+ * routes to when the user has no preference; `isUserPreferred` unchanged)
31
+ * and `capabilities.options` is a self-describing schema v2
32
+ * (`{type: "range"|"select"|"boolean"|"text"|"size", min, max, step,
33
+ * values, default, scope, label?, help?, affectsPrice?, custom?}`).
34
+ * `catalog({serviceType: "tts", voiceLanguage: "zh"})` filters
35
+ * `capabilities.voices[]`, whose entries now carry
36
+ * `gender? | accent? | age? | tags?`. `image_gen` / `image_edit` entries
37
+ * are populated (`options`, `sizeInput: "size"|"aspect_ratio"|"both"`,
38
+ * `edit: {referenceImages, maxReferenceImages?, mask}`, per-image CU
39
+ * `pricing`). `video_gen` entries add `capabilities.options` too, keyed
40
+ * by the `video.generate` request fields (`durationSec`, `resolution`,
41
+ * `aspectRatio`, `generateAudio`) so a rendered form merges 1:1 into the
42
+ * request; the legacy `duration / resolutions / aspectRatios` keys stay.
43
+ * • `anna.audio.speak({…, params?})` — `params` = any key of
44
+ * `capabilities.options`; legacy top-level `speed/language/timestamps/
45
+ * format` still work (merged, `params` wins). Response adds `params`
46
+ * (normalised, as sent to the provider) and `ignoredParams` (keys the
47
+ * model does not declare — dropped, never surcharged). New error
48
+ * `-32149 AUDIO_OPTION_INVALID` (`data.{key, reason, allowed}`).
49
+ * • `anna.image.generate/edit({…, model?, params?, fit?, aspect_ratio?})`
50
+ * — `model` = exact catalogue name (unknown → `-32110
51
+ * IMAGE_MODEL_UNAVAILABLE` + `data.allowed`); `modelPreferences.hints`
52
+ * stays as a legacy input. `fit: "nearest"` (default — closest size,
53
+ * same orientation) | `"strict"` (`-32111 IMAGE_SIZE_UNSUPPORTED` +
54
+ * `data.allowed`). `params` validated per model (`-32112
55
+ * IMAGE_OPTION_INVALID`). Response adds `requestedSize`, `size`,
56
+ * `sizeAdjusted`, `aspectRatio`, `fit`, `params`, `ignoredParams`;
57
+ * `images[].width/height` are the real decoded dimensions.
58
+ * Additive — old hosts ignore the new request fields.
59
+ *
60
+ * v0.21.0 — App realtime voice session (design:
61
+ * app-realtime-voice-session-and-executa-transcribe.md §5.2 / §5.3, PB2).
62
+ * Adds `anna.audio.session(config)` → `VoiceSession` handle over the host
63
+ * bridge relay (`audio.session.*` are handled IN the host page, which owns
64
+ * the `wss://…/anna-apps/runtime/voice` socket — the iframe never holds a
65
+ * token nor opens a network connection). Full-duplex pipeline: streaming
66
+ * ASR → LLM (`llm: "agent"` = this app's agent session, or `"none"`) →
67
+ * streaming TTS with barge-in. Handle API: `sendAudio(pcm16)` (16 kHz
68
+ * mono; auto-chunked ≤ 32 KB, fire-and-forget), `flushAudio()` (push-to-talk
69
+ * released → finalize the pending sentence), `setContext(text)`
70
+ * (≤ 4 KB live context injected into the NEXT turn's system prompt — not
71
+ * into history), `say(text, {priority, interrupt})` (TTS-only, no LLM),
72
+ * `interrupt()`, `end()`; events `asr_partial | asr_final | llm_start |
73
+ * llm_partial | llm_done | tts_audio | tts_done | interrupted | say_start |
74
+ * say_done | context_updated | asr_paused | asr_resumed | quota_warning |
75
+ * error | ended` (the host pauses ASR after `asrIdleTimeoutSec` without
76
+ * audio and reconnects on the next frame — push-to-talk is safe). Pure
77
+ * client helpers `anna.audio.mic({sampleRate})` (AudioWorklet 16 kHz PCM16
78
+ * capture, ScriptProcessor fallback) and `anna.audio.player({sampleRate})`
79
+ * (gapless 24 kHz PCM queue) share ONE source with the dashboard main-chat
80
+ * voice call (`static/js/anna-voice-client-core.js`, embedded below).
81
+ * Requires manifest `ui.host_api.audio ∋ "session"` (implies the outer
82
+ * iframe gets `allow="microphone"`) + user `media_grant.audio.{speak,
83
+ * transcribe}`; `llm:"agent"` additionally needs `host_api.agent.session`.
84
+ * Hosts without the relay reply `unknown_method`/`not_supported`.
85
+ * Additive — `audio.speak` / `audio.transcribe` unchanged.
3
86
  *
4
87
  * v0.20.0 — Media generation surface (design:
5
88
  * platform-media-generation-video-audio.md §7/§9/§10).
@@ -552,15 +635,15 @@
552
635
  // billedCostCU}); `result.url` is a ~30 min presigned GET — call
553
636
  // `anna.video.getJob({jobId})` again to re-sign after expiry.
554
637
 
555
- function mediaJobErrorFromView(view) {
638
+ function mediaJobErrorFromView(view, ns = "video") {
556
639
  const e = view.error || {};
557
640
  const code =
558
641
  e.code ||
559
642
  (view.state === "expired"
560
- ? "video_timeout"
643
+ ? `${ns}_timeout`
561
644
  : view.state === "cancelled"
562
645
  ? "cancelled"
563
- : "video_failed");
646
+ : `${ns}_failed`);
564
647
  const err = new Error(
565
648
  e.message || `media job ${view.jobId} ended as ${view.state}`
566
649
  );
@@ -570,7 +653,10 @@
570
653
  return err;
571
654
  }
572
655
 
573
- function videoGenerateAwaitImpl(rt, args, opts = {}) {
656
+ // Shared by video (v0.20.0) and music (v0.23.0): `ns` selects the RPC
657
+ // namespace; wire shapes are identical except the music job view carries
658
+ // `idempotentReplay` (a terminal replay resolves without polling).
659
+ function mediaGenerateAwaitImpl(rt, ns, args, opts = {}) {
574
660
  const onProgress =
575
661
  typeof opts.onProgress === "function" ? opts.onProgress : null;
576
662
  const signal = opts.signal || null;
@@ -631,17 +717,22 @@
631
717
  if (settled || pollInFlight || !jobId) return;
632
718
  pollInFlight = true;
633
719
  try {
634
- const view = await rt.call("video", "getJob", { jobId });
720
+ const view = await rt.call(ns, "getJob", { jobId });
635
721
  if (view.progress) {
636
722
  deliverProgress(view.progress.seq, view.progress, view.state);
637
723
  }
638
724
  if (JOB_TERMINAL_STATES.has(view.state)) {
639
725
  if (view.state === "succeeded") settleOk(view);
640
- else settleErr(mediaJobErrorFromView(view));
726
+ else settleErr(mediaJobErrorFromView(view, ns));
641
727
  return;
642
728
  }
643
729
  } catch (e) {
644
- if (e && (e.code === "VIDEO_JOB_NOT_FOUND" || e.code === "job_not_found")) {
730
+ if (
731
+ e &&
732
+ (e.code === "VIDEO_JOB_NOT_FOUND" ||
733
+ e.code === "MUSIC_JOB_NOT_FOUND" ||
734
+ e.code === "job_not_found")
735
+ ) {
645
736
  settleErr(e);
646
737
  return;
647
738
  }
@@ -663,19 +754,25 @@
663
754
 
664
755
  const start = async () => {
665
756
  if (signal && signal.aborted) {
666
- const err = new Error("video.generateAwait aborted before start");
757
+ const err = new Error(`${ns}.generateAwait aborted before start`);
667
758
  err.code = "cancelled";
668
759
  settleErr(err);
669
760
  return;
670
761
  }
671
762
  let created;
672
763
  try {
673
- created = await rt.call("video", "generate", args || {});
764
+ created = await rt.call(ns, "generate", args || {});
674
765
  } catch (e) {
675
766
  settleErr(e);
676
767
  return;
677
768
  }
678
769
  jobId = created.jobId;
770
+ // Idempotent replay of an already-terminal job: nothing to wait for.
771
+ if (created.idempotentReplay && JOB_TERMINAL_STATES.has(created.state)) {
772
+ if (created.state === "succeeded") settleOk(created);
773
+ else settleErr(mediaJobErrorFromView(created, ns));
774
+ return;
775
+ }
679
776
  const deadlineMs = created.deadlineAt
680
777
  ? Date.parse(created.deadlineAt)
681
778
  : NaN;
@@ -686,9 +783,9 @@
686
783
  : 35 * 60 * 1000;
687
784
  wallTimer = setTimeout(() => {
688
785
  const err = new Error(
689
- `video.generateAwait wall clock elapsed after ${wallMs}ms; ` +
786
+ `${ns}.generateAwait wall clock elapsed after ${wallMs}ms; ` +
690
787
  `job ${jobId} may still be rendering — recover it with ` +
691
- `anna.video.getJob({jobId})`
788
+ `anna.${ns}.getJob({jobId})`
692
789
  );
693
790
  err.code = "wait_timeout";
694
791
  settleErr(err);
@@ -698,7 +795,7 @@
698
795
  onAbort = () => {
699
796
  // queued cancel = full refund; running cancel is best-effort
700
797
  // (provider may refuse — the job then runs to terminal).
701
- rt.call("video", "cancelJob", { jobId }).catch(() => {});
798
+ rt.call(ns, "cancelJob", { jobId }).catch(() => {});
702
799
  schedulePoll(0);
703
800
  };
704
801
  signal.addEventListener("abort", onAbort, { once: true });
@@ -710,7 +807,7 @@
710
807
  });
711
808
  }
712
809
 
713
- function buildVideoNamespace(rt) {
810
+ function buildMediaJobNamespace(rt, ns) {
714
811
  return new Proxy(
715
812
  {},
716
813
  {
@@ -718,18 +815,28 @@
718
815
  if (typeof method !== "string") return undefined;
719
816
  if (method === "onJobEvent") {
720
817
  // Raw `media_job` host events ({jobId, state, seq, progress,
721
- // error, terminal}). Most apps should prefer generateAwait.
818
+ // error, terminal}) — shared stream; filter by `jobId` prefix
819
+ // (`vjob_` / `mjob_`) or `kind` when both namespaces are used.
722
820
  return (fn) => rt.on("media_job", fn);
723
821
  }
724
822
  if (method === "generateAwait") {
725
- return (args, opts) => videoGenerateAwaitImpl(rt, args, opts || {});
823
+ return (args, opts) => mediaGenerateAwaitImpl(rt, ns, args, opts || {});
726
824
  }
727
- return (args, opts) => rt.call("video", method, args || {}, opts);
825
+ return (args, opts) => rt.call(ns, method, args || {}, opts);
728
826
  },
729
827
  }
730
828
  );
731
829
  }
732
830
 
831
+ function buildVideoNamespace(rt) {
832
+ return buildMediaJobNamespace(rt, "video");
833
+ }
834
+
835
+ // v0.23.0 — anna.music.* (platform-media-generation-music.md §12.1)
836
+ function buildMusicNamespace(rt) {
837
+ return buildMediaJobNamespace(rt, "music");
838
+ }
839
+
733
840
  // ---- Agent namespace (v0.2.0) ----
734
841
  //
735
842
  // Exposes both raw RPCs (`anna.agent.session.create({submode, ...})`,
@@ -741,6 +848,620 @@
741
848
  // for await (const ev of sess.run({ content: "hi" })) {
742
849
  // if (ev.event === "model_token") render(ev.text);
743
850
  // }
851
+ // ==== BEGIN anna-voice-client-core ====
852
+ var AnnaVoiceClientCore = (function () {
853
+ "use strict";
854
+
855
+ const VERSION = "1.0.0";
856
+ const DEFAULT_MIC_SAMPLE_RATE = 16000;
857
+ const DEFAULT_FRAME_SIZE = 4096; // samples → 256 ms @ 16 kHz, 8 KB PCM16
858
+ const MAX_CHUNK_BYTES = 32 * 1024; // server-side single audio_data cap
859
+
860
+ // ───────────────────────── PCM / base64 helpers ─────────────────────────
861
+
862
+ /** Float32 [-1,1] → Int16 LE (clamped). */
863
+ function float32ToPcm16(float32) {
864
+ const out = new Int16Array(float32.length);
865
+ for (let i = 0; i < float32.length; i++) {
866
+ const s = Math.max(-1, Math.min(1, float32[i]));
867
+ out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
868
+ }
869
+ return out;
870
+ }
871
+
872
+ /** Uint8Array → base64 (chunked String.fromCharCode to avoid arg limits). */
873
+ function bytesToBase64(bytes) {
874
+ let binary = "";
875
+ const STEP = 0x8000;
876
+ for (let i = 0; i < bytes.length; i += STEP) {
877
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + STEP));
878
+ }
879
+ return btoa(binary);
880
+ }
881
+
882
+ /** Int16Array | ArrayBuffer | Uint8Array → base64 of the raw little-endian bytes. */
883
+ function pcm16ToBase64(pcm) {
884
+ const bytes =
885
+ pcm instanceof Uint8Array
886
+ ? pcm
887
+ : pcm instanceof ArrayBuffer
888
+ ? new Uint8Array(pcm)
889
+ : new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength);
890
+ return bytesToBase64(bytes);
891
+ }
892
+
893
+ /** base64 → Uint8Array. */
894
+ function base64ToBytes(b64) {
895
+ const binary = atob(b64);
896
+ const bytes = new Uint8Array(binary.length);
897
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
898
+ return bytes;
899
+ }
900
+
901
+ /**
902
+ * Split PCM16 into ≤ `maxBytes` slices (even byte boundary) and base64 each.
903
+ * Returns `string[]`; an empty input yields `[]`.
904
+ */
905
+ function chunkPcm16(pcm, maxBytes = MAX_CHUNK_BYTES) {
906
+ const bytes =
907
+ pcm instanceof Uint8Array
908
+ ? pcm
909
+ : pcm instanceof ArrayBuffer
910
+ ? new Uint8Array(pcm)
911
+ : new Uint8Array(pcm.buffer, pcm.byteOffset, pcm.byteLength);
912
+ const step = Math.max(2, maxBytes - (maxBytes % 2));
913
+ const out = [];
914
+ for (let i = 0; i < bytes.length; i += step) {
915
+ out.push(bytesToBase64(bytes.subarray(i, Math.min(i + step, bytes.length))));
916
+ }
917
+ return out;
918
+ }
919
+
920
+ // ───────────────────────── MicCapture ─────────────────────────
921
+
922
+ // AudioWorkletProcessor source. Accumulates 128-frame render quanta into
923
+ // `frameSize` samples and posts one Float32Array per frame.
924
+ const WORKLET_SOURCE = `
925
+ class AnnaPcmCaptureProcessor extends AudioWorkletProcessor {
926
+ constructor(options) {
927
+ super();
928
+ const fs = (options && options.processorOptions && options.processorOptions.frameSize) || 4096;
929
+ this._fs = fs;
930
+ this._buf = new Float32Array(fs);
931
+ this._pos = 0;
932
+ }
933
+ process(inputs) {
934
+ const ch = inputs[0] && inputs[0][0];
935
+ if (!ch) return true;
936
+ let i = 0;
937
+ while (i < ch.length) {
938
+ const n = Math.min(ch.length - i, this._buf.length - this._pos);
939
+ this._buf.set(ch.subarray(i, i + n), this._pos);
940
+ this._pos += n; i += n;
941
+ if (this._pos === this._buf.length) {
942
+ const out = this._buf;
943
+ this.port.postMessage(out, [out.buffer]);
944
+ // out is detached after the transfer (length 0) — never size the
945
+ // next buffer from it, or process() spins forever on a 0-length buf.
946
+ this._buf = new Float32Array(this._fs);
947
+ this._pos = 0;
948
+ }
949
+ }
950
+ return true;
951
+ }
952
+ }
953
+ registerProcessor("anna-pcm-capture", AnnaPcmCaptureProcessor);
954
+ `;
955
+
956
+ /**
957
+ * Microphone → PCM16 frames.
958
+ *
959
+ * const mic = new MicCapture({ onChunk(pcm16, float32) { ... } });
960
+ * await mic.start(); // prompts for permission
961
+ * mic.setMuted(true); // keeps the stream, stops emitting
962
+ * mic.analyser // AnalyserNode (fftSize 256) for visualizers
963
+ * mic.stop(); // releases tracks + closes the AudioContext
964
+ *
965
+ * `onChunk(pcm16: Int16Array, float32: Float32Array)` fires once per
966
+ * `frameSize` samples at `sampleRate`. `onLevel(rms)` is optional cheap VAD
967
+ * input (RMS of the frame). Errors from the browser surface via `onError`
968
+ * and the rejected `start()` promise.
969
+ */
970
+ class MicCapture {
971
+ constructor(opts = {}) {
972
+ this.sampleRate = opts.sampleRate || DEFAULT_MIC_SAMPLE_RATE;
973
+ this.frameSize = opts.frameSize || DEFAULT_FRAME_SIZE;
974
+ this.onChunk = opts.onChunk || null;
975
+ this.onLevel = opts.onLevel || null;
976
+ this.onError = opts.onError || null;
977
+ this.preferWorklet = opts.preferWorklet !== false;
978
+ this.constraints = opts.constraints || {
979
+ echoCancellation: true,
980
+ noiseSuppression: true,
981
+ autoGainControl: true,
982
+ };
983
+ this.stream = null;
984
+ this.ctx = null;
985
+ this.analyser = null;
986
+ this.muted = false;
987
+ this.active = false;
988
+ this.mode = null; // "worklet" | "script"
989
+ this._source = null;
990
+ this._node = null;
991
+ this._workletUrl = null;
992
+ }
993
+
994
+ async start() {
995
+ if (this.active) return this;
996
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
997
+ // `navigator.mediaDevices` is [SecureContext]-only: on http://<lan-ip>
998
+ // (RN dev builds, LAN testing) it is simply undefined. Say so, instead
999
+ // of a generic "not available" that reads like a missing device.
1000
+ const insecure = typeof window !== "undefined" && window.isSecureContext === false;
1001
+ throw new Error(
1002
+ insecure
1003
+ ? "getUserMedia unavailable: insecure context (page must be served over https or from localhost)"
1004
+ : "getUserMedia not available"
1005
+ );
1006
+ }
1007
+ this.stream = await navigator.mediaDevices.getUserMedia({
1008
+ audio: Object.assign({ sampleRate: this.sampleRate }, this.constraints),
1009
+ });
1010
+ try {
1011
+ const Ctx = window.AudioContext || window.webkitAudioContext;
1012
+ this.ctx = new Ctx({ sampleRate: this.sampleRate });
1013
+ if (this.ctx.state === "suspended") {
1014
+ try { await this.ctx.resume(); } catch (_) {}
1015
+ }
1016
+ this._source = this.ctx.createMediaStreamSource(this.stream);
1017
+ this.analyser = this.ctx.createAnalyser();
1018
+ this.analyser.fftSize = 256;
1019
+ this.analyser.smoothingTimeConstant = 0.7;
1020
+ this._source.connect(this.analyser);
1021
+
1022
+ let ok = false;
1023
+ if (this.preferWorklet && this.ctx.audioWorklet && typeof Blob !== "undefined") {
1024
+ ok = await this._startWorklet();
1025
+ }
1026
+ if (!ok) this._startScriptProcessor();
1027
+ } catch (e) {
1028
+ // Never leave the mic indicator on after a failed start.
1029
+ this.stop();
1030
+ throw e;
1031
+ }
1032
+ this.active = true;
1033
+ return this;
1034
+ }
1035
+
1036
+ async _startWorklet() {
1037
+ try {
1038
+ this._workletUrl = URL.createObjectURL(
1039
+ new Blob([WORKLET_SOURCE], { type: "application/javascript" })
1040
+ );
1041
+ await this.ctx.audioWorklet.addModule(this._workletUrl);
1042
+ const node = new AudioWorkletNode(this.ctx, "anna-pcm-capture", {
1043
+ numberOfInputs: 1,
1044
+ numberOfOutputs: 0,
1045
+ channelCount: 1,
1046
+ processorOptions: { frameSize: this.frameSize },
1047
+ });
1048
+ node.port.onmessage = (ev) => this._emit(ev.data);
1049
+ this._source.connect(node);
1050
+ this._node = node;
1051
+ this.mode = "worklet";
1052
+ return true;
1053
+ } catch (e) {
1054
+ // CSP without blob: workers, old WebViews, … → ScriptProcessor.
1055
+ if (this._workletUrl) { try { URL.revokeObjectURL(this._workletUrl); } catch (_) {} }
1056
+ this._workletUrl = null;
1057
+ return false;
1058
+ }
1059
+ }
1060
+
1061
+ _startScriptProcessor() {
1062
+ const node = this.ctx.createScriptProcessor(this.frameSize, 1, 1);
1063
+ node.onaudioprocess = (e) => {
1064
+ // Copy: the input buffer is reused by the engine.
1065
+ this._emit(new Float32Array(e.inputBuffer.getChannelData(0)));
1066
+ };
1067
+ this._source.connect(node);
1068
+ node.connect(this.ctx.destination); // required for onaudioprocess to fire
1069
+ this._node = node;
1070
+ this.mode = "script";
1071
+ }
1072
+
1073
+ _emit(float32) {
1074
+ if (!this.active || this.muted) return;
1075
+ if (this.onLevel) {
1076
+ let sumSq = 0;
1077
+ for (let i = 0; i < float32.length; i++) sumSq += float32[i] * float32[i];
1078
+ try { this.onLevel(Math.sqrt(sumSq / (float32.length || 1)), float32); } catch (e) { this._err(e); }
1079
+ }
1080
+ if (this.onChunk) {
1081
+ try { this.onChunk(float32ToPcm16(float32), float32); } catch (e) { this._err(e); }
1082
+ }
1083
+ }
1084
+
1085
+ _err(e) {
1086
+ if (this.onError) { try { this.onError(e); } catch (_) {} }
1087
+ else console.warn("[anna-voice-core] MicCapture handler error", e);
1088
+ }
1089
+
1090
+ /** Mute keeps the track live (fast unmute) but stops emitting frames. */
1091
+ setMuted(muted) {
1092
+ this.muted = !!muted;
1093
+ if (this.stream) this.stream.getAudioTracks().forEach((t) => { t.enabled = !this.muted; });
1094
+ }
1095
+
1096
+ stop() {
1097
+ this.active = false;
1098
+ if (this._node) {
1099
+ try { this._node.disconnect(); } catch (_) {}
1100
+ if (this._node.port) this._node.port.onmessage = null;
1101
+ this._node = null;
1102
+ }
1103
+ if (this._source) { try { this._source.disconnect(); } catch (_) {} this._source = null; }
1104
+ if (this.stream) { this.stream.getTracks().forEach((t) => t.stop()); this.stream = null; }
1105
+ if (this.ctx) { this.ctx.close().catch(() => {}); this.ctx = null; }
1106
+ if (this._workletUrl) { try { URL.revokeObjectURL(this._workletUrl); } catch (_) {} this._workletUrl = null; }
1107
+ this.analyser = null;
1108
+ this.muted = false;
1109
+ }
1110
+ }
1111
+
1112
+ // ───────────────────────── VoiceAudioPlayer ─────────────────────────
1113
+
1114
+ /**
1115
+ * Gapless audio player for streamed TTS. Sample-accurate
1116
+ * AudioBufferSourceNode scheduling eliminates gaps between chunks.
1117
+ * Supports PCM (Int16 LE) and MP3 with a small jitter buffer.
1118
+ *
1119
+ * const player = new VoiceAudioPlayer({ sampleRate: 24000 });
1120
+ * player.onPlaybackEnd = () => ...;
1121
+ * player.enqueue(base64Chunk); // per tts_audio
1122
+ * player.flush(); // on tts_done
1123
+ * player.stop(); // on interrupted / barge-in
1124
+ */
1125
+ class VoiceAudioPlayer {
1126
+ constructor(opts = {}) {
1127
+ this.ctx = null;
1128
+ this.nextPlayTime = 0;
1129
+ this.pendingChunks = []; // jitter buffer
1130
+ this.started = false;
1131
+ this.playing = false;
1132
+ this.activeSources = []; // scheduled sources (for stop)
1133
+ this.onPlaybackEnd = opts.onPlaybackEnd || null;
1134
+ this.format = opts.format || "pcm";
1135
+ this.sampleRate = opts.sampleRate || 24000;
1136
+ this.channels = opts.channels || 1;
1137
+ this.JITTER_CHUNKS = opts.jitterChunks || 3;
1138
+ }
1139
+
1140
+ /** Apply `session_started.audio_config` ({format, sample_rate, channels}). */
1141
+ configure(config) {
1142
+ if (!config) return;
1143
+ if (config.format) this.format = config.format;
1144
+ if (config.sample_rate) this.sampleRate = config.sample_rate;
1145
+ if (config.sampleRate) this.sampleRate = config.sampleRate;
1146
+ if (config.channels) this.channels = config.channels;
1147
+ }
1148
+
1149
+ _ensureContext() {
1150
+ if (!this.ctx || this.ctx.state === "closed") {
1151
+ this.ctx = new (window.AudioContext || window.webkitAudioContext)();
1152
+ }
1153
+ if (this.ctx.state === "suspended") this.ctx.resume();
1154
+ }
1155
+
1156
+ _decodePCM(base64Data) {
1157
+ const bytes = base64ToBytes(base64Data);
1158
+ const int16 = new Int16Array(bytes.buffer, 0, bytes.byteLength >> 1);
1159
+ const float32 = new Float32Array(int16.length);
1160
+ for (let i = 0; i < int16.length; i++) float32[i] = int16[i] / 32768;
1161
+ return float32;
1162
+ }
1163
+
1164
+ _onSourceEnded(source) {
1165
+ const idx = this.activeSources.indexOf(source);
1166
+ if (idx !== -1) this.activeSources.splice(idx, 1);
1167
+ if (this.activeSources.length === 0 && this.pendingChunks.length === 0) {
1168
+ this.playing = false;
1169
+ if (this.onPlaybackEnd) this.onPlaybackEnd();
1170
+ }
1171
+ }
1172
+
1173
+ _scheduleBuffer(buffer) {
1174
+ const source = this.ctx.createBufferSource();
1175
+ source.buffer = buffer;
1176
+ source.connect(this.ctx.destination);
1177
+ const startTime = Math.max(this.nextPlayTime, this.ctx.currentTime);
1178
+ source.start(startTime);
1179
+ this.nextPlayTime = startTime + buffer.duration;
1180
+ this.activeSources.push(source);
1181
+ source.onended = () => this._onSourceEnded(source);
1182
+ }
1183
+
1184
+ _scheduleFloat32(float32Data) {
1185
+ this._ensureContext();
1186
+ const buffer = this.ctx.createBuffer(this.channels, float32Data.length, this.sampleRate);
1187
+ buffer.copyToChannel(float32Data, 0);
1188
+ this._scheduleBuffer(buffer);
1189
+ }
1190
+
1191
+ _scheduleMP3(base64Data) {
1192
+ this._ensureContext();
1193
+ const bytes = base64ToBytes(base64Data);
1194
+ this.ctx
1195
+ .decodeAudioData(bytes.buffer.slice(0))
1196
+ .then((audioBuffer) => this._scheduleBuffer(audioBuffer))
1197
+ .catch((err) => console.warn("VoiceAudioPlayer: MP3 decode error, skipping chunk", err));
1198
+ }
1199
+
1200
+ _flushPending() {
1201
+ this.started = true;
1202
+ this.playing = true;
1203
+ this._ensureContext();
1204
+ this.nextPlayTime = this.ctx.currentTime + 0.05; // jitter headroom
1205
+ const chunks = this.pendingChunks.splice(0);
1206
+ for (const chunk of chunks) this._scheduleChunk(chunk);
1207
+ }
1208
+
1209
+ _scheduleChunk(base64Audio) {
1210
+ if (this.format === "pcm") this._scheduleFloat32(this._decodePCM(base64Audio));
1211
+ else this._scheduleMP3(base64Audio);
1212
+ }
1213
+
1214
+ /** Enqueue a base64 audio chunk (jitter-buffered until JITTER_CHUNKS). */
1215
+ enqueue(base64Audio) {
1216
+ if (!base64Audio) return;
1217
+ if (!this.started) {
1218
+ this.pendingChunks.push(base64Audio);
1219
+ if (this.pendingChunks.length >= this.JITTER_CHUNKS) this._flushPending();
1220
+ } else {
1221
+ this.playing = true;
1222
+ this._scheduleChunk(base64Audio);
1223
+ }
1224
+ }
1225
+
1226
+ /** Flush the jitter buffer (call when the TTS stream ends). */
1227
+ flush() {
1228
+ if (this.pendingChunks.length > 0) this._flushPending();
1229
+ }
1230
+
1231
+ /** Stop everything immediately (barge-in / interrupt). */
1232
+ stop() {
1233
+ for (const source of this.activeSources) {
1234
+ try { source.onended = null; source.stop(); } catch (_) {}
1235
+ }
1236
+ this.activeSources = [];
1237
+ this.pendingChunks = [];
1238
+ this.started = false;
1239
+ this.playing = false;
1240
+ this.nextPlayTime = 0;
1241
+ }
1242
+
1243
+ /** Full cleanup (closes the AudioContext). */
1244
+ destroy() {
1245
+ this.stop();
1246
+ if (this.ctx) { this.ctx.close().catch(() => {}); this.ctx = null; }
1247
+ }
1248
+
1249
+ get isPlaying() {
1250
+ return this.playing;
1251
+ }
1252
+ }
1253
+
1254
+ return {
1255
+ VERSION,
1256
+ DEFAULT_MIC_SAMPLE_RATE,
1257
+ DEFAULT_FRAME_SIZE,
1258
+ MAX_CHUNK_BYTES,
1259
+ float32ToPcm16,
1260
+ bytesToBase64,
1261
+ pcm16ToBase64,
1262
+ base64ToBytes,
1263
+ chunkPcm16,
1264
+ MicCapture,
1265
+ VoiceAudioPlayer,
1266
+ };
1267
+ })();
1268
+ // ==== END anna-voice-client-core ====
1269
+
1270
+ // ───────────────────────── audio namespace (v0.21.0) ─────────────────────────
1271
+
1272
+ const VOICE_SESSION_EVENTS = new Set([
1273
+ "asr_partial", "asr_final", "llm_start", "llm_partial", "llm_done",
1274
+ "tts_audio", "tts_done", "interrupted", "say_start", "say_done",
1275
+ "context_updated", "quota_warning", "error", "session_ended",
1276
+ "asr_paused", "asr_resumed",
1277
+ ]);
1278
+ const VOICE_MAX_CONTEXT_CHARS = 4 * 1024;
1279
+ const VOICE_MAX_SAY_CHARS = 1000;
1280
+
1281
+ /**
1282
+ * App realtime voice session handle (design §5.2). Obtained via
1283
+ * `await anna.audio.session({...})`; the host bridge owns the WebSocket.
1284
+ *
1285
+ * const vs = await anna.audio.session({ llm: "agent", context: "..." });
1286
+ * vs.on("asr_final", ({text}) => ...);
1287
+ * vs.on("tts_audio", ({audio}) => player.enqueue(audio));
1288
+ * vs.on("tts_done", () => player.flush());
1289
+ * vs.on("interrupted", () => player.stop());
1290
+ * mic.onChunk = (pcm16) => vs.sendAudio(pcm16); // push-to-talk: only while pressed!
1291
+ * vs.setContext("hp=30% gold=1200"); // replaces; next turn
1292
+ * await vs.say("小心上路", { priority: "high" }); // TTS-only, preempts
1293
+ * await vs.end();
1294
+ *
1295
+ * ASR is billed per second of audio you send — gate `sendAudio` behind
1296
+ * push-to-talk / a wake word instead of streaming continuously.
1297
+ */
1298
+ class VoiceSession {
1299
+ constructor(rt, info) {
1300
+ this._rt = rt;
1301
+ this.sessionId = info.sessionId || null;
1302
+ this.audioConfig = info.audio_config || null;
1303
+ this.models = info.models || null;
1304
+ this.maxDurationSec = info.max_duration_sec ?? null;
1305
+ // Host pauses the ASR connection after this many idle seconds (no
1306
+ // sendAudio); the next frame reconnects transparently (`asr_paused` /
1307
+ // `asr_resumed` events). Expect the first word after a long pause to be
1308
+ // ~0.3–0.6 s slower. null on hosts without idle management.
1309
+ this.asrIdleTimeoutSec = info.asr_idle_timeout_sec ?? null;
1310
+ this.ended = false;
1311
+ this.usage = null;
1312
+ this._handlers = new Map();
1313
+ this._endResolvers = [];
1314
+ }
1315
+
1316
+ on(event, fn) {
1317
+ let set = this._handlers.get(event);
1318
+ if (!set) { set = new Set(); this._handlers.set(event, set); }
1319
+ set.add(fn);
1320
+ return () => set.delete(fn);
1321
+ }
1322
+
1323
+ off(event, fn) {
1324
+ const set = this._handlers.get(event);
1325
+ if (set) set.delete(fn);
1326
+ }
1327
+
1328
+ _emit(event, payload) {
1329
+ const set = this._handlers.get(event);
1330
+ if (set) for (const fn of set) try { fn(payload); } catch (e) { console.warn("[anna-sdk] voice handler threw", e); }
1331
+ const all = this._handlers.get("*");
1332
+ if (all) for (const fn of all) try { fn(event, payload); } catch (_) {}
1333
+ }
1334
+
1335
+ /** Bridge → SDK dispatch (payload = raw server event + sessionId). */
1336
+ _dispatch(payload) {
1337
+ if (this.ended) return;
1338
+ const type = payload.type;
1339
+ if (type === "session_ended") {
1340
+ this.ended = true;
1341
+ this.usage = {
1342
+ duration: payload.duration ?? null,
1343
+ total_asr_seconds: payload.total_asr_seconds ?? null,
1344
+ total_tts_characters: payload.total_tts_characters ?? null,
1345
+ reason: payload.reason || null,
1346
+ };
1347
+ this._emit("ended", Object.assign({ sessionId: this.sessionId }, this.usage));
1348
+ for (const r of this._endResolvers.splice(0)) r(this.usage);
1349
+ this._rt._voiceSessions.delete(this.sessionId || "__single__");
1350
+ return;
1351
+ }
1352
+ if (!VOICE_SESSION_EVENTS.has(type)) return; // forward-compat: ignore unknown
1353
+ this._emit(type, payload);
1354
+ }
1355
+
1356
+ /**
1357
+ * Send 16 kHz mono PCM16 (`Int16Array` | `ArrayBuffer` | `Uint8Array`).
1358
+ * Auto-chunked to ≤ 32 KB; fire-and-forget (no per-chunk round trip).
1359
+ * Returns the number of chunks posted.
1360
+ */
1361
+ sendAudio(pcm16) {
1362
+ if (this.ended || !pcm16) return 0;
1363
+ const chunks = AnnaVoiceClientCore.chunkPcm16(pcm16);
1364
+ for (const b64 of chunks) {
1365
+ this._rt._post({
1366
+ kind: "req",
1367
+ id: uuid(),
1368
+ ns: "audio",
1369
+ method: "session.send",
1370
+ args: { sessionId: this.sessionId, audio_b64: b64 },
1371
+ });
1372
+ }
1373
+ return chunks.length;
1374
+ }
1375
+
1376
+ /**
1377
+ * Signal end of the current utterance (push-to-talk released). Streaming
1378
+ * ASR only finalizes a sentence after enough trailing *silence frames*;
1379
+ * once you stop calling `sendAudio` the pending sentence would never
1380
+ * finalize — `flushAudio()` asks the host to finalize it now
1381
+ * (`asr_final` follows, then `asr_paused{reason:"flushed"}`; the next
1382
+ * `sendAudio` reconnects transparently). Fire-and-forget.
1383
+ */
1384
+ flushAudio() {
1385
+ if (this.ended) return;
1386
+ this._rt._post({ kind: "req", id: uuid(), ns: "audio", method: "session.flush", args: { sessionId: this.sessionId } });
1387
+ }
1388
+
1389
+ /** Replace the live context (≤ 4 KB); takes effect from the next utterance. */
1390
+ setContext(text) {
1391
+ const t = text == null ? "" : String(text);
1392
+ if (t.length > VOICE_MAX_CONTEXT_CHARS) {
1393
+ return Promise.reject(Object.assign(new Error(`context exceeds ${VOICE_MAX_CONTEXT_CHARS} chars`), { code: "context_too_large" }));
1394
+ }
1395
+ return this._rt.call("audio", "session.context", { sessionId: this.sessionId, text: t });
1396
+ }
1397
+
1398
+ /**
1399
+ * Speak `text` through the session's streaming TTS without the LLM.
1400
+ * `priority:"high"` or `interrupt:true` preempts the current reply;
1401
+ * `"normal"` queues in the server's single pending slot (newer replaces
1402
+ * older — `say_done{status:"replaced"}`). Resolves `{sayId}` once queued;
1403
+ * listen to `say_start` / `say_done` for playback lifecycle.
1404
+ */
1405
+ say(text, opts = {}) {
1406
+ const t = text == null ? "" : String(text);
1407
+ if (!t.trim()) return Promise.reject(Object.assign(new Error("say: text required"), { code: "invalid_request" }));
1408
+ if (t.length > VOICE_MAX_SAY_CHARS) {
1409
+ return Promise.reject(Object.assign(new Error(`say exceeds ${VOICE_MAX_SAY_CHARS} chars`), { code: "say_too_long" }));
1410
+ }
1411
+ return this._rt
1412
+ .call("audio", "session.say", {
1413
+ sessionId: this.sessionId,
1414
+ text: t,
1415
+ priority: opts.priority || "normal",
1416
+ interrupt: !!opts.interrupt,
1417
+ say_id: opts.sayId || opts.say_id || undefined,
1418
+ })
1419
+ .then((r) => ({ sayId: r && r.sayId }));
1420
+ }
1421
+
1422
+ /** Stop the current LLM reply + TTS playback server-side. */
1423
+ interrupt() {
1424
+ return this._rt.call("audio", "session.interrupt", { sessionId: this.sessionId });
1425
+ }
1426
+
1427
+ /** End the session; resolves with the usage summary (`session_ended`). */
1428
+ end() {
1429
+ if (this.ended) return Promise.resolve(this.usage);
1430
+ if (this._ending) return this._ending; // concurrent end() share one close
1431
+ this._ending = (async () => {
1432
+ const done = new Promise((resolve) => this._endResolvers.push(resolve));
1433
+ const res = await this._rt.call("audio", "session.close", { sessionId: this.sessionId }, { timeoutMs: 10000 });
1434
+ if (!this.ended) {
1435
+ // Bridge timed out waiting for session_ended — synthesize from the close reply.
1436
+ this._dispatch(Object.assign({ type: "session_ended", reason: "closed" }, res || {}));
1437
+ }
1438
+ return done;
1439
+ })();
1440
+ return this._ending;
1441
+ }
1442
+ }
1443
+
1444
+ function buildAudioNamespace(rt) {
1445
+ const ns = buildNamespace(rt, "audio"); // speak / transcribe (v0.20.0)
1446
+ return {
1447
+ speak: ns.speak,
1448
+ transcribe: ns.transcribe,
1449
+ /** Open a realtime voice session (see VoiceSession). */
1450
+ session: async (config = {}) => {
1451
+ const result = await rt.call("audio", "session.open", { config: config || {} }, { timeoutMs: 20000 });
1452
+ const vs = new VoiceSession(rt, result || {});
1453
+ rt._voiceSessions.set(vs.sessionId || "__single__", vs);
1454
+ return vs;
1455
+ },
1456
+ /** Microphone → PCM16 frames (`MicCapture`, see anna-voice-client-core). */
1457
+ mic: (opts = {}) => new AnnaVoiceClientCore.MicCapture(opts),
1458
+ /** Gapless streamed-TTS player (`VoiceAudioPlayer`). */
1459
+ player: (opts = {}) => new AnnaVoiceClientCore.VoiceAudioPlayer(opts),
1460
+ /** Low-level helpers (chunking / base64 / PCM conversion). */
1461
+ core: AnnaVoiceClientCore,
1462
+ };
1463
+ }
1464
+
744
1465
  function buildAgentNamespace(rt) {
745
1466
  const sessionRpcs = new Proxy(
746
1467
  {},
@@ -1217,8 +1938,12 @@
1217
1938
  this.agent = buildAgentNamespace(this);
1218
1939
 
1219
1940
  // ---- image / upload namespaces (v0.4.0; postMessage) ----
1220
- // anna.image.generate({prompt, n?, size?, reference_image_urls?, metadata?})
1221
- // anna.image.edit({image_url, prompt, n?, size?, mask_url?, metadata?})
1941
+ // anna.image.generate({prompt, n?, size?, aspect_ratio?, model?, params?,
1942
+ // fit?: "nearest"|"strict", reference_image_urls?, metadata?})
1943
+ // → {images:[{url,width,height,…}], model, requestedSize, size,
1944
+ // sizeAdjusted, aspectRatio, fit, params, ignoredParams, usage}
1945
+ // anna.image.edit({image_url, prompt, n?, size?, aspect_ratio?, model?,
1946
+ // params?, fit?, mask_url?, metadata?}) → same shape (v0.22.0 fields)
1222
1947
  // anna.upload.inline({filename, mime_type, content_b64, purpose?, metadata?})
1223
1948
  // anna.upload.negotiate({filename, mime_type, size_bytes, purpose?, metadata?})
1224
1949
  // anna.upload.confirm({r2_key})
@@ -1230,13 +1955,29 @@
1230
1955
  // aspectRatio?, generateAudio?, model?, clientTag?}) → {jobId, ...}
1231
1956
  // anna.video.{getJob,cancelJob,listJobs}({jobId|filters})
1232
1957
  // anna.video.generateAwait(args, {onProgress, signal, timeoutMs})
1233
- // anna.audio.speak({text, voice?, language?, format?, speed?,
1234
- // delivery?}) → {url|audioBase64, mimeType, charCount, billedCostCU}
1958
+ // anna.audio.speak({text, model?, voice?, params?, language?, format?,
1959
+ // speed?, delivery?}) → {url|audioBase64, mimeType, charCount,
1960
+ // billedCostCU, model, voice, params, ignoredParams} (v0.22.0 fields)
1235
1961
  // anna.audio.transcribe({audioUrl|audioBase64, language?}) → {text, ...}
1236
- // Capability discovery: anna.llm.catalog({serviceType?}).
1962
+ // Capability discovery: anna.llm.catalog({serviceType?, voiceLanguage?})
1963
+ // → {models:[{modelName, isUserPreferred, isPlatformDefault,
1964
+ // capabilities:{options (schema v2), voices?, sizeInput?, edit?, …},
1965
+ // pricing}], quota}.
1237
1966
  // Requires manifest ui.host_api.video / .audio + per-app media_grant.
1238
1967
  this.video = buildVideoNamespace(this);
1239
- this.audio = buildNamespace(this, "audio");
1968
+ // v0.23.0: anna.music.{generate,getJob,cancelJob,listJobs,generateAwait}
1969
+ // ({prompt, lyrics?, instrumental?, durationSec?, format?,
1970
+ // referenceImageUrl?, options?, model?, clientTag?, idempotencyKey?})
1971
+ // → {jobId:"mjob_…", kind:"music", state, estimatedCostCU, deadlineAt,
1972
+ // idempotentReplay}; terminal result {url, mimeType, durationSec|null,
1973
+ // lyrics|null, seed, expiresIn}. Requires ui.host_api.music +
1974
+ // media_grant.music.
1975
+ this.music = buildMusicNamespace(this);
1976
+ // v0.21.0: + anna.audio.session(config) → VoiceSession (host-bridge
1977
+ // relayed realtime ASR→LLM→TTS, barge-in, setContext/say),
1978
+ // anna.audio.mic() / anna.audio.player() client helpers.
1979
+ this.audio = buildAudioNamespace(this);
1980
+ this._voiceSessions = new Map(); // sessionId -> VoiceSession
1240
1981
 
1241
1982
  // ---- credentials namespace (v0.11.0; multi-account) ----
1242
1983
  // anna.credentials.list_accounts({provider}) — metadata only, no tokens
@@ -1300,6 +2041,8 @@
1300
2041
  // Reassembly buffers for `rpc.stream` events. Map<stream_id, AgentRunStream>.
1301
2042
  this._streams = new Map();
1302
2043
  this.on("rpc.stream", (payload) => this._onStreamFrame(payload || {}));
2044
+ // Voice relay events from the host bridge: {sessionId, type, ...}
2045
+ this.on("audio.session", (payload) => this._onVoiceEvent(payload || {}));
1303
2046
 
1304
2047
  window.addEventListener("message", (ev) => this._onMessage(ev));
1305
2048
  window.addEventListener("error", (ev) => {
@@ -1412,6 +2155,13 @@
1412
2155
  }, 10000);
1413
2156
  }
1414
2157
 
2158
+ _onVoiceEvent(payload) {
2159
+ const vs =
2160
+ (payload.sessionId && this._voiceSessions.get(payload.sessionId)) ||
2161
+ this._voiceSessions.get("__single__");
2162
+ if (vs) vs._dispatch(payload);
2163
+ }
2164
+
1415
2165
  _onStreamFrame(payload) {
1416
2166
  const sid = payload.stream_id;
1417
2167
  if (!sid) return;
@@ -1479,6 +2229,8 @@
1479
2229
  // v0.4.0; apps should now branch on the standard RPC error `.code`.
1480
2230
  AnnaAppRuntime.AgentSession = AgentSession;
1481
2231
  AnnaAppRuntime.AgentRunStream = AgentRunStream;
2232
+ AnnaAppRuntime.VoiceSession = VoiceSession;
2233
+ AnnaAppRuntime.VoiceClientCore = AnnaVoiceClientCore;
1482
2234
 
1483
- export { AnnaAppRuntime, AgentSession, AgentRunStream };
2235
+ export { AnnaAppRuntime, AgentSession, AgentRunStream, VoiceSession, AnnaVoiceClientCore };
1484
2236
  export default AnnaAppRuntime;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anna-ai/app-runtime",
3
- "version": "0.20.0",
3
+ "version": "0.23.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",