@anna-ai/app-runtime 0.21.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 +118 -22
  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,61 @@
1
1
  /**
2
- * Anna App Runtime SDK — v0.21.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.
3
59
  *
4
60
  * v0.21.0 — App realtime voice session (design:
5
61
  * app-realtime-voice-session-and-executa-transcribe.md §5.2 / §5.3, PB2).
@@ -579,15 +635,15 @@
579
635
  // billedCostCU}); `result.url` is a ~30 min presigned GET — call
580
636
  // `anna.video.getJob({jobId})` again to re-sign after expiry.
581
637
 
582
- function mediaJobErrorFromView(view) {
638
+ function mediaJobErrorFromView(view, ns = "video") {
583
639
  const e = view.error || {};
584
640
  const code =
585
641
  e.code ||
586
642
  (view.state === "expired"
587
- ? "video_timeout"
643
+ ? `${ns}_timeout`
588
644
  : view.state === "cancelled"
589
645
  ? "cancelled"
590
- : "video_failed");
646
+ : `${ns}_failed`);
591
647
  const err = new Error(
592
648
  e.message || `media job ${view.jobId} ended as ${view.state}`
593
649
  );
@@ -597,7 +653,10 @@
597
653
  return err;
598
654
  }
599
655
 
600
- 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 = {}) {
601
660
  const onProgress =
602
661
  typeof opts.onProgress === "function" ? opts.onProgress : null;
603
662
  const signal = opts.signal || null;
@@ -658,17 +717,22 @@
658
717
  if (settled || pollInFlight || !jobId) return;
659
718
  pollInFlight = true;
660
719
  try {
661
- const view = await rt.call("video", "getJob", { jobId });
720
+ const view = await rt.call(ns, "getJob", { jobId });
662
721
  if (view.progress) {
663
722
  deliverProgress(view.progress.seq, view.progress, view.state);
664
723
  }
665
724
  if (JOB_TERMINAL_STATES.has(view.state)) {
666
725
  if (view.state === "succeeded") settleOk(view);
667
- else settleErr(mediaJobErrorFromView(view));
726
+ else settleErr(mediaJobErrorFromView(view, ns));
668
727
  return;
669
728
  }
670
729
  } catch (e) {
671
- 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
+ ) {
672
736
  settleErr(e);
673
737
  return;
674
738
  }
@@ -690,19 +754,25 @@
690
754
 
691
755
  const start = async () => {
692
756
  if (signal && signal.aborted) {
693
- const err = new Error("video.generateAwait aborted before start");
757
+ const err = new Error(`${ns}.generateAwait aborted before start`);
694
758
  err.code = "cancelled";
695
759
  settleErr(err);
696
760
  return;
697
761
  }
698
762
  let created;
699
763
  try {
700
- created = await rt.call("video", "generate", args || {});
764
+ created = await rt.call(ns, "generate", args || {});
701
765
  } catch (e) {
702
766
  settleErr(e);
703
767
  return;
704
768
  }
705
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
+ }
706
776
  const deadlineMs = created.deadlineAt
707
777
  ? Date.parse(created.deadlineAt)
708
778
  : NaN;
@@ -713,9 +783,9 @@
713
783
  : 35 * 60 * 1000;
714
784
  wallTimer = setTimeout(() => {
715
785
  const err = new Error(
716
- `video.generateAwait wall clock elapsed after ${wallMs}ms; ` +
786
+ `${ns}.generateAwait wall clock elapsed after ${wallMs}ms; ` +
717
787
  `job ${jobId} may still be rendering — recover it with ` +
718
- `anna.video.getJob({jobId})`
788
+ `anna.${ns}.getJob({jobId})`
719
789
  );
720
790
  err.code = "wait_timeout";
721
791
  settleErr(err);
@@ -725,7 +795,7 @@
725
795
  onAbort = () => {
726
796
  // queued cancel = full refund; running cancel is best-effort
727
797
  // (provider may refuse — the job then runs to terminal).
728
- rt.call("video", "cancelJob", { jobId }).catch(() => {});
798
+ rt.call(ns, "cancelJob", { jobId }).catch(() => {});
729
799
  schedulePoll(0);
730
800
  };
731
801
  signal.addEventListener("abort", onAbort, { once: true });
@@ -737,7 +807,7 @@
737
807
  });
738
808
  }
739
809
 
740
- function buildVideoNamespace(rt) {
810
+ function buildMediaJobNamespace(rt, ns) {
741
811
  return new Proxy(
742
812
  {},
743
813
  {
@@ -745,18 +815,28 @@
745
815
  if (typeof method !== "string") return undefined;
746
816
  if (method === "onJobEvent") {
747
817
  // Raw `media_job` host events ({jobId, state, seq, progress,
748
- // 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.
749
820
  return (fn) => rt.on("media_job", fn);
750
821
  }
751
822
  if (method === "generateAwait") {
752
- return (args, opts) => videoGenerateAwaitImpl(rt, args, opts || {});
823
+ return (args, opts) => mediaGenerateAwaitImpl(rt, ns, args, opts || {});
753
824
  }
754
- return (args, opts) => rt.call("video", method, args || {}, opts);
825
+ return (args, opts) => rt.call(ns, method, args || {}, opts);
755
826
  },
756
827
  }
757
828
  );
758
829
  }
759
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
+
760
840
  // ---- Agent namespace (v0.2.0) ----
761
841
  //
762
842
  // Exposes both raw RPCs (`anna.agent.session.create({submode, ...})`,
@@ -1858,8 +1938,12 @@ var AnnaVoiceClientCore = (function () {
1858
1938
  this.agent = buildAgentNamespace(this);
1859
1939
 
1860
1940
  // ---- image / upload namespaces (v0.4.0; postMessage) ----
1861
- // anna.image.generate({prompt, n?, size?, reference_image_urls?, metadata?})
1862
- // 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)
1863
1947
  // anna.upload.inline({filename, mime_type, content_b64, purpose?, metadata?})
1864
1948
  // anna.upload.negotiate({filename, mime_type, size_bytes, purpose?, metadata?})
1865
1949
  // anna.upload.confirm({r2_key})
@@ -1871,12 +1955,24 @@ var AnnaVoiceClientCore = (function () {
1871
1955
  // aspectRatio?, generateAudio?, model?, clientTag?}) → {jobId, ...}
1872
1956
  // anna.video.{getJob,cancelJob,listJobs}({jobId|filters})
1873
1957
  // anna.video.generateAwait(args, {onProgress, signal, timeoutMs})
1874
- // anna.audio.speak({text, voice?, language?, format?, speed?,
1875
- // 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)
1876
1961
  // anna.audio.transcribe({audioUrl|audioBase64, language?}) → {text, ...}
1877
- // 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}.
1878
1966
  // Requires manifest ui.host_api.video / .audio + per-app media_grant.
1879
1967
  this.video = buildVideoNamespace(this);
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);
1880
1976
  // v0.21.0: + anna.audio.session(config) → VoiceSession (host-bridge
1881
1977
  // relayed realtime ASR→LLM→TTS, barge-in, setContext/say),
1882
1978
  // anna.audio.mic() / anna.audio.player() client helpers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anna-ai/app-runtime",
3
- "version": "0.21.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",