@anna-ai/app-runtime 0.1.0 → 0.4.2

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 +28 -0
  2. package/dist/index.js +288 -15
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -37,6 +37,34 @@ anna.on("entry_payload", (p) => console.log(p));
37
37
  The host validates every call against the app's manifest ACL before
38
38
  forwarding to the backend.
39
39
 
40
+ ## RPC timeouts
41
+
42
+ Each call has a per-namespace default; apps can override per call:
43
+
44
+ ```js
45
+ // Use the namespace default (image: 180s)
46
+ const out = await anna.image.generate({ prompt: "..." });
47
+
48
+ // Override for one call (e.g. high-res / many images)
49
+ const out = await anna.image.generate(
50
+ { prompt: "...", n: 4, size: "2048x2048" },
51
+ { timeoutMs: 240000 }
52
+ );
53
+ ```
54
+
55
+ | Namespace | Default | Rationale |
56
+ | --- | --- | --- |
57
+ | `image.*` | 180 s | Matches host's upstream provider timeout (Seedream / Qwen / native) |
58
+ | `upload.*` | 120 s | Large multipart / negotiate+confirm |
59
+ | `agent.*` | 300 s | `session.run` loops model + tools many turns |
60
+ | `llm.*` | 180 s | Long completions / large context |
61
+ | everything else | 30 s | storage / chat / window / prefs / fs / tools / artifact |
62
+
63
+ The timeout is a *client-side* deadline. The host bridge fetch has no
64
+ abort signal — the backend always runs to completion, but a timed-out
65
+ promise rejects with `Error("RPC <ns>.<method> timed out after Nms")`
66
+ and the eventual response is discarded.
67
+
40
68
  ## Where the script comes from
41
69
 
42
70
  | Environment | Source |
package/dist/index.js CHANGED
@@ -1,15 +1,44 @@
1
1
  /**
2
- * Anna App Runtime SDK — v0.1.0
2
+ * Anna App Runtime SDK — v0.4.1
3
3
  *
4
- * Loaded by every Anna App iframe. Provides a typed proxy over the
5
- * postMessage RPC bridge to the host (Anna dashboard). All host calls go
6
- * through the host page (parent window), which validates them against the
7
- * app's manifest ACL before forwarding to the backend.
4
+ * v0.4.1 — Per-namespace default RPC timeouts and per-call override.
5
+ * image.* / upload.* / agent.* / llm.* used to share the 30s default,
6
+ * but real LLM / image-gen latency easily exceeds that on high-res
7
+ * prompts (Seedream 5.0 @ 2048x2048 can take 60-120s). New defaults:
8
+ * image: 180s upload: 120s agent: 300s llm: 180s
9
+ * storage: 30s chat/window/...: 30s (unchanged)
10
+ * Any call can override via a second arg, e.g.
11
+ * await anna.image.generate(args, { timeoutMs: 240000 })
12
+ *
13
+ * Loaded by every Anna App iframe as a native ES module via
14
+ * `import { AnnaAppRuntime } from "/static/anna-apps/_sdk/latest/index.js"`.
15
+ * Provides a typed proxy over the postMessage RPC bridge to the host
16
+ * (Anna dashboard). All host calls go through the host page (parent
17
+ * window), which validates them against the app's manifest ACL before
18
+ * forwarding to the backend.
19
+ *
20
+ * v0.4.0 — BREAKING: removed the cross-origin HTTP shim and the
21
+ * `AnnaHostError` class. `anna.image.{generate,edit}` and
22
+ * `anna.upload.{inline,negotiate,confirm}` now go through the same
23
+ * postMessage → `/api/v1/anna-apps/runtime/rpc` dispatcher channel as
24
+ * every other namespace (symmetric with `anna.storage.*` /
25
+ * `anna.llm.complete`). The dispatcher mints the underlying
26
+ * `app_session_token` server-side; the iframe never holds capability
27
+ * credentials. Errors arrive as the standard RPC error shape:
28
+ * `Error` with `.code` (e.g. `APP_ERR_NOT_GRANTED`,
29
+ * `APP_ERR_QUOTA_EXCEEDED`, `not_implemented`) and `.details`. Apps
30
+ * that previously branched on `err.status === 403/415/429` must rewrite
31
+ * to branch on `err.code` (see VERSIONS.md changelog for the mapping).
32
+ *
33
+ * v0.3.1 — packaged as pure ESM (no IIFE / window-global). Consumers must
34
+ * use `<script type="module">` + `import`. Legacy `<script src=...>`
35
+ * loading is no longer supported.
8
36
  *
9
37
  * Envelope: { kind:"req"|"res"|"event", id, ns, method, args | result | error }
10
38
  *
11
39
  * Usage inside the iframe:
12
40
  *
41
+ * import { AnnaAppRuntime } from "/static/anna-apps/_sdk/latest/index.js";
13
42
  * const anna = await AnnaAppRuntime.connect();
14
43
  * // Mint-only tool_ids (tool-{handle}-{slug}-{uniq}) carry no separator,
15
44
  * // so the target plugin method is supplied via `method`:
@@ -22,27 +51,199 @@
22
51
  * anna.on("entry_payload", (p) => console.log(p));
23
52
  */
