@anna-ai/app-runtime 0.21.0 → 0.25.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 +140 -0
  2. package/dist/index.js +270 -23
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -101,6 +101,38 @@ 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
103
 
104
+ ## Host context: theme & language (v0.24.0)
105
+
106
+ The dashboard tells every App which **theme** and **UI language** the user
107
+ chose, so Apps no longer guess from `prefers-color-scheme` / `navigator.language`.
108
+ No manifest grant is involved — these are one-way host→app broadcasts (like
109
+ `auth.refresh`), never callable RPC methods.
110
+
111
+ ```js
112
+ const anna = await AnnaAppRuntime.connect();
113
+
114
+ anna.theme; // 'light' | 'dark' — already correct before the first paint
115
+ anna.themeMode; // 'light' | 'dark' | 'system' — what the user picked
116
+ anna.locale; // 'en' | 'zh-CN' | … — dashboard UI language
117
+
118
+ // Subscribe; both replay the current value once, then fire on every change.
119
+ anna.onThemeChange(({ theme }) => { document.documentElement.dataset.theme = theme; });
120
+ anna.onLocaleChange(({ lang }) => i18n.setLocale(lang));
121
+ ```
122
+
123
+ Wire details: initial values ride on the iframe URL
124
+ (`…?wid=&t=&theme=light&themeMode=system&lang=zh-CN`) and are read synchronously
125
+ in `connect()`; live changes arrive as `{kind:"event", event:"theme.changed",
126
+ payload:{theme, mode}}` and `{event:"locale.changed", payload:{lang}}`. Hosts older
127
+ than this release send neither — the SDK falls back to `prefers-color-scheme` and
128
+ `navigator.language`, so keep a CSS fallback for standalone previews:
129
+
130
+ ```css
131
+ :root[data-theme="light"] { /* light tokens */ }
132
+ :root[data-theme="dark"] { /* dark tokens */ }
133
+ @media (prefers-color-scheme: dark) { :root:not([data-theme]) { /* dark tokens */ } }
134
+ ```
135
+
104
136
  ## Media generation (v0.20.0)
105
137
 
106
138
  Async video jobs + sync audio, gated by the per-app `media_grant`
@@ -129,6 +161,114 @@ const { text } = await anna.audio.transcribe({ audioUrl: "https://..." });
129
161
  const catalog = await anna.llm.catalog({ serviceType: "video_gen" });
