@anna-ai/app-runtime 0.1.0 → 0.2.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 (2) hide show
  1. package/dist/index.js +195 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Anna App Runtime SDK — v0.1.0
2
+ * Anna App Runtime SDK — v0.2.0
3
3
  *
4
4
  * Loaded by every Anna App iframe. Provides a typed proxy over the
5
5
  * postMessage RPC bridge to the host (Anna dashboard). All host calls go
@@ -45,6 +45,153 @@
45
45
  );
46
46
  }
47
47
 
48
+ // ---- Agent namespace (v0.2.0) ----
49
+ //
50
+ // Exposes both raw RPCs (`anna.agent.session.create({submode, ...})`,
51
+ // `anna.agent.session.run({...})`, etc.) AND a higher-level helper
52
+ // `anna.agent.session(opts)` that returns an AgentSession instance
53
+ // for ergonomic use in apps:
54
+ //
55
+ // const sess = await anna.agent.session({ submode: "auto" });
56
+ // for await (const ev of sess.run({ content: "hi" })) {
57
+ // if (ev.event === "model_token") render(ev.text);
58
+ // }
59
+ function buildAgentNamespace(rt) {
60
+ const sessionRpcs = new Proxy(
61
+ {},
62
+ {
63
+ get(_, method) {
64
+ if (typeof method !== "string") return undefined;
65
+ return (args) => rt.call("agent", "session." + method, args || {});
66
+ },
67
+ }
68
+ );
69
+ const ns = {
70
+ // Higher-level: mint and return an AgentSession wrapper.
71
+ session: async (opts = {}) => {
72
+ const result = await rt.call("agent", "session.create", opts);
73
+ return new AgentSession(rt, result);
74
+ },
75
+ };
76
+ // Also expose raw RPC sub-methods on the function — apps can do
77
+ // `anna.agent.session.create(...)` if they want to manage state manually.
78
+ for (const m of ["create", "run", "cancel", "history", "delete"]) {
79
+ ns.session[m] = sessionRpcs[m];
80
+ }
81
+ return ns;
82
+ }
83
+
84
+ // AsyncIterable view over `rpc.stream` event chunks. Reassembles by `seq`
85
+ // so out-of-order arrivals are normalised; back-pressure is bounded only
86
+ // by the iframe's heap (events are small JSON blobs).
87
+ class AgentRunStream {
88
+ constructor(streamId, runId) {
89
+ this.streamId = streamId;
90
+ this.runId = runId;
91
+ this._queue = []; // ordered by seq
92
+ this._waiters = []; // resolvers awaiting next event
93
+ this._buffer = new Map(); // seq -> payload (out-of-order holding)
94
+ this._nextSeq = 1;
95
+ this._done = false;
96
+ }
97
+ _push(frame) {
98
+ const seq = Number(frame.seq || 0);
99
+ const payload = frame.payload;
100
+ const done = !!frame.done;
101
+ if (seq && seq !== this._nextSeq) {
102
+ this._buffer.set(seq, { payload, done });
103
+ return;
104
+ }
105
+ this._emit(payload, done);
106
+ this._nextSeq += 1;
107
+ // Drain consecutive buffered frames.
108
+ while (this._buffer.has(this._nextSeq)) {
109
+ const next = this._buffer.get(this._nextSeq);
110
+ this._buffer.delete(this._nextSeq);
111
+ this._emit(next.payload, next.done);
112
+ this._nextSeq += 1;
113
+ }
114
+ }
115
+ _emit(payload, done) {
116
+ if (payload != null) this._queue.push(payload);
117
+ if (done) this._done = true;
118
+ while (this._waiters.length && (this._queue.length || this._done)) {
119
+ const w = this._waiters.shift();
120
+ if (this._queue.length) w({ value: this._queue.shift(), done: false });
121
+ else w({ value: undefined, done: true });
122
+ }
123
+ }
124
+ [Symbol.asyncIterator]() {
125
+ const self = this;
126
+ return {
127
+ next() {
128
+ if (self._queue.length) {
129
+ return Promise.resolve({ value: self._queue.shift(), done: false });
130
+ }
131
+ if (self._done) return Promise.resolve({ value: undefined, done: true });
132
+ return new Promise((resolve) => self._waiters.push(resolve));
133
+ },
134
+ return() {
135
+ self._done = true;
136
+ while (self._waiters.length) self._waiters.shift()({ value: undefined, done: true });
137
+ return Promise.resolve({ value: undefined, done: true });
138
+ },
139
+ };
140
+ }
141
+ }
142
+
143
+ // Higher-level agent session wrapper. Holds the dispatcher-managed
144
+ // app_session_uuid; its methods are sugar around the raw `agent.session.*`
145
+ // RPCs.
146
+ class AgentSession {
147
+ constructor(rt, info) {
148
+ this._rt = rt;
149
+ this.app_session_uuid = info.app_session_uuid;
150
+ this.expires_in = info.expires_in;
151
+ this.submode = info.submode;
152
+ this.fixed_client_id = info.fixed_client_id || null;
153
+ this.granted_tools = info.granted_tools || [];
154
+ }
155
+ run(opts = {}) {
156
+ const args = Object.assign(
157
+ { app_session_uuid: this.app_session_uuid },
158
+ opts
159
+ );
160
+ const stream = new AgentRunStream(null, args.run_id || null);
161
+ // Kick off the RPC; once the host returns {stream_id, run_id} we
162
+ // register the stream so subsequent rpc.stream events flow into it.
163
+ this._rt.call("agent", "session.run", args).then(
164
+ (res) => {
165
+ stream.streamId = res.stream_id || stream.streamId;
166
+ stream.runId = res.run_id || stream.runId;
167
+ if (stream.streamId) this._rt._registerStream(stream.streamId, stream);
168
+ // If host returns done immediately (e.g. cached error), close.
169
+ if (!stream.streamId) stream._emit(null, true);
170
+ },
171
+ (err) => {
172
+ stream._emit({ event: "error", code: err.code, message: err.message }, true);
173
+ }
174
+ );
175
+ return stream;
176
+ }
177
+ cancel(runId) {
178
+ return this._rt.call("agent", "session.cancel", {
179
+ app_session_uuid: this.app_session_uuid,
180
+ run_id: runId,
181
+ });
182
+ }
183
+ history(opts = {}) {
184
+ return this._rt.call("agent", "session.history", Object.assign(
185
+ { app_session_uuid: this.app_session_uuid }, opts
186
+ ));
187
+ }
188
+ delete() {
189
+ return this._rt.call("agent", "session.delete", {
190
+ app_session_uuid: this.app_session_uuid,
191
+ });
192
+ }
193
+ }
194
+
48
195
  class AnnaAppRuntime {
49
196
  constructor(opts) {
50
197
  this.windowUuid = opts.windowUuid;
@@ -72,6 +219,15 @@
72
219
  this.prefs = buildNamespace(this, "prefs");
73
220
  this.window = buildNamespace(this, "window");
74
221
 
222
+ // ---- agent namespace (v0.2.0) ----
223
+ // Exposes session.{create,run,cancel,history,delete}; SDK also offers
224
+ // a higher-level `anna.agent.session(opts)` helper that returns an
225
+ // AgentSession bound to a fresh AnnaAppSession.
226
+ this.agent = buildAgentNamespace(this);
227
+ // Reassembly buffers for `rpc.stream` events. Map<stream_id, AgentRunStream>.
228
+ this._streams = new Map();
229
+ this.on("rpc.stream", (payload) => this._onStreamFrame(payload || {}));
230
+
75
231
  window.addEventListener("message", (ev) => this._onMessage(ev));
76
232
  window.addEventListener("error", (ev) => {
77
233
  // best-effort error reporting
@@ -162,6 +318,42 @@
162
318
  }, 10000);
163
319
  }
164
320
 
321
+ _onStreamFrame(payload) {
322
+ const sid = payload.stream_id;
323
+ if (!sid) return;
324
+ const stream = this._streams.get(sid);
325
+ if (!stream) {
326
+ // Frame may have arrived before `agent.session.run` resolved with
327
+ // its stream_id. Buffer for a short window — the registration
328
+ // path drains this on `_registerStream`.
329
+ if (!this._earlyFrames) this._earlyFrames = new Map();
330
+ let q = this._earlyFrames.get(sid);
331
+ if (!q) { q = []; this._earlyFrames.set(sid, q); }
332
+ q.push(payload);
333
+ // Cap to avoid unbounded growth on truly orphaned streams.
334
+ if (q.length > 256) q.shift();
335
+ return;
336
+ }
337
+ stream._push(payload);
338
+ if (payload.done) this._streams.delete(sid);
339
+ }
340
+
341
+ _registerStream(streamId, stream) {
342
+ this._streams.set(streamId, stream);
343
+ // Drain any frames that arrived before the RPC reply.
344
+ const queued = this._earlyFrames && this._earlyFrames.get(streamId);
345
+ if (queued && queued.length) {
346
+ this._earlyFrames.delete(streamId);
347
+ for (const p of queued) {
348
+ stream._push(p);
349
+ if (p.done) {
350
+ this._streams.delete(streamId);
351
+ break;
352
+ }
353
+ }
354
+ }
355
+ }
356
+
165
357
  static async connect(options = {}) {
166
358
  // Discover credentials from URL
167
359
  const params = new URLSearchParams(location.search);
@@ -185,4 +377,6 @@
185
377
  }
186
378
 
187
379
  global.AnnaAppRuntime = AnnaAppRuntime;
380
+ global.AnnaAppRuntime.AgentSession = AgentSession;
381
+ global.AnnaAppRuntime.AgentRunStream = AgentRunStream;
188
382
  })(typeof window !== "undefined" ? window : globalThis);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anna-ai/app-runtime",
3
- "version": "0.1.0",
3
+ "version": "0.2.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
  "main": "./dist/index.js",