@almadar/sdk 0.1.0-alpha.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.
package/LICENSE ADDED
@@ -0,0 +1,72 @@
1
+ Business Source License 1.1
2
+
3
+ Parameters
4
+
5
+ Licensor: Almadar FZE
6
+ Licensed Work: KFlow Builder / Almadar
7
+ The Licensed Work is (c) 2025-2026 Almadar FZE.
8
+ Additional Use Grant: You may make production use of the Licensed Work for
9
+ non-commercial purposes and for internal evaluation.
10
+ Production use for commercial purposes requires a
11
+ commercial license from the Licensor.
12
+ Change Date: 2030-02-01
13
+ Change License: Apache License, Version 2.0
14
+
15
+ Terms
16
+
17
+ The Licensor hereby grants you the right to copy, modify, create derivative
18
+ works, redistribute, and make non-production use of the Licensed Work. The
19
+ Licensor may make an Additional Use Grant, above, permitting limited
20
+ production use.
21
+
22
+ Effective on the Change Date, or the fourth anniversary of the first publicly
23
+ available distribution of a specific version of the Licensed Work under this
24
+ License, whichever comes first, the Licensor hereby grants you rights under
25
+ the terms of the Change License, and the rights granted in the paragraph
26
+ above terminate.
27
+
28
+ If your use of the Licensed Work does not comply with the requirements
29
+ currently in effect as described in this License, you must purchase a
30
+ commercial license from the Licensor, its affiliated entities, or authorized
31
+ resellers, or you must refrain from using the Licensed Work.
32
+
33
+ All copies of the original and modified Licensed Work, and derivative works
34
+ of the Licensed Work, are subject to this License. This License applies
35
+ separately for each version of the Licensed Work and the Change Date may vary
36
+ for each version of the Licensed Work released by Licensor.
37
+
38
+ You must conspicuously display this License on each original or modified copy
39
+ of the Licensed Work. If you receive the Licensed Work in original or
40
+ modified form from a third party, the terms and conditions set forth in this
41
+ License apply to your use of that work.
42
+
43
+ Any use of the Licensed Work in violation of this License will automatically
44
+ terminate your rights under this License for the current and all other
45
+ versions of the Licensed Work.
46
+
47
+ This License does not grant you any right in any trademark or logo of
48
+ Licensor or its affiliates (provided that you may use a trademark or logo of
49
+ Licensor as expressly required by this License).
50
+
51
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
52
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
53
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
54
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
55
+ TITLE.
56
+
57
+ ---
58
+
59
+ License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
60
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
61
+
62
+ ADDITIONAL TERMS:
63
+
64
+ Documentation (builder/packages/website/docs/) is licensed under CC BY 4.0.
65
+
66
+ TRADEMARKS:
67
+
68
+ "Orbital", "KFlow", "Almadar", and the Almadar logo are trademarks of
69
+ Almadar FZE. You may not use these trademarks without prior written
70
+ permission from Almadar FZE.
71
+
72
+ For licensing inquiries: licensing@almadar.io
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @almadar/sdk
2
+
3
+ Embed Almadar agent-generated orbital schemas in your React app, and call the agent from your server.
4
+
5
+ > Status: **alpha** (`0.1.0-alpha.0`). API may shift before `0.1.0`. See [`docs/Almadar_Studio_SDK.md`](https://github.com/almadar-io/kflow.ai.builder/blob/main/docs/Almadar_Studio_SDK.md) for the full design doc and gap list.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @almadar/sdk @almadar/runtime @almadar/ui @almadar/core
11
+ ```
12
+
13
+ Peers: React 18+, react-dom 18+.
14
+
15
+ ## Render an orbital in your React app
16
+
17
+ ```tsx
18
+ 'use client';
19
+ import { AlmadarApp } from '@almadar/sdk/react';
20
+ import schema from './dashboard.orb.json';
21
+
22
+ export default function Embedded({ data }: { data: Record<string, unknown[]> }) {
23
+ return <AlmadarApp schema={schema} mode="static" data={data} height="100%" />;
24
+ }
25
+ ```
26
+
27
+ Three render modes:
28
+
29
+ | `mode` | Effects | Use case |
30
+ |---|---|---|
31
+ | `static` (default) | None — pure UI with the `data` you pass | Static dashboards, snapshots |
32
+ | `mock` | In-browser fake server, faker-seeded if no `data` | Demos, design previews |
33
+ | `server` | Real backend at `serverUrl` | Production with persist/fetch/call-service |
34
+
35
+ ## Call the agent from your server
36
+
37
+ ```ts
38
+ import { AlmadarClient } from '@almadar/sdk/client';
39
+
40
+ const almadar = new AlmadarClient({ apiKey: process.env.ALMADAR_API_KEY! });
41
+
42
+ const { schema } = await almadar.generate({
43
+ prompt: 'A finance dashboard with revenue, customers, and churn KPIs',
44
+ endUserId: 'customer-X-user-42',
45
+ onEvent: (event) => console.log(event.type, event),
46
+ });
47
+ ```
48
+
49
+ `AlmadarClient.generate()` streams SSE events (`start`, `orbital_added`, `complete`, …) via `onEvent`. The returned `schema` is the final `OrbitalSchema` you pass to `<AlmadarApp />`.
50
+
51
+ For long-running generations, pass `async: true` to flip to job-polling mode:
52
+
53
+ ```ts
54
+ const { schema } = await almadar.generate({ prompt, async: true });
55
+ ```
56
+
57
+ ## Issuing API keys
58
+
59
+ Keys are issued from Studio (`/settings/sdk`) on the **Teams** plan. See `docs/Almadar_Studio_Subscriptions.md` for plan details. Server-side use only — never ship `sk_*` to a browser.
60
+
61
+ ## License
62
+
63
+ BSL-1.1
@@ -0,0 +1,58 @@
1
+ import { OrbitalSchema } from '@almadar/core';
2
+ export { EntityData, EventPayload, OrbitalSchema } from '@almadar/core';
3
+ import { c as AlmadarClientOptions, G as GenerateOptions, g as GenerateResult, E as EditSchemaPatch, C as CompileOptions, f as CompileResult, d as ApiErrorBody } from '../types-BfWDIOGm.js';
4
+ export { A as AgentEvent, e as AsyncJobHandle, J as JsonValue } from '../types-BfWDIOGm.js';
5
+
6
+ /**
7
+ * `AlmadarClient` — server / Node-side HTTP client targeting `/api/v1/agent/*`.
8
+ * Authenticates with a team-bound API key (`sk_*`) issued from
9
+ * Studio's `/settings/sdk` panel. See `docs/Almadar_Studio_SDK.md` §5.
10
+ *
11
+ * Never instantiate this in a browser bundle — `apiKey` must never leave
12
+ * the customer's server.
13
+ */
14
+
15
+ declare class AlmadarClient {
16
+ private readonly apiKey;
17
+ private readonly baseUrl;
18
+ private readonly fetchImpl;
19
+ constructor(opts: AlmadarClientOptions);
20
+ generate(input: GenerateOptions): Promise<GenerateResult>;
21
+ editSchema(appId: string, patch: EditSchemaPatch): Promise<OrbitalSchema>;
22
+ compileToApp(schema: OrbitalSchema, opts?: CompileOptions): Promise<CompileResult>;
23
+ private streamGenerate;
24
+ private pollUntilComplete;
25
+ private requestJson;
26
+ private headers;
27
+ private errorFromResponse;
28
+ }
29
+
30
+ /**
31
+ * Typed SDK errors. Server emits a structured `ApiErrorBody`; the HTTP layer
32
+ * maps the `code` to one of these subclasses. Customers `catch` by class.
33
+ */
34
+
35
+ declare class AlmadarError extends Error {
36
+ readonly code: number;
37
+ readonly details?: ApiErrorBody['details'];
38
+ constructor(body: ApiErrorBody);
39
+ }
40
+ /** 4001 — invalid, revoked, or missing API key. */
41
+ declare class ApiKeyError extends AlmadarError {
42
+ constructor(body: ApiErrorBody);
43
+ }
44
+ /** 4029 — team cap (feature counter) exceeded. Retry after a billing cycle. */
45
+ declare class RateLimitedError extends AlmadarError {
46
+ readonly retryAfterSeconds?: number;
47
+ constructor(body: ApiErrorBody, retryAfterSeconds?: number);
48
+ }
49
+ /** 4040 — the team's behavior catalog (subset/replace mode) cannot serve the request. */
50
+ declare class CatalogOutOfScopeError extends AlmadarError {
51
+ constructor(body: ApiErrorBody);
52
+ }
53
+ /** Anything else from the server with a recognized envelope but no specific subclass. */
54
+ declare class ServerError extends AlmadarError {
55
+ constructor(body: ApiErrorBody);
56
+ }
57
+
58
+ export { AlmadarClient, AlmadarClientOptions, AlmadarError, ApiErrorBody, ApiKeyError, CatalogOutOfScopeError, CompileOptions, CompileResult, EditSchemaPatch, GenerateOptions, GenerateResult, RateLimitedError, ServerError };
@@ -0,0 +1,282 @@
1
+ // src/client/errors.ts
2
+ var AlmadarError = class extends Error {
3
+ code;
4
+ details;
5
+ constructor(body) {
6
+ super(body.message);
7
+ this.name = "AlmadarError";
8
+ this.code = body.code;
9
+ this.details = body.details;
10
+ }
11
+ };
12
+ var ApiKeyError = class extends AlmadarError {
13
+ constructor(body) {
14
+ super(body);
15
+ this.name = "ApiKeyError";
16
+ }
17
+ };
18
+ var RateLimitedError = class extends AlmadarError {
19
+ retryAfterSeconds;
20
+ constructor(body, retryAfterSeconds) {
21
+ super(body);
22
+ this.name = "RateLimitedError";
23
+ this.retryAfterSeconds = retryAfterSeconds;
24
+ }
25
+ };
26
+ var CatalogOutOfScopeError = class extends AlmadarError {
27
+ constructor(body) {
28
+ super(body);
29
+ this.name = "CatalogOutOfScopeError";
30
+ }
31
+ };
32
+ var ServerError = class extends AlmadarError {
33
+ constructor(body) {
34
+ super(body);
35
+ this.name = "ServerError";
36
+ }
37
+ };
38
+ function errorFromBody(body) {
39
+ switch (body.code) {
40
+ case 4001:
41
+ return new ApiKeyError(body);
42
+ case 4029:
43
+ return new RateLimitedError(body);
44
+ case 4040:
45
+ return new CatalogOutOfScopeError(body);
46
+ default:
47
+ return new ServerError(body);
48
+ }
49
+ }
50
+
51
+ // src/client/sseParser.ts
52
+ async function* parseSSE(stream) {
53
+ const reader = stream.getReader();
54
+ const decoder = new TextDecoder("utf-8");
55
+ let buffer = "";
56
+ let currentEvent = "";
57
+ let currentData = "";
58
+ try {
59
+ for (; ; ) {
60
+ const { value, done } = await reader.read();
61
+ if (done) break;
62
+ buffer += decoder.decode(value, { stream: true });
63
+ let newlineIdx;
64
+ while ((newlineIdx = indexOfNewline(buffer)) !== -1) {
65
+ const rawLine = buffer.slice(0, newlineIdx);
66
+ buffer = buffer.slice(newlineIdx + (buffer[newlineIdx] === "\r" && buffer[newlineIdx + 1] === "\n" ? 2 : 1));
67
+ if (rawLine === "") {
68
+ if (currentData !== "" || currentEvent !== "") {
69
+ yield { event: currentEvent, data: currentData };
70
+ currentEvent = "";
71
+ currentData = "";
72
+ }
73
+ continue;
74
+ }
75
+ if (rawLine.startsWith(":")) continue;
76
+ const colon = rawLine.indexOf(":");
77
+ const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
78
+ const rawValue = colon === -1 ? "" : rawLine.slice(colon + 1);
79
+ const value2 = rawValue.startsWith(" ") ? rawValue.slice(1) : rawValue;
80
+ if (field === "event") {
81
+ currentEvent = value2;
82
+ } else if (field === "data") {
83
+ currentData = currentData === "" ? value2 : `${currentData}
84
+ ${value2}`;
85
+ }
86
+ }
87
+ }
88
+ if (currentData !== "" || currentEvent !== "") {
89
+ yield { event: currentEvent, data: currentData };
90
+ }
91
+ } finally {
92
+ reader.releaseLock();
93
+ }
94
+ }
95
+ function indexOfNewline(s) {
96
+ for (let i = 0; i < s.length; i += 1) {
97
+ const c = s[i];
98
+ if (c === "\n" || c === "\r") return i;
99
+ }
100
+ return -1;
101
+ }
102
+
103
+ // src/client/AlmadarClient.ts
104
+ var DEFAULT_BASE_URL = "https://api.almadar.io";
105
+ var POLL_BACKOFF_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
106
+ var AlmadarClient = class {
107
+ apiKey;
108
+ baseUrl;
109
+ fetchImpl;
110
+ constructor(opts) {
111
+ if (!opts.apiKey || typeof opts.apiKey !== "string") {
112
+ throw new Error("AlmadarClient: opts.apiKey is required");
113
+ }
114
+ this.apiKey = opts.apiKey;
115
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
116
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
117
+ if (typeof this.fetchImpl !== "function") {
118
+ throw new Error("AlmadarClient: no fetch available \u2014 pass opts.fetch for Node <18");
119
+ }
120
+ }
121
+ async generate(input) {
122
+ if (input.async === true) {
123
+ const handle = await this.requestJson("POST", "/api/v1/agent/generate", {
124
+ prompt: input.prompt,
125
+ endUserId: input.endUserId,
126
+ appId: input.appId,
127
+ async: true
128
+ });
129
+ assertString(handle.jobId, "AsyncJobHandle.jobId");
130
+ assertString(handle.statusUrl, "AsyncJobHandle.statusUrl");
131
+ return this.pollUntilComplete(handle, input.onEvent);
132
+ }
133
+ return this.streamGenerate(input);
134
+ }
135
+ async editSchema(appId, patch) {
136
+ if (!appId) throw new Error("AlmadarClient.editSchema: appId is required");
137
+ const schema = await this.requestJson("PUT", "/api/v1/agent/edit-schema", {
138
+ appId,
139
+ patch
140
+ });
141
+ assertString(schema.name, "OrbitalSchema.name");
142
+ return schema;
143
+ }
144
+ async compileToApp(schema, opts) {
145
+ const result = await this.requestJson("POST", "/api/v1/agent/compile", {
146
+ schema,
147
+ target: opts?.target,
148
+ shell: opts?.shell
149
+ });
150
+ assertString(result.downloadUrl, "CompileResult.downloadUrl");
151
+ assertString(result.expiresAt, "CompileResult.expiresAt");
152
+ return result;
153
+ }
154
+ async streamGenerate(input) {
155
+ const res = await this.fetchImpl(`${this.baseUrl}/api/v1/agent/generate`, {
156
+ method: "POST",
157
+ headers: this.headers({ accept: "text/event-stream", contentType: "application/json" }, input.endUserId),
158
+ body: JSON.stringify({
159
+ prompt: input.prompt,
160
+ endUserId: input.endUserId,
161
+ appId: input.appId
162
+ })
163
+ });
164
+ if (!res.ok) throw await this.errorFromResponse(res);
165
+ if (res.body === null) throw new Error("AlmadarClient.generate: server returned no body");
166
+ let final = null;
167
+ for await (const raw of parseSSE(res.body)) {
168
+ const event = parseAgentEvent(raw.event, raw.data);
169
+ if (event === null) continue;
170
+ input.onEvent?.(event);
171
+ if (event.type === "complete") {
172
+ final = { schema: event.schema, appId: event.appId };
173
+ } else if (event.type === "error") {
174
+ throw errorFromBody({ code: event.code ?? 500, message: event.message });
175
+ }
176
+ }
177
+ if (final === null) {
178
+ throw new ServerError({ code: 500, message: "SSE stream ended without `complete` event" });
179
+ }
180
+ return final;
181
+ }
182
+ async pollUntilComplete(handle, onEvent) {
183
+ let attempt = 0;
184
+ for (; ; ) {
185
+ const delay = POLL_BACKOFF_MS[Math.min(attempt, POLL_BACKOFF_MS.length - 1)];
186
+ await sleep(delay);
187
+ attempt += 1;
188
+ const status = await this.requestJson("GET", handle.statusUrl);
189
+ assertString(status.state, "JobStatus.state");
190
+ if (status.events !== void 0 && onEvent !== void 0) {
191
+ for (const e of status.events) onEvent(e);
192
+ }
193
+ if (status.state === "complete") {
194
+ if (status.result === void 0) {
195
+ throw new ServerError({ code: 500, message: "Job complete but no result returned" });
196
+ }
197
+ return status.result;
198
+ }
199
+ if (status.state === "error") {
200
+ throw errorFromBody({
201
+ code: status.errorCode ?? 500,
202
+ message: status.errorMessage ?? "Job failed"
203
+ });
204
+ }
205
+ }
206
+ }
207
+ async requestJson(method, path, body) {
208
+ const isAbsolute = path.startsWith("http://") || path.startsWith("https://");
209
+ const url = isAbsolute ? path : `${this.baseUrl}${path}`;
210
+ const init = {
211
+ method,
212
+ headers: this.headers({
213
+ accept: "application/json",
214
+ contentType: body !== void 0 ? "application/json" : void 0
215
+ })
216
+ };
217
+ if (body !== void 0) init.body = JSON.stringify(body);
218
+ const res = await this.fetchImpl(url, init);
219
+ if (!res.ok) throw await this.errorFromResponse(res);
220
+ const text = await res.text();
221
+ if (text === "") {
222
+ throw new ServerError({ code: 500, message: "Empty response body" });
223
+ }
224
+ const parsed = JSON.parse(text);
225
+ return parsed;
226
+ }
227
+ headers(opts, endUserId) {
228
+ const h = { authorization: `Bearer ${this.apiKey}` };
229
+ if (opts.accept !== void 0) h["accept"] = opts.accept;
230
+ if (opts.contentType !== void 0) h["content-type"] = opts.contentType;
231
+ if (endUserId !== void 0 && endUserId !== "") h["x-end-user-id"] = endUserId;
232
+ return h;
233
+ }
234
+ async errorFromResponse(res) {
235
+ const text = await res.text();
236
+ let body;
237
+ try {
238
+ const parsed = text === "" ? null : JSON.parse(text);
239
+ body = parsed !== null && typeof parsed.code === "number" && typeof parsed.message === "string" ? parsed : {
240
+ code: res.status,
241
+ message: res.statusText !== "" ? res.statusText : "HTTP error"
242
+ };
243
+ } catch {
244
+ body = { code: res.status, message: text !== "" ? text : res.statusText };
245
+ }
246
+ const retryAfter = res.headers.get("retry-after");
247
+ const err = errorFromBody(body);
248
+ if (err.name === "RateLimitedError" && retryAfter !== null) {
249
+ const seconds = Number(retryAfter);
250
+ if (Number.isFinite(seconds)) {
251
+ Object.defineProperty(err, "retryAfterSeconds", { value: seconds, enumerable: true });
252
+ }
253
+ }
254
+ return err;
255
+ }
256
+ };
257
+ function parseAgentEvent(eventName, dataLine) {
258
+ if (dataLine === "") return null;
259
+ let payload;
260
+ try {
261
+ payload = JSON.parse(dataLine);
262
+ } catch {
263
+ return null;
264
+ }
265
+ if (payload === null || typeof payload !== "object") return null;
266
+ if (typeof payload.type === "string") return payload;
267
+ if (eventName === "") return null;
268
+ const synthesized = Object.assign(payload, { type: eventName });
269
+ return synthesized;
270
+ }
271
+ function assertString(v, name) {
272
+ if (typeof v !== "string" || v === "") {
273
+ throw new ServerError({ code: 500, message: `Malformed server response: ${name} is not a string` });
274
+ }
275
+ }
276
+ function sleep(ms) {
277
+ return new Promise((resolve) => setTimeout(resolve, ms));
278
+ }
279
+
280
+ export { AlmadarClient, AlmadarError, ApiKeyError, CatalogOutOfScopeError, RateLimitedError, ServerError };
281
+ //# sourceMappingURL=index.js.map
282
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/errors.ts","../../src/client/sseParser.ts","../../src/client/AlmadarClient.ts"],"names":[],"mappings":";AAOO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA;AAAA,EACA,OAAA;AAAA,EACT,YAAY,IAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,OAAA;AAAA,EACtB;AACF;AAGO,IAAM,WAAA,GAAN,cAA0B,YAAA,CAAa;AAAA,EAC5C,YAAY,IAAA,EAAoB;AAC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IAAA,EAAM,WAAW,CAAA;AAC7F,EAAA,OAAO,WAAA;AACT;AAEA,SAAS,YAAA,CAAa,GAAuB,IAAA,EAAmC;AAC9E,EAAA,IAAI,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,EAAA,EAAI;AACrC,IAAA,MAAM,IAAI,YAAY,EAAE,IAAA,EAAM,KAAK,OAAA,EAAS,CAAA,2BAAA,EAA8B,IAAI,CAAA,gBAAA,CAAA,EAAoB,CAAA;AAAA,EACpG;AACF;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AACzD","file":"index.js","sourcesContent":["/**\n * Typed SDK errors. Server emits a structured `ApiErrorBody`; the HTTP layer\n * maps the `code` to one of these subclasses. Customers `catch` by class.\n */\n\nimport type { ApiErrorBody } from '../types';\n\nexport class AlmadarError extends Error {\n readonly code: number;\n readonly details?: ApiErrorBody['details'];\n constructor(body: ApiErrorBody) {\n super(body.message);\n this.name = 'AlmadarError';\n this.code = body.code;\n this.details = body.details;\n }\n}\n\n/** 4001 — invalid, revoked, or missing API key. */\nexport class ApiKeyError extends AlmadarError {\n constructor(body: ApiErrorBody) {\n super(body);\n this.name = 'ApiKeyError';\n }\n}\n\n/** 4029 — team cap (feature counter) exceeded. Retry after a billing cycle. */\nexport class RateLimitedError extends AlmadarError {\n readonly retryAfterSeconds?: number;\n constructor(body: ApiErrorBody, retryAfterSeconds?: number) {\n super(body);\n this.name = 'RateLimitedError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\n/** 4040 — the team's behavior catalog (subset/replace mode) cannot serve the request. */\nexport class CatalogOutOfScopeError extends AlmadarError {\n constructor(body: ApiErrorBody) {\n super(body);\n this.name = 'CatalogOutOfScopeError';\n }\n}\n\n/** Anything else from the server with a recognized envelope but no specific subclass. */\nexport class ServerError extends AlmadarError {\n constructor(body: ApiErrorBody) {\n super(body);\n this.name = 'ServerError';\n }\n}\n\nexport function errorFromBody(body: ApiErrorBody): AlmadarError {\n switch (body.code) {\n case 4001:\n return new ApiKeyError(body);\n case 4029:\n return new RateLimitedError(body);\n case 4040:\n return new CatalogOutOfScopeError(body);\n default:\n return new ServerError(body);\n }\n}\n","/**\n * Minimal Server-Sent Events parser. Reads a `ReadableStream<Uint8Array>`\n * (the body of a `fetch` Response) and yields decoded events. Universal:\n * works in browser, Node 18+, Deno, Bun.\n *\n * Spec subset implemented:\n * - `event:` and `data:` fields\n * - dispatch on blank line\n * - newline-tolerant (CRLF + LF)\n * - skips comments (`:`-prefixed lines)\n *\n * Not implemented (we don't need them):\n * - `id:` / `retry:` fields\n * - reconnection / last-event-id\n */\n\nexport interface RawSseEvent {\n /** `event:` field value. Empty string when absent — matches the spec default. */\n event: string;\n /** Concatenated `data:` lines, joined by newlines. */\n data: string;\n}\n\nexport async function* parseSSE(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<RawSseEvent, void, void> {\n const reader = stream.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n let currentEvent = '';\n let currentData = '';\n\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let newlineIdx: number;\n while ((newlineIdx = indexOfNewline(buffer)) !== -1) {\n const rawLine = buffer.slice(0, newlineIdx);\n buffer = buffer.slice(newlineIdx + (buffer[newlineIdx] === '\\r' && buffer[newlineIdx + 1] === '\\n' ? 2 : 1));\n\n if (rawLine === '') {\n if (currentData !== '' || currentEvent !== '') {\n yield { event: currentEvent, data: currentData };\n currentEvent = '';\n currentData = '';\n }\n continue;\n }\n if (rawLine.startsWith(':')) continue;\n\n const colon = rawLine.indexOf(':');\n const field = colon === -1 ? rawLine : rawLine.slice(0, colon);\n const rawValue = colon === -1 ? '' : rawLine.slice(colon + 1);\n const value2 = rawValue.startsWith(' ') ? rawValue.slice(1) : rawValue;\n\n if (field === 'event') {\n currentEvent = value2;\n } else if (field === 'data') {\n currentData = currentData === '' ? value2 : `${currentData}\\n${value2}`;\n }\n }\n }\n if (currentData !== '' || currentEvent !== '') {\n yield { event: currentEvent, data: currentData };\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction indexOfNewline(s: string): number {\n for (let i = 0; i < s.length; i += 1) {\n const c = s[i];\n if (c === '\\n' || c === '\\r') return i;\n }\n return -1;\n}\n","/**\n * `AlmadarClient` — server / Node-side HTTP client targeting `/api/v1/agent/*`.\n * Authenticates with a team-bound API key (`sk_*`) issued from\n * Studio's `/settings/sdk` panel. See `docs/Almadar_Studio_SDK.md` §5.\n *\n * Never instantiate this in a browser bundle — `apiKey` must never leave\n * the customer's server.\n */\n\nimport type { OrbitalSchema } from '@almadar/core';\nimport type {\n AgentEvent,\n AlmadarClientOptions,\n ApiErrorBody,\n AsyncJobHandle,\n CompileOptions,\n CompileResult,\n EditSchemaPatch,\n GenerateOptions,\n GenerateResult,\n} from '../types';\nimport { errorFromBody, ServerError } from './errors';\nimport { parseSSE } from './sseParser';\n\nconst DEFAULT_BASE_URL = 'https://api.almadar.io';\nconst POLL_BACKOFF_MS: readonly number[] = [1000, 2000, 5000, 10_000, 30_000];\n\ninterface JobStatus {\n state: 'pending' | 'complete' | 'error';\n events?: readonly AgentEvent[];\n result?: GenerateResult;\n errorCode?: number;\n errorMessage?: string;\n}\n\nexport class AlmadarClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(opts: AlmadarClientOptions) {\n if (!opts.apiKey || typeof opts.apiKey !== 'string') {\n throw new Error('AlmadarClient: opts.apiKey is required');\n }\n this.apiKey = opts.apiKey;\n this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n this.fetchImpl = opts.fetch ?? globalThis.fetch;\n if (typeof this.fetchImpl !== 'function') {\n throw new Error('AlmadarClient: no fetch available — pass opts.fetch for Node <18');\n }\n }\n\n async generate(input: GenerateOptions): Promise<GenerateResult> {\n if (input.async === true) {\n const handle = await this.requestJson<AsyncJobHandle>('POST', '/api/v1/agent/generate', {\n prompt: input.prompt,\n endUserId: input.endUserId,\n appId: input.appId,\n async: true,\n });\n assertString(handle.jobId, 'AsyncJobHandle.jobId');\n assertString(handle.statusUrl, 'AsyncJobHandle.statusUrl');\n return this.pollUntilComplete(handle, input.onEvent);\n }\n return this.streamGenerate(input);\n }\n\n async editSchema(appId: string, patch: EditSchemaPatch): Promise<OrbitalSchema> {\n if (!appId) throw new Error('AlmadarClient.editSchema: appId is required');\n const schema = await this.requestJson<OrbitalSchema>('PUT', '/api/v1/agent/edit-schema', {\n appId,\n patch,\n });\n assertString(schema.name, 'OrbitalSchema.name');\n return schema;\n }\n\n async compileToApp(schema: OrbitalSchema, opts?: CompileOptions): Promise<CompileResult> {\n const result = await this.requestJson<CompileResult>('POST', '/api/v1/agent/compile', {\n schema,\n target: opts?.target,\n shell: opts?.shell,\n });\n assertString(result.downloadUrl, 'CompileResult.downloadUrl');\n assertString(result.expiresAt, 'CompileResult.expiresAt');\n return result;\n }\n\n private async streamGenerate(input: GenerateOptions): Promise<GenerateResult> {\n const res = await this.fetchImpl(`${this.baseUrl}/api/v1/agent/generate`, {\n method: 'POST',\n headers: this.headers({ accept: 'text/event-stream', contentType: 'application/json' }, input.endUserId),\n body: JSON.stringify({\n prompt: input.prompt,\n endUserId: input.endUserId,\n appId: input.appId,\n }),\n });\n if (!res.ok) throw await this.errorFromResponse(res);\n if (res.body === null) throw new Error('AlmadarClient.generate: server returned no body');\n\n let final: GenerateResult | null = null;\n for await (const raw of parseSSE(res.body)) {\n const event = parseAgentEvent(raw.event, raw.data);\n if (event === null) continue;\n input.onEvent?.(event);\n if (event.type === 'complete') {\n final = { schema: event.schema, appId: event.appId };\n } else if (event.type === 'error') {\n throw errorFromBody({ code: event.code ?? 500, message: event.message });\n }\n }\n if (final === null) {\n throw new ServerError({ code: 500, message: 'SSE stream ended without `complete` event' });\n }\n return final;\n }\n\n private async pollUntilComplete(\n handle: AsyncJobHandle,\n onEvent: GenerateOptions['onEvent'],\n ): Promise<GenerateResult> {\n let attempt = 0;\n for (;;) {\n const delay = POLL_BACKOFF_MS[Math.min(attempt, POLL_BACKOFF_MS.length - 1)];\n await sleep(delay);\n attempt += 1;\n const status = await this.requestJson<JobStatus>('GET', handle.statusUrl);\n assertString(status.state, 'JobStatus.state');\n if (status.events !== undefined && onEvent !== undefined) {\n for (const e of status.events) onEvent(e);\n }\n if (status.state === 'complete') {\n if (status.result === undefined) {\n throw new ServerError({ code: 500, message: 'Job complete but no result returned' });\n }\n return status.result;\n }\n if (status.state === 'error') {\n throw errorFromBody({\n code: status.errorCode ?? 500,\n message: status.errorMessage ?? 'Job failed',\n });\n }\n }\n }\n\n private async requestJson<T>(method: string, path: string, body?: object): Promise<T> {\n const isAbsolute = path.startsWith('http://') || path.startsWith('https://');\n const url = isAbsolute ? path : `${this.baseUrl}${path}`;\n const init: RequestInit = {\n method,\n headers: this.headers({\n accept: 'application/json',\n contentType: body !== undefined ? 'application/json' : undefined,\n }),\n };\n if (body !== undefined) init.body = JSON.stringify(body);\n const res = await this.fetchImpl(url, init);\n if (!res.ok) throw await this.errorFromResponse(res);\n const text = await res.text();\n if (text === '') {\n throw new ServerError({ code: 500, message: 'Empty response body' });\n }\n const parsed: T = JSON.parse(text);\n return parsed;\n }\n\n private headers(\n opts: { accept?: string; contentType?: string },\n endUserId?: string,\n ): Record<string, string> {\n const h: Record<string, string> = { authorization: `Bearer ${this.apiKey}` };\n if (opts.accept !== undefined) h['accept'] = opts.accept;\n if (opts.contentType !== undefined) h['content-type'] = opts.contentType;\n if (endUserId !== undefined && endUserId !== '') h['x-end-user-id'] = endUserId;\n return h;\n }\n\n private async errorFromResponse(res: Response): Promise<Error> {\n const text = await res.text();\n let body: ApiErrorBody;\n try {\n const parsed: ApiErrorBody | null = text === '' ? null : JSON.parse(text);\n body = parsed !== null && typeof parsed.code === 'number' && typeof parsed.message === 'string'\n ? parsed\n : {\n code: res.status,\n message: res.statusText !== '' ? res.statusText : 'HTTP error',\n };\n } catch {\n body = { code: res.status, message: text !== '' ? text : res.statusText };\n }\n const retryAfter = res.headers.get('retry-after');\n const err = errorFromBody(body);\n if (err.name === 'RateLimitedError' && retryAfter !== null) {\n const seconds = Number(retryAfter);\n if (Number.isFinite(seconds)) {\n Object.defineProperty(err, 'retryAfterSeconds', { value: seconds, enumerable: true });\n }\n }\n return err;\n }\n}\n\nfunction parseAgentEvent(eventName: string, dataLine: string): AgentEvent | null {\n if (dataLine === '') return null;\n let payload: AgentEvent | null;\n try {\n payload = JSON.parse(dataLine);\n } catch {\n return null;\n }\n if (payload === null || typeof payload !== 'object') return null;\n if (typeof payload.type === 'string') return payload;\n if (eventName === '') return null;\n // Server sent only an `event:` field name — write `type` onto the payload.\n // Mutating the parsed result is safe because we own it.\n const synthesized: AgentEvent & { type: string } = Object.assign(payload, { type: eventName });\n return synthesized;\n}\n\nfunction assertString(v: string | undefined, name: string): asserts v is string {\n if (typeof v !== 'string' || v === '') {\n throw new ServerError({ code: 500, message: `Malformed server response: ${name} is not a string` });\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
@@ -0,0 +1,6 @@
1
+ export { AlmadarApp } from './react/index.js';
2
+ export { useEventBus as useOrbBus } from '@almadar/ui/hooks';
3
+ export { AlmadarClient, AlmadarError, ApiKeyError, CatalogOutOfScopeError, RateLimitedError, ServerError } from './client/index.js';
4
+ export { A as AgentEvent, a as AlmadarAppProps, b as AlmadarAppRef, c as AlmadarClientOptions, d as ApiErrorBody, e as AsyncJobHandle, C as CompileOptions, f as CompileResult, E as EditSchemaPatch, G as GenerateOptions, g as GenerateResult, J as JsonValue } from './types-BfWDIOGm.js';
5
+ export { EntityData, EventPayload, OrbitalSchema } from '@almadar/core';
6
+ import 'react';