@anna-ai/app-runtime 0.1.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 +59 -0
  2. package/dist/index.js +188 -0
  3. package/package.json +28 -0
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @anna-ai/app-runtime
2
+
3
+ Browser runtime SDK for Anna Apps. Loaded as a `<script>` inside every Anna
4
+ App iframe; exposes a global `AnnaAppRuntime` that proxies RPC calls over
5
+ `postMessage` to the host page (Anna dashboard in production, the
6
+ `anna-app dev` harness in local development).
7
+
8
+ ## Use inside an Anna App bundle
9
+
10
+ ```html
11
+ <!-- index.html -->
12
+ <script src="/static/anna-apps/_sdk/0.1.0/index.js" defer></script>
13
+ <script src="./app.js" type="module" defer></script>
14
+ ```
15
+
16
+ ```js
17
+ // app.js
18
+ const anna = await AnnaAppRuntime.connect();
19
+
20
+ await anna.window.set_title({ title: "My App" });
21
+
22
+ const out = await anna.tools.invoke({
23
+ tool_id: "tool-twitter-handle-twitter-tool-abcd1234",
24
+ method: "post_tweet",
25
+ args: { text: "hi" },
26
+ });
27
+
28
+ anna.on("entry_payload", (p) => console.log(p));
29
+ ```
30
+
31
+ ## Wire envelope
32
+
33
+ ```
34
+ { kind: "req"|"res"|"event", id, ns, method, args | result | error }
35
+ ```
36
+
37
+ The host validates every call against the app's manifest ACL before
38
+ forwarding to the backend.
39
+
40
+ ## Where the script comes from
41
+
42
+ | Environment | Source |
43
+ | --- | --- |
44
+ | Production (Anna dashboard) | `matrix-nexus` static server, path `/static/anna-apps/_sdk/<version>/index.js` |
45
+ | Local dev (`anna-app dev`) | `@anna-ai/cli` harness server resolves this package from its `node_modules` and serves the same path |
46
+
47
+ The bundle author writes the same `<script src="/static/anna-apps/_sdk/...">`
48
+ either way; the URL is part of the host contract.
49
+
50
+ ## Versioning
51
+
52
+ This package's version tracks `dispatcher_version` (wire protocol). See
53
+ [`packages/VERSIONS.md`](../VERSIONS.md) for the full pin matrix and bump
54
+ procedure.
55
+
56
+ ## Contents
57
+
58
+ Single file `dist/index.js` (~8 KB). Plain ES5 IIFE, no build step, runs
59
+ directly in any modern browser.
package/dist/index.js ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Anna App Runtime SDK — v0.1.0
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.
8
+ *
9
+ * Envelope: { kind:"req"|"res"|"event", id, ns, method, args | result | error }
10
+ *
11
+ * Usage inside the iframe:
12
+ *
13
+ * const anna = await AnnaAppRuntime.connect();
14
+ * // Mint-only tool_ids (tool-{handle}-{slug}-{uniq}) carry no separator,
15
+ * // so the target plugin method is supplied via `method`:
16
+ * const out = await anna.tools.invoke({
17
+ * tool_id: "tool-twitter-handle-twitter-tool-abcd1234",
18
+ * method: "post_tweet",
19
+ * args: { text: "hi" },
20
+ * });
21
+ * await anna.window.set_title({ title: "My App" });
22
+ * anna.on("entry_payload", (p) => console.log(p));
23
+ */
24
+
25
+ (function (global) {
26
+ "use strict";
27
+
28
+ // ---- Internals ----
29
+ function uuid() {
30
+ return (
31
+ Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 10)
32
+ );
33
+ }
34
+
35
+ // Build a target proxy that exposes namespace.method(args) calls.
36
+ function buildNamespace(rt, ns) {
37
+ return new Proxy(
38
+ {},
39
+ {
40
+ get(_, method) {
41
+ if (typeof method !== "string") return undefined;
42
+ return (args) => rt.call(ns, method, args || {});
43
+ },
44
+ }
45
+ );
46
+ }
47
+
48
+ class AnnaAppRuntime {
49
+ constructor(opts) {
50
+ this.windowUuid = opts.windowUuid;
51
+ this.token = opts.token;
52
+ this.targetOrigin = opts.targetOrigin || "*"; // host enforces sandbox
53
+ this.parent = opts.parent || window.parent;
54
+ this._pending = new Map(); // id -> {resolve, reject, retries}
55
+ this._handlers = new Map(); // event kind -> Set<fn>
56
+ this._closed = false;
57
+ this._handshake = null;
58
+ this._heartbeatTimer = null;
59
+ this.capabilities = null;
60
+ this.viewMeta = null;
61
+ this.entryPayload = null;
62
+ this.runtimeState = null;
63
+ this.geometry = null;
64
+
65
+ // namespace proxies
66
+ this.tools = buildNamespace(this, "tools");
67
+ this.chat = buildNamespace(this, "chat");
68
+ this.artifact = buildNamespace(this, "artifact");
69
+ this.llm = buildNamespace(this, "llm");
70
+ this.fs = buildNamespace(this, "fs");
71
+ this.storage = buildNamespace(this, "storage");
72
+ this.prefs = buildNamespace(this, "prefs");
73
+ this.window = buildNamespace(this, "window");
74
+
75
+ window.addEventListener("message", (ev) => this._onMessage(ev));
76
+ window.addEventListener("error", (ev) => {
77
+ // best-effort error reporting
78
+ this._post({
79
+ kind: "req",
80
+ id: uuid(),
81
+ ns: "window",
82
+ method: "report_error",
83
+ args: {
84
+ error: { message: String(ev.message), source: ev.filename, line: ev.lineno },
85
+ },
86
+ });
87
+ });
88
+ // Final flush on unload (best-effort)
89
+ window.addEventListener("pagehide", () => {
90
+ this._closed = true;
91
+ });
92
+ }
93
+
94
+ _post(envelope) {
95
+ try {
96
+ this.parent.postMessage(
97
+ Object.assign({ wid: this.windowUuid, t: this.token }, envelope),
98
+ this.targetOrigin
99
+ );
100
+ } catch (e) {
101
+ console.error("[anna-sdk] postMessage failed", e);
102
+ }
103
+ }
104
+
105
+ _onMessage(ev) {
106
+ const msg = ev.data;
107
+ if (!msg || typeof msg !== "object") return;
108
+ if (msg.wid && msg.wid !== this.windowUuid) return;
109
+
110
+ if (msg.kind === "res") {
111
+ const pending = this._pending.get(msg.id);
112
+ if (!pending) return;
113
+ this._pending.delete(msg.id);
114
+ if (msg.error) {
115
+ const err = new Error(msg.error.message || "RPC error");
116
+ err.code = msg.error.code;
117
+ err.details = msg.error.details;
118
+ pending.reject(err);
119
+ } else {
120
+ pending.resolve(msg.result);
121
+ }
122
+ return;
123
+ }
124
+
125
+ if (msg.kind === "event") {
126
+ if (msg.event === "auth.refresh" && msg.token) {
127
+ this.token = msg.token;
128
+ return;
129
+ }
130
+ const set = this._handlers.get(msg.event);
131
+ if (set) for (const fn of set) try { fn(msg.payload); } catch (_) {}
132
+ }
133
+ }
134
+
135
+ on(kind, fn) {
136
+ let set = this._handlers.get(kind);
137
+ if (!set) { set = new Set(); this._handlers.set(kind, set); }
138
+ set.add(fn);
139
+ return () => set.delete(fn);
140
+ }
141
+
142
+ call(ns, method, args, { timeoutMs = 30000 } = {}) {
143
+ if (this._closed) return Promise.reject(new Error("runtime closed"));
144
+ const id = uuid();
145
+ return new Promise((resolve, reject) => {
146
+ const timer = setTimeout(() => {
147
+ this._pending.delete(id);
148
+ reject(new Error(`RPC ${ns}.${method} timed out`));
149
+ }, timeoutMs);
150
+ this._pending.set(id, {
151
+ resolve: (v) => { clearTimeout(timer); resolve(v); },
152
+ reject: (e) => { clearTimeout(timer); reject(e); },
153
+ });
154
+ this._post({ kind: "req", id, ns, method, args: args || {} });
155
+ });
156
+ }
157
+
158
+ _startHeartbeat() {
159
+ this._heartbeatTimer = setInterval(() => {
160
+ if (this._closed) return;
161
+ this.call("window", "ready", {}).catch(() => {});
162
+ }, 10000);
163
+ }
164
+
165
+ static async connect(options = {}) {
166
+ // Discover credentials from URL
167
+ const params = new URLSearchParams(location.search);
168
+ const wid = options.windowUuid || params.get("wid");
169
+ const token = options.token || params.get("t");
170
+ if (!wid || !token) {
171
+ throw new Error("[anna-sdk] missing wid/t URL parameters");
172
+ }
173
+ const rt = new AnnaAppRuntime({ windowUuid: wid, token, parent: window.parent });
174
+ const hello = await rt.call("window", "hello", {});
175
+ rt.capabilities = hello.capabilities;
176
+ rt.viewMeta = hello.view_meta;
177
+ rt.entryPayload = hello.entry_payload || {};
178
+ rt.runtimeState = hello.runtime_state || {};
179
+ rt.geometry = hello.geometry || {};
180
+ rt._startHeartbeat();
181
+ // signal ready (host may show iframe at this point)
182
+ rt.call("window", "ready", {}).catch(() => {});
183
+ return rt;
184
+ }
185
+ }
186
+
187
+ global.AnnaAppRuntime = AnnaAppRuntime;
188
+ })(typeof window !== "undefined" ? window : globalThis);
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@anna-ai/app-runtime",
3
+ "version": "0.1.0",
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
+ "license": "MIT",
6
+ "main": "./dist/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "browser": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./dist/index.js": "./dist/index.js"
13
+ },
14
+ "files": [
15
+ "dist/",
16
+ "README.md"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "keywords": [
22
+ "anna",
23
+ "anna-app",
24
+ "sdk",
25
+ "runtime",
26
+ "iframe"
27
+ ]
28
+ }