@anna-ai/app-runtime 0.23.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 +73 -0
  2. package/dist/index.js +160 -9
  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`
@@ -160,6 +192,47 @@ song.idempotentReplay; // true when the key hit an existing job
160
192
  await anna.music.generate({ prompt: "ambient pad", model: "fal-ai/ace-step", durationSec: 30, instrumental: true });
161
193
  ```
162
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
+
163
236
  ### Model-aware options (v0.22.0)
164
237
 
165
238
  Every TTS / image model describes its knobs in `capabilities.options`
package/dist/index.js CHANGED
@@ -1,5 +1,62 @@
1
1
  /**
2
- * Anna App Runtime SDK — v0.23.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).
3
60
  *
4
61
  * v0.23.0 — Music generation surface (design:
5
62
  * platform-media-generation-music.md §7/§9/§12.1).
@@ -653,13 +710,20 @@
653
710
  return err;
654
711
  }
655
712
 
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 = {}) {
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 = {}) {
660
721
  const onProgress =
661
722
  typeof opts.onProgress === "function" ? opts.onProgress : null;
662
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"}`;
663
727
 
664
728
  return new Promise((resolve, reject) => {
665
729
  let settled = false;
@@ -731,6 +795,7 @@
731
795
  e &&
732
796
  (e.code === "VIDEO_JOB_NOT_FOUND" ||
733
797
  e.code === "MUSIC_JOB_NOT_FOUND" ||
798
+ e.code === "IMAGE_JOB_NOT_FOUND" ||
734
799
  e.code === "job_not_found")
735
800
  ) {
736
801
  settleErr(e);
@@ -745,6 +810,7 @@
745
810
 
746
811
  const onJobEvent = (payload) => {
747
812
  if (settled || !payload || payload.jobId !== jobId) return;
813
+ if (payload.kind && payload.kind !== kindFilter) return;
748
814
  eventSeen = true;
749
815
  deliverProgress(payload.seq, payload.progress, payload.state);
750
816
  // Terminal push → fetch the authoritative view immediately (the
@@ -754,14 +820,14 @@
754
820
 
755
821
  const start = async () => {
756
822
  if (signal && signal.aborted) {
757
- const err = new Error(`${ns}.generateAwait aborted before start`);
823
+ const err = new Error(`${label} aborted before start`);
758
824
  err.code = "cancelled";
759
825
  settleErr(err);
760
826
  return;
761
827
  }
762
828
  let created;
763
829
  try {
764
- created = await rt.call(ns, "generate", args || {});
830
+ created = await rt.call(ns, createMethod, args || {});
765
831
  } catch (e) {
766
832
  settleErr(e);
767
833
  return;
@@ -783,7 +849,7 @@
783
849
  : 35 * 60 * 1000;
784
850
  wallTimer = setTimeout(() => {
785
851
  const err = new Error(
786
- `${ns}.generateAwait wall clock elapsed after ${wallMs}ms; ` +
852
+ `${label} wall clock elapsed after ${wallMs}ms; ` +
787
853
  `job ${jobId} may still be rendering — recover it with ` +
788
854
  `anna.${ns}.getJob({jobId})`
789
855
  );
@@ -837,6 +903,49 @@
837
903
  return buildMediaJobNamespace(rt, "music");
838
904
  }
839
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
+
840
949
  // ---- Agent namespace (v0.2.0) ----
841
950
  //
842
951
  // Exposes both raw RPCs (`anna.agent.session.create({submode, ...})`,
@@ -1920,6 +2029,11 @@ var AnnaVoiceClientCore = (function () {
1920
2029
  this.app = null;
1921
2030
  this.runtimeState = null;
1922
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'
1923
2037
 
1924
2038
  // namespace proxies
1925
2039
  this.tools = buildToolsNamespace(this);
@@ -1947,7 +2061,7 @@ var AnnaVoiceClientCore = (function () {
1947
2061
  // anna.upload.inline({filename, mime_type, content_b64, purpose?, metadata?})
1948
2062
  // anna.upload.negotiate({filename, mime_type, size_bytes, purpose?, metadata?})
1949
2063
  // anna.upload.confirm({r2_key})
1950
- this.image = buildNamespace(this, "image");
2064
+ this.image = buildImageNamespace(this);
1951
2065
  this.upload = buildNamespace(this, "upload");
1952
2066
 
1953
2067
  // ---- video / audio namespaces (v0.20.0; media generation) ----
@@ -2103,6 +2217,12 @@ var AnnaVoiceClientCore = (function () {
2103
2217
  // handlers (and later reads) observe the updated values.
2104
2218
  if (msg.event === "entry_payload") {
2105
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);
2106
2226
  } else if (msg.event === "runtime_state_synced") {
2107
2227
  const patch = msg.payload && msg.payload.patch;
2108
2228
  if (patch) {
@@ -2121,6 +2241,28 @@ var AnnaVoiceClientCore = (function () {
2121
2241
  return () => set.delete(fn);
2122
2242
  }
2123
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
+
2124
2266
  call(ns, method, args, opts) {
2125
2267
  if (this._closed) return Promise.reject(new Error("runtime closed"));
2126
2268
  const timeoutMs =
@@ -2207,6 +2349,15 @@ var AnnaVoiceClientCore = (function () {
2207
2349
  throw new Error("[anna-sdk] missing wid/t URL parameters");
2208
2350
  }
2209
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";
2210
2361
  const hello = await rt.call("window", "hello", {});
2211
2362
  rt.capabilities = hello.capabilities;
2212
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.23.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",