130
162
  ```
131
163
 
164
+ ### Music generation (v0.23.0)
165
+
166
+ Async music jobs (`mjob_…`) with the exact same job API, `media_job` events and
167
+ pre-hold → settle → refund billing as video. Requires `ui.host_api.music` +
168
+ per-app `media_grant.music`.
169
+
170
+ ```js
171
+ // Capability discovery first — models differ (lyrics vs prompt-embedded lyrics,
172
+ // fixed vs range length, mp3 vs wav, reference image …). Nothing is silently
173
+ // downgraded: an unsupported field fails with MUSIC_FEATURE_UNSUPPORTED (-32165)
174
+ // and error.data.alternatives lists models that do support it.
175
+ const { models } = await anna.llm.catalog({ serviceType: "music_gen" });
176
+ const m = models.find(x => x.isPlatformDefault); // fal-ai/minimax-music/v2.6
177
+
178
+ const song = await anna.music.generateAwait(
179
+ { prompt: "melancholic cinematic piano, slow ~70 BPM, rainy night",
180
+ lyrics: "[Verse 1]\n…\n[Chorus]\n…", // only when m.capabilities.lyrics
181
+ model: m.modelName,
182
+ clientTag: "scene-3-score",
183
+ idempotencyKey: "canvas-node-8f3a-v2" }, // 24h replay → same job, no re-charge
184
+ { onProgress: (p) => bar.update(p), signal: abortController.signal }
185
+ );
186
+ audio.src = song.result.url; // presigned GET, ~30 min TTL; song.result.lyrics when returned
187
+ song.idempotentReplay; // true when the key hit an existing job
188
+
189
+ // Range-length models (ElevenLabs / Stable Audio / ACE-Step) take durationSec;
190
+ // fixed-length models (MiniMax / Lyria) reject it. Instrumental-only models
191
+ // (Stable Audio) reject lyrics and instrumental:false.
192
+ await anna.music.generate({ prompt: "ambient pad", model: "fal-ai/ace-step", durationSec: 30, instrumental: true });
193
+ ```
194
+
195
+ ### Image async jobs & re-signing (v0.25.0)
196
+
197
+ `anna.image.generate` / `anna.image.edit` stay synchronous and unchanged. For
198
+ 2K/4K or `quality: "high"` renders (60–120 s) opt into the same async-job shape
199
+ as video / music — `ijob_…` ids, `media_job` events, pre-hold → settle (on the
200
+ actual number of images) → refund — and re-sign any already-paid artifact for
201
+ 7 days instead of losing it after the 30-min URL TTL. Requires
202
+ `ui.host_api.image` listing the new method names + the existing `image_grant`
203
+ (`allowGenerate` / `allowEdit`; no new grant).
204
+
205
+ ```js
206
+ // Same request body as image.generate, plus clientTag / idempotencyKey.
207
+ const job = await anna.image.generateAwait(
208
+ { prompt: "A bold art-deco poster of the planet Mars", n: 2,
209
+ model: "fal-ai/nano-banana-2", aspect_ratio: "9:16", params: { resolution: "4K" },
210
+ clientTag: "poster-v3", idempotencyKey: `poster-v3:${attempt}` }, // 24h replay → same job, no re-charge
211
+ { onProgress: (p) => status.textContent = `${p.state} · queue ${p.queuePosition ?? "-"}`,
212
+ signal: abortController.signal } // → image.cancelJob
213
+ );
214
+ job.result.images; // [{url, r2Key, mimeType, width, height, expiresIn}] — url re-signed by getJob
215
+ job.billedCostCU; // settled on actual output (≤ estimatedCostCU)
216
+
217
+ // Edit (optionally mask-based) as a job:
218
+ await anna.image.editAwait({ image_url, prompt: "replace the sky with aurora", mask_url, model: "openai/gpt-image-2" });
219
+
220
+ // Reload recovery / correlation — same four-pack as video / music:
221
+ const { jobs } = await anna.image.listJobs({ state: "running", clientTag: "poster-v3" });
222
+ const fresh = await anna.image.getJob({ jobId }); // every result.images[].url re-signed (~30 min)
223
+
224
+ // Re-sign already-paid artifacts (sync `images[].r2_key` or job `r2Key`), up to 7 days:
225
+ const { urls } = await anna.image.resign({ r2Keys: [img.images[0].r2_key, job.result.images[0].r2Key] });
226
+ // One key that is not yours → whole call fails with IMAGE_ASSET_NOT_FOUND (details.data.index).
227
+ ```
228
+
229
+ Errors surface as `HostRpcError` names: `IMAGE_JOB_NOT_FOUND`,
230
+ `IMAGE_JOB_NOT_CANCELLABLE`, `IMAGE_CONTENT_REJECTED` (also replaces the sync
231
+ path's former `APP_PROVIDER_ERROR` for provider safety rejections),
232
+ `IMAGE_JOB_EXPIRED`, `IMAGE_ASSET_NOT_FOUND`; `error.details.data` now carries
233
+ `allowed` / `alternatives` / `index`. `anna.llm.catalog` image entries report
234
+ `capabilities.jobs` and, for `image_edit`, the real `options.n.max`.
235
+
236
+ ### Model-aware options (v0.22.0)
237
+
238
+ Every TTS / image model describes its knobs in `capabilities.options`
239
+ (schema v2: `{type, min, max, step, values, default, scope, …}`). Pass any of
240
+ them in `params`; keys a model does not declare are dropped and echoed in
241
+ `ignoredParams`, never surcharged.
242
+
243
+ ```js
244
+ const { models } = await anna.llm.catalog({ serviceType: "tts", voiceLanguage: "zh" });
245
+ const tts = models.find(m => m.isUserPreferred) ?? models.find(m => m.isPlatformDefault);
246
+ const out = await anna.audio.speak({
247
+ text: "Welcome!",
248
+ model: tts.modelName,
249
+ voice: tts.capabilities.defaultVoice,
250
+ params: { stability: 0.3, similarity_boost: 0.8 }, // keys from capabilities.options
251
+ });
252
+ out.params; // what reached the provider
253
+ out.ignoredParams; // e.g. ["similarity_boost"] on a model that only exposes stability
254
+
255
+ // Image: explicit model + size policy. `fit: "strict"` fails with
256
+ // IMAGE_SIZE_UNSUPPORTED (+ data.allowed) instead of snapping to the nearest size.
257
+ const img = await anna.image.generate({
258
+ prompt: "A bold art-deco poster of the planet Mars",
259
+ model: "fal-ai/nano-banana-2",
260
+ aspect_ratio: "9:16",
261
+ params: { resolution: "2K" },
262
+ fit: "strict",
263
+ });
264
+ img.size; img.sizeAdjusted; img.images[0].width; // real decoded dimensions
265
+ ```
266
+
267
+ Render `capabilities.options` as a form with the shared
268
+ [`ModelOptionsForm`](https://anna.partners/developers/reference/model-options-form)
269
+ component — the same file the platform uses on `/llm` and in the Developer
270
+ Console Playground.
271
+
132
272
  Costs are **pre-charged** from the estimate shown in `estimatedCostCU` and
133
273
  fully refunded on failure/cancel/expiry. Aborting `generateAwait` cancels
134
274
  the job (queued = full refund; running cancel is best-effort).
package/dist/index.js CHANGED
@@ -1,5 +1,118 @@
1
1
  /**
2
- * Anna App Runtime SDK — v0.21.0
2
+ * Anna App Runtime SDK — v0.25.0
3
+ *
4
+ * v0.25.0 — Image async jobs + artifact re-signing (design:
5
+ * platform-media-generation-image-jobs.md §7 / §12.1; dispatcher 0.29.0).
6
+ * Image becomes the third media line with the video / music job shape —
7
+ * as an *opt-in* next to the unchanged synchronous `anna.image.generate`
8
+ * / `anna.image.edit` (byte-for-byte identical contract):
9
+ * • `anna.image.generateAsync(args & {clientTag?, idempotencyKey?})` /
10
+ * `anna.image.editAsync(...)` → `{jobId:"ijob_…", kind:"image",
11
+ * state:"queued", estimatedCostCU, deadlineAt, idempotentReplay}`.
12
+ * Request body = the sync body; one job = one user action = `n` images
13
+ * (held up-front, settled on actual output, refunded on failure /
14
+ * cancel). Same `idempotencyKey` rules as music (≤64 chars, 24 h).
15
+ * • `anna.image.getJob({jobId})` (re-signs every `result.images[].url`,
16
+ * ~30 min), `listJobs({state?, clientTag?, limit?, cursor?})`,
17
+ * `cancelJob({jobId})` (queued = full refund; running = best-effort).
18
+ * • `anna.image.generateAwait(args, {onProgress, signal, timeoutMs})` /
19
+ * `editAwait(...)` — the image twins of `video.generateAwait`
20
+ * (shared `mediaGenerateAwaitImpl`, now parameterised by the create
21
+ * method and filtering `media_job` events by `kind === "image"` /
22
+ * `ijob_` prefix). Resolve with the terminal job view whose
23
+ * `result.images[]` carry `{url, r2Key, mimeType, width, height,
24
+ * expiresIn}`; `url` is `null` once the object was GC'd (7 days).
25
+ * • `anna.image.resign({r2Keys})` → `{urls:[{r2Key, url, expiresIn}]}` —
26
+ * re-sign any already-paid artifact (sync result `r2_key` or job
27
+ * `r2Key`) for 7 days; one foreign / malformed key fails the whole call
28
+ * with `IMAGE_ASSET_NOT_FOUND` (`details.data.index`).
29
+ * • `anna.image.onJobEvent(fn)` — raw `media_job` stream (kind "image").
30
+ * Errors: `IMAGE_JOB_NOT_FOUND` / `IMAGE_JOB_NOT_CANCELLABLE` /
31
+ * `IMAGE_CONTENT_REJECTED` / `IMAGE_JOB_EXPIRED` / `IMAGE_ASSET_NOT_FOUND`
32
+ * via `HostRpcError` (name + `details.jsonrpc_code`; `details.data` now
33
+ * carries the facade `data` — `allowed`, `alternatives`, `index`). The sync
34
+ * path's provider content rejection moved from `APP_PROVIDER_ERROR` to
35
+ * `IMAGE_CONTENT_REJECTED` (-32115). `llm.catalog` image entries gain
36
+ * `capabilities.jobs` and `image_edit` entries report the real
37
+ * `options.n.max` (= grant `maxPerCallEdit`). Grant: `image_grant`
38
+ * (`allowGenerate` / `allowEdit`) — no new grant; manifest `host_api.image`
39
+ * must list the new method names. Coordinated: dispatcher / schema 0.29.0,
40
+ * anna-app-core 0.26.0, runtime-local a30, cli 0.1.60.
41
+ *
42
+ * v0.24.0 — Theme & locale propagation (design:
43
+ * anna-app-theme-propagation.md §2/§4, extended with locale per
44
+ * docs/design/apps/anna-music.md §12.2-G8).
45
+ * The host now tells every App which theme and UI language the user has
46
+ * chosen, so Apps no longer have to guess from `prefers-color-scheme` /
47
+ * `navigator.language`:
48
+ * • Initial values ride on the iframe URL (`?theme=light|dark&themeMode=
49
+ * light|dark|system&lang=en|zh-CN`) and are read synchronously in
50
+ * `connect()` — before any RPC, so the first paint is already right.
51
+ * • Live changes arrive as one-way host→app broadcast events
52
+ * `theme.changed {theme, mode}` and `locale.changed {lang}` (same
53
+ * envelope as `auth.refresh`; no `host_api` grant involved).
54
+ * • Read-only mirrors `rt.theme`, `rt.themeMode`, `rt.locale` are kept
55
+ * fresh even without subscribers; `rt.onThemeChange(fn)` /
56
+ * `rt.onLocaleChange(fn)` subscribe AND replay the current value once.
57
+ * Hosts older than this release send neither — the SDK falls back to
58
+ * `prefers-color-scheme` / `navigator.language` so old+new combinations
59
+ * keep working. No dispatcher / schema / backend change (additive).
60
+ *
61
+ * v0.23.0 — Music generation surface (design:
62
+ * platform-media-generation-music.md §7/§9/§12.1).
63
+ * Adds `anna.music.{generate,getJob,cancelJob,listJobs}` (async music
64
+ * jobs, `mjob_…` ids; same state machine / `media_job` events /
65
+ * pre-hold→settle→refund billing as video) and
66
+ * `anna.music.generateAwait(args, {onProgress, signal, timeoutMs})` —
67
+ * the music twin of `video.generateAwait` (shared implementation).
68
+ * `music.generate` args: `{prompt, lyrics?, instrumental?, durationSec?,
69
+ * format?, referenceImageUrl?, options?, model?, clientTag?,
70
+ * idempotencyKey?}`; replies carry `idempotentReplay` — when a replay is
71
+ * already terminal, `generateAwait` resolves immediately without polling.
72
+ * Unsupported features raise `MUSIC_FEATURE_UNSUPPORTED` (-32165) with
73
+ * `error.data.alternatives` (model names that support the feature) —
74
+ * never a silent downgrade. Terminal result: `{url, mimeType,
75
+ * durationSec|null, lyrics|null, seed, expiresIn}`.
76
+ * `video.generate` additionally accepts `idempotencyKey` (same 24h replay
77
+ * semantics). Requires manifest `ui.host_api.music` + per-app
78
+ * `media_grant.music`. Coordinated versions: dispatcher_version 0.28.0 +
79
+ * schema 0.28.0 + anna-app-core 0.25.0. Additive: old hosts reject the new
80
+ * namespace with `unknown_method`.
81
+ *
82
+ * v0.22.0 — Schema-driven media options (design:
83
+ * developer-model-playground-and-tts-options-schema.md §5.12, PR1/PR2).
84
+ * Contract-only release — every namespace is a pass-through proxy, so no
85
+ * runtime code changes; this documents the new wire fields:
86
+ * • `anna.llm.catalog()` models carry `isPlatformDefault` (who the host
87
+ * routes to when the user has no preference; `isUserPreferred` unchanged)
88
+ * and `capabilities.options` is a self-describing schema v2
89
+ * (`{type: "range"|"select"|"boolean"|"text"|"size", min, max, step,
90
+ * values, default, scope, label?, help?, affectsPrice?, custom?}`).
91
+ * `catalog({serviceType: "tts", voiceLanguage: "zh"})` filters
92
+ * `capabilities.voices[]`, whose entries now carry
93
+ * `gender? | accent? | age? | tags?`. `image_gen` / `image_edit` entries
94
+ * are populated (`options`, `sizeInput: "size"|"aspect_ratio"|"both"`,
95
+ * `edit: {referenceImages, maxReferenceImages?, mask}`, per-image CU
96
+ * `pricing`). `video_gen` entries add `capabilities.options` too, keyed
97
+ * by the `video.generate` request fields (`durationSec`, `resolution`,
98
+ * `aspectRatio`, `generateAudio`) so a rendered form merges 1:1 into the
99
+ * request; the legacy `duration / resolutions / aspectRatios` keys stay.
100
+ * • `anna.audio.speak({…, params?})` — `params` = any key of
101
+ * `capabilities.options`; legacy top-level `speed/language/timestamps/
102
+ * format` still work (merged, `params` wins). Response adds `params`
103
+ * (normalised, as sent to the provider) and `ignoredParams` (keys the
104
+ * model does not declare — dropped, never surcharged). New error
105
+ * `-32149 AUDIO_OPTION_INVALID` (`data.{key, reason, allowed}`).
106
+ * • `anna.image.generate/edit({…, model?, params?, fit?, aspect_ratio?})`
107
+ * — `model` = exact catalogue name (unknown → `-32110
108
+ * IMAGE_MODEL_UNAVAILABLE` + `data.allowed`); `modelPreferences.hints`
109
+ * stays as a legacy input. `fit: "nearest"` (default — closest size,
110
+ * same orientation) | `"strict"` (`-32111 IMAGE_SIZE_UNSUPPORTED` +
111
+ * `data.allowed`). `params` validated per model (`-32112
112
+ * IMAGE_OPTION_INVALID`). Response adds `requestedSize`, `size`,
113
+ * `sizeAdjusted`, `aspectRatio`, `fit`, `params`, `ignoredParams`;
114
+ * `images[].width/height` are the real decoded dimensions.
115
+ * Additive — old hosts ignore the new request fields.
3
116
  *
4
117
  * v0.21.0 — App realtime voice session (design:
5
118
  * app-realtime-voice-session-and-executa-transcribe.md §5.2 / §5.3, PB2).
@@ -579,15 +692,15 @@
579
692
  // billedCostCU}); `result.url` is a ~30 min presigned GET — call
580
693
  // `anna.video.getJob({jobId})` again to re-sign after expiry.
581
694
 
582
- function mediaJobErrorFromView(view) {
695
+ function mediaJobErrorFromView(view, ns = "video") {
583
696
  const e = view.error || {};
584
697
  const code =
585
698
  e.code ||
586
699
  (view.state === "expired"
587
- ? "video_timeout"
700
+ ? `${ns}_timeout`
588
701
  : view.state === "cancelled"
589
702
  ? "cancelled"
590
- : "video_failed");
703
+ : `${ns}_failed`);
591
704
  const err = new Error(
592
705
  e.message || `media job ${view.jobId} ended as ${view.state}`
593
706
  );
@@ -597,10 +710,20 @@
597
710
  return err;
598
711
  }
599
712
 
600
- function videoGenerateAwaitImpl(rt, args, opts = {}) {
713
+ // Shared by video (v0.20.0), music (v0.23.0) and image (v0.25.0): `ns`
714
+ // selects the RPC namespace; wire shapes are identical except the music /
715
+ // image job views carry `idempotentReplay` (a terminal replay resolves
716
+ // without polling). `impl.createMethod` (default "generate") lets image
717
+ // submit through `generateAsync` / `editAsync` while the sync `generate` /
718
+ // `edit` keep their contract; `impl.kindFilter` (default = ns) drops
719
+ // `media_job` events of other kinds sharing the stream.
720
+ function mediaGenerateAwaitImpl(rt, ns, args, opts = {}, impl = {}) {
601
721
  const onProgress =
602
722
  typeof opts.onProgress === "function" ? opts.onProgress : null;
603
723
  const signal = opts.signal || null;
724
+ const createMethod = impl.createMethod || "generate";
725
+ const kindFilter = impl.kindFilter || ns;
726
+ const label = `${ns}.${impl.awaitName || "generateAwait"}`;
604
727
 
605
728
  return new Promise((resolve, reject) => {
606
729
  let settled = false;
@@ -658,17 +781,23 @@
658
781
  if (settled || pollInFlight || !jobId) return;
659
782
  pollInFlight = true;
660
783
  try {
661
- const view = await rt.call("video", "getJob", { jobId });
784
+ const view = await rt.call(ns, "getJob", { jobId });
662
785
  if (view.progress) {
663
786
  deliverProgress(view.progress.seq, view.progress, view.state);
664
787
  }
665
788
  if (JOB_TERMINAL_STATES.has(view.state)) {
666
789
  if (view.state === "succeeded") settleOk(view);
667
- else settleErr(mediaJobErrorFromView(view));
790
+ else settleErr(mediaJobErrorFromView(view, ns));
668
791
  return;
669
792
  }
670
793
  } catch (e) {
671
- if (e && (e.code === "VIDEO_JOB_NOT_FOUND" || e.code === "job_not_found")) {
794
+ if (
795
+ e &&
796
+ (e.code === "VIDEO_JOB_NOT_FOUND" ||
797
+ e.code === "MUSIC_JOB_NOT_FOUND" ||
798
+ e.code === "IMAGE_JOB_NOT_FOUND" ||
799
+ e.code === "job_not_found")
800
+ ) {
672
801
  settleErr(e);
673
802
  return;
674
803
  }
@@ -681,6 +810,7 @@
681
810
 
682
811
  const onJobEvent = (payload) => {
683
812
  if (settled || !payload || payload.jobId !== jobId) return;
813
+ if (payload.kind && payload.kind !== kindFilter) return;
684
814
  eventSeen = true;
685
815
  deliverProgress(payload.seq, payload.progress, payload.state);
686
816
  // Terminal push → fetch the authoritative view immediately (the
@@ -690,19 +820,25 @@
690
820
 
691
821
  const start = async () => {
692
822
  if (signal && signal.aborted) {
693
- const err = new Error("video.generateAwait aborted before start");
823
+ const err = new Error(`${label} aborted before start`);
694
824
  err.code = "cancelled";
695
825
  settleErr(err);
696
826
  return;
697
827
  }
698
828
  let created;
699
829
  try {
700
- created = await rt.call("video", "generate", args || {});
830
+ created = await rt.call(ns, createMethod, args || {});
701
831
  } catch (e) {
702
832
  settleErr(e);
703
833
  return;
704
834
  }
705
835
  jobId = created.jobId;
836
+ // Idempotent replay of an already-terminal job: nothing to wait for.
837
+ if (created.idempotentReplay && JOB_TERMINAL_STATES.has(created.state)) {
838
+ if (created.state === "succeeded") settleOk(created);
839
+ else settleErr(mediaJobErrorFromView(created, ns));
840
+ return;
841
+ }
706
842
  const deadlineMs = created.deadlineAt
707
843
  ? Date.parse(created.deadlineAt)
708
844
  : NaN;
@@ -713,9 +849,9 @@
713
849
  : 35 * 60 * 1000;
714
850
  wallTimer = setTimeout(() => {
715
851
  const err = new Error(
716
- `video.generateAwait wall clock elapsed after ${wallMs}ms; ` +
852
+ `${label} wall clock elapsed after ${wallMs}ms; ` +
717
853
  `job ${jobId} may still be rendering — recover it with ` +
718
- `anna.video.getJob({jobId})`
854
+ `anna.${ns}.getJob({jobId})`
719
855
  );
720
856
  err.code = "wait_timeout";
721
857
  settleErr(err);
@@ -725,7 +861,7 @@
725
861
  onAbort = () => {
726
862
  // queued cancel = full refund; running cancel is best-effort
727
863
  // (provider may refuse — the job then runs to terminal).
728
- rt.call("video", "cancelJob", { jobId }).catch(() => {});
864
+ rt.call(ns, "cancelJob", { jobId }).catch(() => {});
729
865
  schedulePoll(0);
730
866
  };
731
867
  signal.addEventListener("abort", onAbort, { once: true });
@@ -737,7 +873,7 @@
737
873
  });
738
874
  }
739
875
 
740
- function buildVideoNamespace(rt) {
876
+ function buildMediaJobNamespace(rt, ns) {
741
877
  return new Proxy(
742
878
  {},
743
879
  {
@@ -745,18 +881,71 @@
745
881
  if (typeof method !== "string") return undefined;
746
882
  if (method === "onJobEvent") {
747
883
  // Raw `media_job` host events ({jobId, state, seq, progress,
748
- // error, terminal}). Most apps should prefer generateAwait.
884
+ // error, terminal}) — shared stream; filter by `jobId` prefix
885
+ // (`vjob_` / `mjob_`) or `kind` when both namespaces are used.
749
886
  return (fn) => rt.on("media_job", fn);
750
887
  }
751
888
  if (method === "generateAwait") {
752
- return (args, opts) => videoGenerateAwaitImpl(rt, args, opts || {});
889
+ return (args, opts) => mediaGenerateAwaitImpl(rt, ns, args, opts || {});
753
890
  }
754
- return (args, opts) => rt.call("video", method, args || {}, opts);
891
+ return (args, opts) => rt.call(ns, method, args || {}, opts);
755
892
  },
756
893
  }
757
894
  );
758
895
  }
759
896
 
897
+ function buildVideoNamespace(rt) {
898
+ return buildMediaJobNamespace(rt, "video");
899
+ }
900
+
901
+ // v0.23.0 — anna.music.* (platform-media-generation-music.md §12.1)
902
+ function buildMusicNamespace(rt) {
903
+ return buildMediaJobNamespace(rt, "music");
904
+ }
905
+
906
+ // v0.25.0 — anna.image.* (platform-media-generation-image-jobs.md §12.1):
907
+ // the plain `image` proxy (sync generate / edit / resign + job four-pack)
908
+ // wrapped with `generateAwait` / `editAwait` (submit via generateAsync /
909
+ // editAsync, then the shared await loop filtered to kind "image") and
910
+ // `onJobEvent` (raw `media_job` stream, image events only).
911
+ function buildImageNamespace(rt) {
912
+ const base = buildNamespace(rt, "image");
913
+ return new Proxy(base, {
914
+ get(target, method) {
915
+ if (typeof method !== "string") return undefined;
916
+ if (method === "onJobEvent") {
917
+ return (fn) =>
918
+ rt.on("media_job", (payload) => {
919
+ if (!payload) return;
920
+ const isImage =
921
+ payload.kind === "image" ||
922
+ (!payload.kind &&
923
+ typeof payload.jobId === "string" &&
924
+ payload.jobId.startsWith("ijob_"));
925
+ if (isImage) fn(payload);
926
+ });
927
+ }
928
+ if (method === "generateAwait") {
929
+ return (args, opts) =>
930
+ mediaGenerateAwaitImpl(rt, "image", args, opts || {}, {
931
+ createMethod: "generateAsync",
932
+ kindFilter: "image",
933
+ awaitName: "generateAwait",
934
+ });
935
+ }
936
+ if (method === "editAwait") {
937
+ return (args, opts) =>
938
+ mediaGenerateAwaitImpl(rt, "image", args, opts || {}, {
939
+ createMethod: "editAsync",
940
+ kindFilter: "image",
941
+ awaitName: "editAwait",
942
+ });
943
+ }
944
+ return target[method];
945
+ },
946
+ });
947
+ }
948
+
760
949
  // ---- Agent namespace (v0.2.0) ----
761
950
  //
762
951
  // Exposes both raw RPCs (`anna.agent.session.create({submode, ...})`,
@@ -1840,6 +2029,11 @@ var AnnaVoiceClientCore = (function () {
1840
2029
  this.app = null;
1841
2030
  this.runtimeState = null;
1842
2031
  this.geometry = null;
2032
+ // v0.24.0 host context mirrors (filled by connect() from the URL, then
2033
+ // kept fresh by `theme.changed` / `locale.changed` broadcasts).
2034
+ this.theme = null; // 'light' | 'dark'
2035
+ this.themeMode = null; // 'light' | 'dark' | 'system'
2036
+ this.locale = null; // BCP-47-ish host tag, e.g. 'en' | 'zh-CN'
1843
2037
 
1844
2038
  // namespace proxies
1845
2039
  this.tools = buildToolsNamespace(this);
@@ -1858,12 +2052,16 @@ var AnnaVoiceClientCore = (function () {
1858
2052
  this.agent = buildAgentNamespace(this);
1859
2053
 
1860
2054
  // ---- 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?})
2055
+ // anna.image.generate({prompt, n?, size?, aspect_ratio?, model?, params?,
2056
+ // fit?: "nearest"|"strict", reference_image_urls?, metadata?})
2057
+ // → {images:[{url,width,height,…}], model, requestedSize, size,
2058
+ // sizeAdjusted, aspectRatio, fit, params, ignoredParams, usage}
2059
+ // anna.image.edit({image_url, prompt, n?, size?, aspect_ratio?, model?,
2060
+ // params?, fit?, mask_url?, metadata?}) → same shape (v0.22.0 fields)
1863
2061
  // anna.upload.inline({filename, mime_type, content_b64, purpose?, metadata?})
1864
2062
  // anna.upload.negotiate({filename, mime_type, size_bytes, purpose?, metadata?})
1865
2063
  // anna.upload.confirm({r2_key})
1866
- this.image = buildNamespace(this, "image");
2064
+ this.image = buildImageNamespace(this);
1867
2065
  this.upload = buildNamespace(this, "upload");
1868
2066
 
1869
2067
  // ---- video / audio namespaces (v0.20.0; media generation) ----
@@ -1871,12 +2069,24 @@ var AnnaVoiceClientCore = (function () {
1871
2069
  // aspectRatio?, generateAudio?, model?, clientTag?}) → {jobId, ...}
1872
2070
  // anna.video.{getJob,cancelJob,listJobs}({jobId|filters})
1873
2071
  // anna.video.generateAwait(args, {onProgress, signal, timeoutMs})
1874
- // anna.audio.speak({text, voice?, language?, format?, speed?,
1875
- // delivery?}) → {url|audioBase64, mimeType, charCount, billedCostCU}
2072
+ // anna.audio.speak({text, model?, voice?, params?, language?, format?,
2073
+ // speed?, delivery?}) → {url|audioBase64, mimeType, charCount,
2074
+ // billedCostCU, model, voice, params, ignoredParams} (v0.22.0 fields)
1876
2075
  // anna.audio.transcribe({audioUrl|audioBase64, language?}) → {text, ...}
1877
- // Capability discovery: anna.llm.catalog({serviceType?}).
2076
+ // Capability discovery: anna.llm.catalog({serviceType?, voiceLanguage?})
2077
+ // → {models:[{modelName, isUserPreferred, isPlatformDefault,
2078
+ // capabilities:{options (schema v2), voices?, sizeInput?, edit?, …},
2079
+ // pricing}], quota}.
1878
2080
  // Requires manifest ui.host_api.video / .audio + per-app media_grant.
1879
2081
  this.video = buildVideoNamespace(this);
2082
+ // v0.23.0: anna.music.{generate,getJob,cancelJob,listJobs,generateAwait}
2083
+ // ({prompt, lyrics?, instrumental?, durationSec?, format?,
2084
+ // referenceImageUrl?, options?, model?, clientTag?, idempotencyKey?})
2085
+ // → {jobId:"mjob_…", kind:"music", state, estimatedCostCU, deadlineAt,
2086
+ // idempotentReplay}; terminal result {url, mimeType, durationSec|null,
2087
+ // lyrics|null, seed, expiresIn}. Requires ui.host_api.music +
2088
+ // media_grant.music.
2089
+ this.music = buildMusicNamespace(this);
1880
2090
  // v0.21.0: + anna.audio.session(config) → VoiceSession (host-bridge
1881
2091
  // relayed realtime ASR→LLM→TTS, barge-in, setContext/say),
1882
2092
  // anna.audio.mic() / anna.audio.player() client helpers.
@@ -2007,6 +2217,12 @@ var AnnaVoiceClientCore = (function () {
2007
2217
  // handlers (and later reads) observe the updated values.
2008
2218
  if (msg.event === "entry_payload") {
2009
2219
  this.entryPayload = msg.payload || {};
2220
+ } else if (msg.event === "theme.changed" && msg.payload) {
2221
+ // v0.24.0: cache first so late subscribers / plain reads see it.
2222
+ if (msg.payload.theme === "light" || msg.payload.theme === "dark") this.theme = msg.payload.theme;
2223
+ if (msg.payload.mode) this.themeMode = String(msg.payload.mode);
2224
+ } else if (msg.event === "locale.changed" && msg.payload) {
2225
+ if (msg.payload.lang) this.locale = String(msg.payload.lang);
2010
2226
  } else if (msg.event === "runtime_state_synced") {
2011
2227
  const patch = msg.payload && msg.payload.patch;
2012
2228
  if (patch) {
@@ -2025,6 +2241,28 @@ var AnnaVoiceClientCore = (function () {
2025
2241
  return () => set.delete(fn);
2026
2242
  }
2027
2243
 
2244
+ /**
2245
+ * v0.24.0 — subscribe to host theme changes. Replays the current value
2246
+ * immediately so callers never race the handshake. Returns unsubscribe.
2247
+ * @param {(t:{theme:'light'|'dark', mode:'light'|'dark'|'system'})=>void} fn
2248
+ */
2249
+ onThemeChange(fn) {
2250
+ const off = this.on("theme.changed", (p) => fn({ theme: this.theme, mode: this.themeMode, ...(p || {}) }));
2251
+ try { fn({ theme: this.theme, mode: this.themeMode }); } catch (_) {}
2252
+ return off;
2253
+ }
2254
+
2255
+ /**
2256
+ * v0.24.0 — subscribe to host UI-language changes (`{lang}`), replaying
2257
+ * the current value immediately. Returns unsubscribe.
2258
+ * @param {(l:{lang:string})=>void} fn
2259
+ */
2260
+ onLocaleChange(fn) {
2261
+ const off = this.on("locale.changed", (p) => fn({ lang: this.locale, ...(p || {}) }));
2262
+ try { fn({ lang: this.locale }); } catch (_) {}
2263
+ return off;
2264
+ }
2265
+
2028
2266
  call(ns, method, args, opts) {
2029
2267
  if (this._closed) return Promise.reject(new Error("runtime closed"));
2030
2268
  const timeoutMs =
@@ -2111,6 +2349,15 @@ var AnnaVoiceClientCore = (function () {
2111
2349
  throw new Error("[anna-sdk] missing wid/t URL parameters");
2112
2350
  }
2113
2351
  const rt = new AnnaAppRuntime({ windowUuid: wid, token, parent: window.parent });
2352
+ // v0.24.0: host context from the iframe URL — synchronous, pre-RPC, so
2353
+ // the first paint already matches the dashboard. Old hosts omit these;
2354
+ // fall back to the browser's own signals.
2355
+ const urlTheme = params.get("theme");
2356
+ rt.theme = urlTheme === "light" || urlTheme === "dark"
2357
+ ? urlTheme
2358
+ : (typeof window.matchMedia === "function" && window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
2359
+ rt.themeMode = params.get("themeMode") || (urlTheme ? rt.theme : "system");
2360
+ rt.locale = params.get("lang") || (typeof navigator !== "undefined" && navigator.language) || "en";
2114
2361
  const hello = await rt.call("window", "hello", {});
2115
2362
  rt.capabilities = hello.capabilities;
2116
2363
  rt.viewMeta = hello.view_meta;
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.25.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",