24
53
 
25
- (function (global) {
26
- "use strict";
27
-
28
- // ---- Internals ----
54
+ // ---- Internals ----
29
55
  function uuid() {
30
56
  return (
31
57
  Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 10)
32
58
  );
33
59
  }
34
60
 
35
- // Build a target proxy that exposes namespace.method(args) calls.
61
+ // Per-namespace default RPC timeout (ms). Picked to comfortably cover
62
+ // upstream provider P99 latency (host bridge fetch is unbounded; backend
63
+ // httpx is 180s for image). Apps can override per-call via the second
64
+ // arg: `anna.image.generate(args, { timeoutMs: 240000 })`.
65
+ const DEFAULT_TIMEOUTS_BY_NS = {
66
+ image: 180000, // image gen/edit; matches src/tools/image_generation_tool.py httpx=180s
67
+ upload: 120000, // large multipart / negotiate+confirm
68
+ agent: 300000, // session.run can loop through model+tools many turns
69
+ llm: 180000, // long completions / large context
70
+ // `tools.invoke` host bound = 65s plugin + 2s grace + 3s SDK margin.
71
+ // Apps requesting longer per call must pass { timeoutMs }; bounded
72
+ // server-side by ANNA_APP_TOOLS_INVOKE_TIMEOUT_MAX_MS.
73
+ tools: 70000,
74
+ };
75
+ const DEFAULT_TIMEOUT_MS = 30000;
76
+
77
+ // Build a target proxy that exposes namespace.method(args, opts?) calls.
78
+ // The optional second arg accepts `{ timeoutMs }`; missing → namespace
79
+ // default → 30000 fallback.
36
80
  function buildNamespace(rt, ns) {
37
81
  return new Proxy(
38
82
  {},
39
83
  {
40
84
  get(_, method) {
41
85
  if (typeof method !== "string") return undefined;
42
- return (args) => rt.call(ns, method, args || {});
86
+ return (args, opts) => rt.call(ns, method, args || {}, opts);
87
+ },
88
+ }
89
+ );
90
+ }
91
+
92
+ // ---- Agent namespace (v0.2.0) ----
93
+ //
94
+ // Exposes both raw RPCs (`anna.agent.session.create({submode, ...})`,
95
+ // `anna.agent.session.run({...})`, etc.) AND a higher-level helper
96
+ // `anna.agent.session(opts)` that returns an AgentSession instance
97
+ // for ergonomic use in apps:
98
+ //
99
+ // const sess = await anna.agent.session({ submode: "auto" });
100
+ // for await (const ev of sess.run({ content: "hi" })) {
101
+ // if (ev.event === "model_token") render(ev.text);
102
+ // }
103
+ function buildAgentNamespace(rt) {
104
+ const sessionRpcs = new Proxy(
105
+ {},
106
+ {
107
+ get(_, method) {
108
+ if (typeof method !== "string") return undefined;
109
+ return (args, opts) =>
110
+ rt.call("agent", "session." + method, args || {}, opts);
43
111
  },
44
112
  }
45
113
  );
114
+ const ns = {
115
+ // Higher-level: mint and return an AgentSession wrapper.
116
+ session: async (opts = {}) => {
117
+ const result = await rt.call("agent", "session.create", opts);
118
+ return new AgentSession(rt, result);
119
+ },
120
+ };
121
+ // Also expose raw RPC sub-methods on the function — apps can do
122
+ // `anna.agent.session.create(...)` if they want to manage state manually.
123
+ for (const m of ["create", "run", "cancel", "history", "delete"]) {
124
+ ns.session[m] = sessionRpcs[m];
125
+ }
126
+ return ns;
127
+ }
128
+
129
+ // ---- HTTP-backed namespaces removed in v0.4.0 ----
130
+ //
131
+ // `anna.image.*` and `anna.upload.*` are now plain postMessage RPCs
132
+ // (see the dispatcher's `image.*` / `upload.*` handlers in
133
+ // anna-app-core 0.3.0+). The dispatcher mints the underlying
134
+ // app_session_token in-process; the iframe never holds capability
135
+ // credentials. Errors arrive on the standard RPC envelope with
136
+ // `.code` set to the facade's `APP_ERR_*` value.
137
+
138
+ // AsyncIterable view over `rpc.stream` event chunks. Reassembles by `seq`
139
+ // so out-of-order arrivals are normalised; back-pressure is bounded only
140
+ // by the iframe's heap (events are small JSON blobs).
141
+ class AgentRunStream {
142
+ constructor(streamId, runId) {
143
+ this.streamId = streamId;
144
+ this.runId = runId;
145
+ this._queue = []; // ordered by seq
146
+ this._waiters = []; // resolvers awaiting next event
147
+ this._buffer = new Map(); // seq -> payload (out-of-order holding)
148
+ this._nextSeq = 1;
149
+ this._done = false;
150
+ }
151
+ _push(frame) {
152
+ const seq = Number(frame.seq || 0);
153
+ const payload = frame.payload;
154
+ const done = !!frame.done;
155
+ if (seq && seq !== this._nextSeq) {
156
+ this._buffer.set(seq, { payload, done });
157
+ return;
158
+ }
159
+ this._emit(payload, done);
160
+ this._nextSeq += 1;
161
+ // Drain consecutive buffered frames.
162
+ while (this._buffer.has(this._nextSeq)) {
163
+ const next = this._buffer.get(this._nextSeq);
164
+ this._buffer.delete(this._nextSeq);
165
+ this._emit(next.payload, next.done);
166
+ this._nextSeq += 1;
167
+ }
168
+ }
169
+ _emit(payload, done) {
170
+ if (payload != null) this._queue.push(payload);
171
+ if (done) this._done = true;
172
+ while (this._waiters.length && (this._queue.length || this._done)) {
173
+ const w = this._waiters.shift();
174
+ if (this._queue.length) w({ value: this._queue.shift(), done: false });
175
+ else w({ value: undefined, done: true });
176
+ }
177
+ }
178
+ [Symbol.asyncIterator]() {
179
+ const self = this;
180
+ return {
181
+ next() {
182
+ if (self._queue.length) {
183
+ return Promise.resolve({ value: self._queue.shift(), done: false });
184
+ }
185
+ if (self._done) return Promise.resolve({ value: undefined, done: true });
186
+ return new Promise((resolve) => self._waiters.push(resolve));
187
+ },
188
+ return() {
189
+ self._done = true;
190
+ while (self._waiters.length) self._waiters.shift()({ value: undefined, done: true });
191
+ return Promise.resolve({ value: undefined, done: true });
192
+ },
193
+ };
194
+ }
195
+ }
196
+
197
+ // Higher-level agent session wrapper. Holds the dispatcher-managed
198
+ // app_session_uuid; its methods are sugar around the raw `agent.session.*`
199
+ // RPCs.
200
+ class AgentSession {
201
+ constructor(rt, info) {
202
+ this._rt = rt;
203
+ this.app_session_uuid = info.app_session_uuid;
204
+ this.expires_in = info.expires_in;
205
+ this.submode = info.submode;
206
+ this.fixed_client_id = info.fixed_client_id || null;
207
+ this.granted_tools = info.granted_tools || [];
208
+ }
209
+ run(opts = {}) {
210
+ const args = Object.assign(
211
+ { app_session_uuid: this.app_session_uuid },
212
+ opts
213
+ );
214
+ const stream = new AgentRunStream(null, args.run_id || null);
215
+ // Kick off the RPC; once the host returns {stream_id, run_id} we
216
+ // register the stream so subsequent rpc.stream events flow into it.
217
+ this._rt.call("agent", "session.run", args).then(
218
+ (res) => {
219
+ stream.streamId = res.stream_id || stream.streamId;
220
+ stream.runId = res.run_id || stream.runId;
221
+ if (stream.streamId) this._rt._registerStream(stream.streamId, stream);
222
+ // If host returns done immediately (e.g. cached error), close.
223
+ if (!stream.streamId) stream._emit(null, true);
224
+ },
225
+ (err) => {
226
+ stream._emit({ event: "error", code: err.code, message: err.message }, true);
227
+ }
228
+ );
229
+ return stream;
230
+ }
231
+ cancel(runId) {
232
+ return this._rt.call("agent", "session.cancel", {
233
+ app_session_uuid: this.app_session_uuid,
234
+ run_id: runId,
235
+ });
236
+ }
237
+ history(opts = {}) {
238
+ return this._rt.call("agent", "session.history", Object.assign(
239
+ { app_session_uuid: this.app_session_uuid }, opts
240
+ ));
241
+ }
242
+ delete() {
243
+ return this._rt.call("agent", "session.delete", {
244
+ app_session_uuid: this.app_session_uuid,
245
+ });
246
+ }
46
247
  }
47
248
 
48
249
  class AnnaAppRuntime {
@@ -72,6 +273,25 @@
72
273
  this.prefs = buildNamespace(this, "prefs");
73
274
  this.window = buildNamespace(this, "window");
74
275
 
276
+ // ---- agent namespace (v0.2.0) ----
277
+ // Exposes session.{create,run,cancel,history,delete}; SDK also offers
278
+ // a higher-level `anna.agent.session(opts)` helper that returns an
279
+ // AgentSession bound to a fresh AnnaAppSession.
280
+ this.agent = buildAgentNamespace(this);
281
+
282
+ // ---- image / upload namespaces (v0.4.0; postMessage) ----
283
+ // anna.image.generate({prompt, n?, size?, reference_image_urls?, metadata?})
284
+ // anna.image.edit({image_url, prompt, n?, size?, mask_url?, metadata?})
285
+ // anna.upload.inline({filename, mime_type, content_b64, purpose?, metadata?})
286
+ // anna.upload.negotiate({filename, mime_type, size_bytes, purpose?, metadata?})
287
+ // anna.upload.confirm({r2_key})
288
+ this.image = buildNamespace(this, "image");
289
+ this.upload = buildNamespace(this, "upload");
290
+
291
+ // Reassembly buffers for `rpc.stream` events. Map<stream_id, AgentRunStream>.
292
+ this._streams = new Map();
293
+ this.on("rpc.stream", (payload) => this._onStreamFrame(payload || {}));
294
+
75
295
  window.addEventListener("message", (ev) => this._onMessage(ev));
76
296
  window.addEventListener("error", (ev) => {
77
297
  // best-effort error reporting
@@ -139,13 +359,22 @@
139
359
  return () => set.delete(fn);
140
360
  }
141
361
 
142
- call(ns, method, args, { timeoutMs = 30000 } = {}) {
362
+ call(ns, method, args, opts) {
143
363
  if (this._closed) return Promise.reject(new Error("runtime closed"));
364
+ const timeoutMs =
365
+ (opts && Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : null) ??
366
+ DEFAULT_TIMEOUTS_BY_NS[ns] ??
367
+ DEFAULT_TIMEOUT_MS;
144
368
  const id = uuid();
145
369
  return new Promise((resolve, reject) => {
146
370
  const timer = setTimeout(() => {
147
371
  this._pending.delete(id);
148
- reject(new Error(`RPC ${ns}.${method} timed out`));
372
+ reject(
373
+ new Error(
374
+ `RPC ${ns}.${method} timed out after ${timeoutMs}ms` +
375
+ ` (pass { timeoutMs } as the 2nd arg to override)`
376
+ )
377
+ );
149
378
  }, timeoutMs);
150
379
  this._pending.set(id, {
151
380
  resolve: (v) => { clearTimeout(timer); resolve(v); },
@@ -155,6 +384,8 @@
155
384
  });
156
385
  }
157
386
 
387
+ // (HTTP shim removed in v0.4.0 — image/upload now use postMessage.)
388
+
158
389
  _startHeartbeat() {
159
390
  this._heartbeatTimer = setInterval(() => {
160
391
  if (this._closed) return;
@@ -162,6 +393,42 @@
162
393
  }, 10000);
163
394
  }
164
395
 
396
+ _onStreamFrame(payload) {
397
+ const sid = payload.stream_id;
398
+ if (!sid) return;
399
+ const stream = this._streams.get(sid);
400
+ if (!stream) {
401
+ // Frame may have arrived before `agent.session.run` resolved with
402
+ // its stream_id. Buffer for a short window — the registration
403
+ // path drains this on `_registerStream`.
404
+ if (!this._earlyFrames) this._earlyFrames = new Map();
405
+ let q = this._earlyFrames.get(sid);
406
+ if (!q) { q = []; this._earlyFrames.set(sid, q); }
407
+ q.push(payload);
408
+ // Cap to avoid unbounded growth on truly orphaned streams.
409
+ if (q.length > 256) q.shift();
410
+ return;
411
+ }
412
+ stream._push(payload);
413
+ if (payload.done) this._streams.delete(sid);
414
+ }
415
+
416
+ _registerStream(streamId, stream) {
417
+ this._streams.set(streamId, stream);
418
+ // Drain any frames that arrived before the RPC reply.
419
+ const queued = this._earlyFrames && this._earlyFrames.get(streamId);
420
+ if (queued && queued.length) {
421
+ this._earlyFrames.delete(streamId);
422
+ for (const p of queued) {
423
+ stream._push(p);
424
+ if (p.done) {
425
+ this._streams.delete(streamId);
426
+ break;
427
+ }
428
+ }
429
+ }
430
+ }
431
+
165
432
  static async connect(options = {}) {
166
433
  // Discover credentials from URL
167
434
  const params = new URLSearchParams(location.search);
@@ -184,5 +451,11 @@
184
451
  }
185
452
  }
186
453
 
187
- global.AnnaAppRuntime = AnnaAppRuntime;
188
- })(typeof window !== "undefined" ? window : globalThis);
454
+ // Convenience static references (mirrors pre-0.3.1 layout where these
455
+ // hung off the AnnaAppRuntime global). `AnnaHostError` was removed in
456
+ // v0.4.0; apps should now branch on the standard RPC error `.code`.
457
+ AnnaAppRuntime.AgentSession = AgentSession;
458
+ AnnaAppRuntime.AgentRunStream = AgentRunStream;
459
+
460
+ export { AnnaAppRuntime, AgentSession, AgentRunStream };
461
+ export default AnnaAppRuntime;
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@anna-ai/app-runtime",
3
- "version": "0.1.0",
3
+ "version": "0.4.2",
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
+ "type": "module",
6
7
  "main": "./dist/index.js",
7
8
  "exports": {
8
9
  ".": {