beru-sdk 0.0.0-stage → 1.0.0-alpha.17

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Beru authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # beru-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use a [Beru](https://docs.beru-cloud.dev) instance as your app's AI layer from TypeScript or
4
+ JavaScript (Node 18+, edge runtimes): chat with its agents and run its workflows as your own users,
5
+ with the answers streamed. Beru keeps the agents, their tools and every run.
6
+
7
+ You need an app and its key from **Settings → Apps** on your instance (developer mode). Keep the key
8
+ on your server: Beru refuses it from a browser.
9
+
10
+ ```ts
11
+ import { Beru } from 'beru-sdk';
12
+
13
+ const beru = new Beru({ baseUrl: 'https://beru.example.com', apiKey: process.env.BERU_APP_KEY });
14
+
15
+ const chat = await beru.chats.create({ agent: '<agent id>', user: 'u_123' });
16
+ for await (const ev of beru.chats.send(chat.id, 'Where is my order?')) {
17
+ if (ev.type === 'message.delta') process.stdout.write(ev.text);
18
+ }
19
+
20
+ const { output } = await beru.workflows.run('<workflow id>', { input: { order: 42 }, user: 'u_123' }).result();
21
+ const run = await beru.workflows.start('<workflow id>', { input: { order: 42 } });
22
+ const status = await beru.workflows.getRun('<workflow id>', run);
23
+ ```
24
+
25
+ A stream that drops is rejoined from the last event; a message is never sent twice. Errors are
26
+ `BeruError` with Beru's `status`, `code` and `retryAfter`; a run that fails throws `RunFailed`.
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Beru's apps API from TypeScript: chat with a Beru instance's agents and run its workflows from
3
+ * your app, as your own users, with the replies streamed. Beru keeps the agents, their tools and
4
+ * every run. Works in Node 18+, edge runtimes and browsers (with a browser token, later).
5
+ *
6
+ * import { Beru } from 'beru-sdk';
7
+ *
8
+ * const beru = new Beru({ baseUrl: 'https://beru.example.com', apiKey: process.env.BERU_APP_KEY });
9
+ * const chat = await beru.chats.create({ agent: '<agent id>', user: 'u_123' });
10
+ * for await (const ev of beru.chats.send(chat.id, 'Where is my order?')) {
11
+ * if (ev.type === 'message.delta') process.stdout.write(ev.text);
12
+ * }
13
+ */
14
+ export type Usage = {
15
+ input_tokens: number;
16
+ output_tokens: number;
17
+ cost?: number;
18
+ };
19
+ export type Question = {
20
+ question: string;
21
+ kind: 'single_choice' | 'multi_choice' | 'text' | 'long_text' | 'yes_no' | 'secret' | string;
22
+ options?: string[];
23
+ id?: string;
24
+ required?: boolean;
25
+ allow_other?: boolean;
26
+ placeholder?: string;
27
+ };
28
+ export type RunStarted = {
29
+ type: 'run.started';
30
+ run: string;
31
+ agent?: string;
32
+ workflow?: string;
33
+ };
34
+ export type MessageDelta = {
35
+ type: 'message.delta';
36
+ text: string;
37
+ step?: string;
38
+ };
39
+ export type ToolStarted = {
40
+ type: 'tool.started';
41
+ call: string;
42
+ name: string;
43
+ input?: unknown;
44
+ };
45
+ export type ToolOutput = {
46
+ type: 'tool.output';
47
+ call: string;
48
+ text: string;
49
+ };
50
+ export type ToolFinished = {
51
+ type: 'tool.finished';
52
+ call: string;
53
+ name: string;
54
+ ok: boolean;
55
+ output?: unknown;
56
+ };
57
+ export type QuestionAsked = {
58
+ type: 'question';
59
+ call: string;
60
+ title?: string;
61
+ questions: Question[];
62
+ };
63
+ export type StepStarted = {
64
+ type: 'step.started';
65
+ step: string;
66
+ name?: string;
67
+ kind?: string;
68
+ };
69
+ export type StepFinished = {
70
+ type: 'step.finished';
71
+ step: string;
72
+ ok: boolean;
73
+ output?: unknown;
74
+ error?: string;
75
+ };
76
+ export type UsageEvent = {
77
+ type: 'usage';
78
+ } & Usage;
79
+ export type ErrorEvent = {
80
+ type: 'error';
81
+ code: string;
82
+ message: string;
83
+ };
84
+ export type RunFinished = {
85
+ type: 'run.finished';
86
+ status: 'done' | 'stopped' | 'failed';
87
+ message?: string;
88
+ output?: unknown;
89
+ usage?: Usage;
90
+ error?: string;
91
+ };
92
+ /** Events added later within v1 arrive with their own `type`: ignore what you do not know. */
93
+ export type OtherEvent = {
94
+ type: string;
95
+ [key: string]: unknown;
96
+ };
97
+ export type BeruEvent = (RunStarted | MessageDelta | ToolStarted | ToolOutput | ToolFinished | QuestionAsked | StepStarted | StepFinished | UsageEvent | ErrorEvent | RunFinished) & {
98
+ id?: string;
99
+ };
100
+ export interface Result {
101
+ run?: string;
102
+ status: 'done' | 'stopped';
103
+ message?: string;
104
+ output?: unknown;
105
+ usage?: Usage;
106
+ questions: Omit<QuestionAsked, 'type'>[];
107
+ /** The reply's deltas, joined. */
108
+ text: string;
109
+ }
110
+ export interface Chat {
111
+ id: string;
112
+ agent: string;
113
+ user: string;
114
+ title: string;
115
+ created_at: string | null;
116
+ }
117
+ /** Your user's token for an MCP server your app signs them in to (Settings → Apps → Sign-ins it gives). */
118
+ export interface SignIn {
119
+ server: string;
120
+ access_token: string;
121
+ expires_in?: number;
122
+ }
123
+ /** A token your page calls Beru with for one of your users, in place of the key. */
124
+ export interface BrowserToken {
125
+ token: string;
126
+ expires_at: string;
127
+ user: string;
128
+ signed_in: string[];
129
+ }
130
+ export interface AgentProfile {
131
+ id: string;
132
+ name: string;
133
+ description: string | null;
134
+ }
135
+ export interface Message {
136
+ id: string;
137
+ role: 'user' | 'assistant' | 'tool' | string;
138
+ text: string;
139
+ created_at: string | null;
140
+ tool?: string;
141
+ }
142
+ export interface WorkflowRun {
143
+ run: string;
144
+ workflow: string;
145
+ execution?: string | null;
146
+ status: 'running' | 'done' | 'stopped' | 'failed';
147
+ output?: unknown;
148
+ error?: string;
149
+ }
150
+ /** An error answer from Beru: its HTTP status, its `code` and its message. */
151
+ export declare class BeruError extends Error {
152
+ readonly status: number;
153
+ readonly code: string;
154
+ readonly retryAfter?: number | undefined;
155
+ constructor(message: string, status?: number, code?: string, retryAfter?: number | undefined);
156
+ }
157
+ /** A run that ended with status `failed`. */
158
+ export declare class RunFailed extends BeruError {
159
+ readonly run?: string | undefined;
160
+ constructor(message: string, run?: string | undefined);
161
+ }
162
+ /**
163
+ * A run's events as they happen: `for await` over it, or await text() / result() for the end.
164
+ * Beru keeps the run going if the connection drops; this rejoins it from the last event it saw.
165
+ * Iterate it once: a second loop continues where the first stopped.
166
+ */
167
+ export declare class RunStream implements AsyncIterable<BeruEvent> {
168
+ private readonly client;
169
+ private readonly method;
170
+ private readonly path;
171
+ private readonly body?;
172
+ private readonly params?;
173
+ private run?;
174
+ private lastId?;
175
+ private textParts;
176
+ private questions;
177
+ private finished?;
178
+ private failure?;
179
+ private gen?;
180
+ private abort;
181
+ constructor(client: Beru, method: string, path: string, body?: unknown | undefined, params?: Record<string, string> | undefined, run?: string);
182
+ /** The run's id, once run.started has arrived. */
183
+ get runId(): string | undefined;
184
+ [Symbol.asyncIterator](): AsyncIterator<BeruEvent>;
185
+ /** Stop listening. The run itself carries on in Beru. */
186
+ close(): void;
187
+ private note;
188
+ private events;
189
+ /** Wait for the end. Throws RunFailed when the run failed. */
190
+ result(): Promise<Result>;
191
+ /** Wait for the end and give the reply's text. */
192
+ text(): Promise<string>;
193
+ /** Stop the run in Beru. */
194
+ cancel(): Promise<{
195
+ stopping: boolean;
196
+ }>;
197
+ }
198
+ export interface BeruOptions {
199
+ /** The instance's address, e.g. https://beru.example.com. Default: BERU_URL. */
200
+ baseUrl?: string;
201
+ /** The app's key (Settings → Apps), on a server only. Default: BERU_APP_KEY. */
202
+ apiKey?: string;
203
+ /** A fetch to use instead of the global one. */
204
+ fetch?: typeof fetch;
205
+ /** How many times a dropped stream is rejoined. Default 5. */
206
+ reconnects?: number;
207
+ }
208
+ export declare class Beru {
209
+ readonly reconnects: number;
210
+ private readonly baseUrl;
211
+ private readonly headers;
212
+ private readonly fetchImpl;
213
+ constructor(options?: BeruOptions);
214
+ /** @internal */
215
+ request(method: string, path: string, body?: unknown, params?: Record<string, string>, signal?: AbortSignal, accept?: string): Promise<Response>;
216
+ /** @internal */
217
+ call<T>(method: string, path: string, body?: unknown, params?: Record<string, string>): Promise<T>;
218
+ readonly chats: {
219
+ /** A chat for one of your users with one of the app's agents. */
220
+ create: (opts: {
221
+ agent: string;
222
+ user: string;
223
+ title?: string;
224
+ }) => Promise<Chat>;
225
+ list: (user: string) => Promise<Chat[]>;
226
+ messages: (chat: string) => Promise<Message[]>;
227
+ /** Send a message; the reply streams. `.text()` waits for it whole. `context`: what the user is
228
+ * looking at in your app, which the agent is told with this message. */
229
+ send: (chat: string, text: string, opts?: {
230
+ context?: string;
231
+ }) => RunStream;
232
+ };
233
+ readonly tokens: {
234
+ /** A browser token for one of your users, for your page (the chat widget) to call Beru with.
235
+ * Never hand a page your key. With `signIns`, also their tokens for the MCP servers your app signs them in to. */
236
+ create: (opts: {
237
+ user: string;
238
+ expiresIn?: number;
239
+ signIns?: SignIn[];
240
+ }) => Promise<BrowserToken>;
241
+ };
242
+ readonly agents: {
243
+ /** An agent the app may use: its id, name and description. */
244
+ get: (agent: string) => Promise<AgentProfile>;
245
+ };
246
+ readonly workflows: {
247
+ /** Run a workflow; its steps stream. `(await …result()).output` is its result. */
248
+ run: (workflow: string, opts?: {
249
+ input?: Record<string, unknown>;
250
+ user?: string;
251
+ }) => RunStream;
252
+ /** Start a workflow and return its run id at once; the run carries on in Beru. */
253
+ start: (workflow: string, opts?: {
254
+ input?: Record<string, unknown>;
255
+ user?: string;
256
+ }) => Promise<string>;
257
+ /** A run's status (running, done, stopped, failed) and, once done, its output. */
258
+ getRun: (workflow: string, run: string) => Promise<WorkflowRun>;
259
+ };
260
+ readonly runs: {
261
+ /** Follow a run (again), from after an event id if given. */
262
+ events: (run: string, opts?: {
263
+ after?: string;
264
+ }) => RunStream;
265
+ cancel: (run: string) => Promise<{
266
+ run: string;
267
+ stopping: boolean;
268
+ }>;
269
+ };
270
+ readonly users: {
271
+ /** Hand Beru your user's tokens for the MCP servers your app signs them in to. */
272
+ signIn: (user: string, signIns: SignIn[]) => Promise<{
273
+ user: string;
274
+ signed_in: string[];
275
+ }>;
276
+ /** Delete one of your users' chats, runs and record in Beru. */
277
+ forget: (user: string) => Promise<{
278
+ user: string;
279
+ deleted: {
280
+ chats: number;
281
+ runs: number;
282
+ };
283
+ }>;
284
+ };
285
+ }
package/dist/index.js ADDED
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Beru's apps API from TypeScript: chat with a Beru instance's agents and run its workflows from
3
+ * your app, as your own users, with the replies streamed. Beru keeps the agents, their tools and
4
+ * every run. Works in Node 18+, edge runtimes and browsers (with a browser token, later).
5
+ *
6
+ * import { Beru } from 'beru-sdk';
7
+ *
8
+ * const beru = new Beru({ baseUrl: 'https://beru.example.com', apiKey: process.env.BERU_APP_KEY });
9
+ * const chat = await beru.chats.create({ agent: '<agent id>', user: 'u_123' });
10
+ * for await (const ev of beru.chats.send(chat.id, 'Where is my order?')) {
11
+ * if (ev.type === 'message.delta') process.stdout.write(ev.text);
12
+ * }
13
+ */
14
+ const API = '/api/apps/v1';
15
+ const RECONNECTS = 5;
16
+ // ── errors ─────────────────────────────────────────────────────────────────────────────────────
17
+ /** An error answer from Beru: its HTTP status, its `code` and its message. */
18
+ export class BeruError extends Error {
19
+ constructor(message, status = 0, code = 'error', retryAfter) {
20
+ super(message);
21
+ this.status = status;
22
+ this.code = code;
23
+ this.retryAfter = retryAfter;
24
+ this.name = 'BeruError';
25
+ }
26
+ }
27
+ /** A run that ended with status `failed`. */
28
+ export class RunFailed extends BeruError {
29
+ constructor(message, run) {
30
+ super(message, 0, 'run_failed');
31
+ this.run = run;
32
+ this.name = 'RunFailed';
33
+ }
34
+ }
35
+ async function errorFrom(response) {
36
+ let body = {};
37
+ try {
38
+ body = await response.json();
39
+ }
40
+ catch {
41
+ /* not JSON */
42
+ }
43
+ const retry = response.headers.get('retry-after');
44
+ return new BeruError(body.message ?? body.detail ?? `HTTP ${response.status}`, response.status, body.code ?? 'error', retry ? Number(retry) : undefined);
45
+ }
46
+ // ── the stream ─────────────────────────────────────────────────────────────────────────────────
47
+ class SSEParser {
48
+ constructor() {
49
+ this.data = [];
50
+ }
51
+ feed(line) {
52
+ if (line === '') {
53
+ if (!this.data.length && this.event === undefined) {
54
+ this.id = undefined;
55
+ return null;
56
+ }
57
+ const raw = this.data.join('\n');
58
+ const id = this.id;
59
+ const name = this.event;
60
+ this.id = undefined;
61
+ this.event = undefined;
62
+ this.data = [];
63
+ let body = {};
64
+ try {
65
+ body = raw ? JSON.parse(raw) : {};
66
+ }
67
+ catch {
68
+ body = { raw };
69
+ }
70
+ return { ...body, type: name ?? body.type ?? 'message', ...(id !== undefined ? { id } : {}) };
71
+ }
72
+ if (line.startsWith(':'))
73
+ return null; // a keep-alive
74
+ const at = line.indexOf(':');
75
+ const field = at < 0 ? line : line.slice(0, at);
76
+ let value = at < 0 ? '' : line.slice(at + 1);
77
+ if (value.startsWith(' '))
78
+ value = value.slice(1);
79
+ if (field === 'id')
80
+ this.id = value;
81
+ else if (field === 'event')
82
+ this.event = value;
83
+ else if (field === 'data')
84
+ this.data.push(value);
85
+ return null;
86
+ }
87
+ }
88
+ async function* linesOf(body) {
89
+ const reader = body.getReader();
90
+ const decoder = new TextDecoder();
91
+ let buf = '';
92
+ try {
93
+ for (;;) {
94
+ const { done, value } = await reader.read();
95
+ if (done)
96
+ break;
97
+ buf += decoder.decode(value, { stream: true });
98
+ let i;
99
+ while ((i = buf.indexOf('\n')) >= 0) {
100
+ const line = buf.slice(0, i).replace(/\r$/, '');
101
+ buf = buf.slice(i + 1);
102
+ yield line;
103
+ }
104
+ }
105
+ buf += decoder.decode();
106
+ if (buf)
107
+ yield buf.replace(/\r$/, '');
108
+ }
109
+ finally {
110
+ reader.releaseLock();
111
+ }
112
+ }
113
+ class Dropped extends Error {
114
+ }
115
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
116
+ /**
117
+ * A run's events as they happen: `for await` over it, or await text() / result() for the end.
118
+ * Beru keeps the run going if the connection drops; this rejoins it from the last event it saw.
119
+ * Iterate it once: a second loop continues where the first stopped.
120
+ */
121
+ export class RunStream {
122
+ constructor(client, method, path, body, params, run) {
123
+ this.client = client;
124
+ this.method = method;
125
+ this.path = path;
126
+ this.body = body;
127
+ this.params = params;
128
+ this.textParts = [];
129
+ this.questions = [];
130
+ this.abort = new AbortController();
131
+ this.run = run;
132
+ }
133
+ /** The run's id, once run.started has arrived. */
134
+ get runId() {
135
+ return this.run;
136
+ }
137
+ [Symbol.asyncIterator]() {
138
+ this.gen ?? (this.gen = this.events());
139
+ return this.gen;
140
+ }
141
+ /** Stop listening. The run itself carries on in Beru. */
142
+ close() {
143
+ this.abort.abort();
144
+ void this.gen?.return(undefined);
145
+ }
146
+ note(ev) {
147
+ if (ev.id !== undefined)
148
+ this.lastId = ev.id;
149
+ if (ev.type === 'run.started')
150
+ this.run = ev.run;
151
+ else if (ev.type === 'message.delta')
152
+ this.textParts.push(ev.text ?? '');
153
+ else if (ev.type === 'question') {
154
+ const { type: _t, id: _i, ...rest } = ev;
155
+ this.questions.push(rest);
156
+ }
157
+ else if (ev.type === 'error')
158
+ this.failure = ev;
159
+ else if (ev.type === 'run.finished')
160
+ this.finished = ev;
161
+ }
162
+ async *events() {
163
+ let { method, path, body, params } = this;
164
+ let attempts = 0;
165
+ for (;;) {
166
+ try {
167
+ const response = await this.client.request(method, path, body, params, this.abort.signal, 'text/event-stream');
168
+ if (!response.body)
169
+ throw new Dropped();
170
+ const parser = new SSEParser();
171
+ for await (const line of linesOf(response.body)) {
172
+ const ev = parser.feed(line);
173
+ if (!ev)
174
+ continue;
175
+ this.note(ev);
176
+ yield ev;
177
+ if (ev.type === 'run.finished')
178
+ return;
179
+ }
180
+ throw new Dropped();
181
+ }
182
+ catch (err) {
183
+ if (err instanceof BeruError || this.abort.signal.aborted)
184
+ throw err;
185
+ // Only a run Beru has started can be rejoined: a request that never got that far is not
186
+ // sent again, so a message is never sent twice.
187
+ if (this.run === undefined || attempts >= this.client.reconnects) {
188
+ throw new BeruError('The stream ended before the run did.', 0, 'stream_lost');
189
+ }
190
+ attempts += 1;
191
+ await wait(Math.min(250 * 2 ** attempts, 5000));
192
+ method = 'GET';
193
+ path = `/runs/${this.run}/events`;
194
+ body = undefined;
195
+ params = this.lastId ? { after: this.lastId } : undefined;
196
+ }
197
+ }
198
+ }
199
+ /** Wait for the end. Throws RunFailed when the run failed. */
200
+ async result() {
201
+ for await (const _ of this) { /* to the end */ }
202
+ const fin = this.finished;
203
+ const status = fin?.status ?? (this.failure ? 'failed' : 'done');
204
+ if (status === 'failed') {
205
+ throw new RunFailed(this.failure?.message ?? fin?.error ?? 'The run failed', this.run);
206
+ }
207
+ return {
208
+ run: this.run, status, message: fin?.message, output: fin?.output, usage: fin?.usage,
209
+ questions: [...this.questions], text: this.textParts.join(''),
210
+ };
211
+ }
212
+ /** Wait for the end and give the reply's text. */
213
+ async text() {
214
+ const res = await this.result();
215
+ return res.message ?? res.text;
216
+ }
217
+ /** Stop the run in Beru. */
218
+ async cancel() {
219
+ if (this.run === undefined) {
220
+ for await (const ev of this)
221
+ if (ev.type === 'run.started')
222
+ break;
223
+ }
224
+ if (this.run === undefined)
225
+ return { stopping: false };
226
+ const out = await this.client.call('POST', `/runs/${this.run}/cancel`);
227
+ this.close();
228
+ return out;
229
+ }
230
+ }
231
+ const env = (name) => globalThis.process?.env?.[name];
232
+ export class Beru {
233
+ constructor(options = {}) {
234
+ this.chats = {
235
+ /** A chat for one of your users with one of the app's agents. */
236
+ create: (opts) => this.call('POST', '/chats', { agent: opts.agent, user: opts.user, ...(opts.title ? { title: opts.title } : {}) }),
237
+ list: async (user) => (await this.call('GET', '/chats', undefined, { user })).chats,
238
+ messages: async (chat) => (await this.call('GET', `/chats/${chat}/messages`)).messages,
239
+ /** Send a message; the reply streams. `.text()` waits for it whole. `context`: what the user is
240
+ * looking at in your app, which the agent is told with this message. */
241
+ send: (chat, text, opts = {}) => new RunStream(this, 'POST', `/chats/${chat}/messages`, { text, ...(opts.context ? { context: opts.context } : {}) }),
242
+ };
243
+ this.tokens = {
244
+ /** A browser token for one of your users, for your page (the chat widget) to call Beru with.
245
+ * Never hand a page your key. With `signIns`, also their tokens for the MCP servers your app signs them in to. */
246
+ create: (opts) => this.call('POST', '/tokens', {
247
+ user: opts.user, ...(opts.expiresIn ? { expires_in: opts.expiresIn } : {}), ...(opts.signIns?.length ? { sign_ins: opts.signIns } : {}),
248
+ }),
249
+ };
250
+ this.agents = {
251
+ /** An agent the app may use: its id, name and description. */
252
+ get: (agent) => this.call('GET', `/agents/${agent}`),
253
+ };
254
+ this.workflows = {
255
+ /** Run a workflow; its steps stream. `(await …result()).output` is its result. */
256
+ run: (workflow, opts = {}) => new RunStream(this, 'POST', `/workflows/${workflow}/runs`, { input: opts.input ?? {}, ...(opts.user ? { user: opts.user } : {}) }),
257
+ /** Start a workflow and return its run id at once; the run carries on in Beru. */
258
+ start: async (workflow, opts = {}) => {
259
+ const stream = this.workflows.run(workflow, opts);
260
+ try {
261
+ for await (const ev of stream)
262
+ if (ev.type === 'run.started')
263
+ break;
264
+ }
265
+ finally {
266
+ stream.close();
267
+ }
268
+ if (!stream.runId)
269
+ throw new BeruError('Beru did not start the run.', 0, 'not_started');
270
+ return stream.runId;
271
+ },
272
+ /** A run's status (running, done, stopped, failed) and, once done, its output. */
273
+ getRun: (workflow, run) => this.call('GET', `/workflows/${workflow}/runs/${run}`),
274
+ };
275
+ this.runs = {
276
+ /** Follow a run (again), from after an event id if given. */
277
+ events: (run, opts = {}) => new RunStream(this, 'GET', `/runs/${run}/events`, undefined, opts.after ? { after: opts.after } : undefined, run),
278
+ cancel: (run) => this.call('POST', `/runs/${run}/cancel`),
279
+ };
280
+ this.users = {
281
+ /** Hand Beru your user's tokens for the MCP servers your app signs them in to. */
282
+ signIn: (user, signIns) => this.call('PUT', `/users/${encodeURIComponent(user)}/sign-ins`, { sign_ins: signIns }),
283
+ /** Delete one of your users' chats, runs and record in Beru. */
284
+ forget: (user) => this.call('DELETE', `/users/${encodeURIComponent(user)}`),
285
+ };
286
+ const baseUrl = (options.baseUrl ?? env('BERU_URL') ?? '').replace(/\/+$/, '');
287
+ const apiKey = options.apiKey ?? env('BERU_APP_KEY');
288
+ if (!baseUrl)
289
+ throw new Error("Give Beru's base URL (baseUrl, or BERU_URL).");
290
+ if (!apiKey)
291
+ throw new Error("Give the app's key (apiKey, or BERU_APP_KEY).");
292
+ this.baseUrl = baseUrl;
293
+ this.headers = { Authorization: `Bearer ${apiKey}` };
294
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
295
+ this.reconnects = options.reconnects ?? RECONNECTS;
296
+ }
297
+ /** @internal */
298
+ async request(method, path, body, params, signal, accept = 'application/json') {
299
+ const query = params && Object.keys(params).length ? `?${new URLSearchParams(params)}` : '';
300
+ const response = await this.fetchImpl(`${this.baseUrl}${API}${path}${query}`, {
301
+ method,
302
+ headers: { ...this.headers, Accept: accept, ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
303
+ body: body !== undefined ? JSON.stringify(body) : undefined,
304
+ signal,
305
+ });
306
+ if (!response.ok)
307
+ throw await errorFrom(response);
308
+ return response;
309
+ }
310
+ /** @internal */
311
+ async call(method, path, body, params) {
312
+ const response = await this.request(method, path, body, params);
313
+ const text = await response.text();
314
+ return (text ? JSON.parse(text) : {});
315
+ }
316
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "beru-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-alpha.17",
4
+ "description": "Use a Beru instance as your app's AI layer: chats with its agents and runs of its workflows, streamed.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json",
24
+ "test": "tsc -p tsconfig.json && node --test test/sdk.test.mjs"
25
+ },
26
+ "devDependencies": {
27
+ "typescript": "^5.8.3"
28
+ },
29
+ "license": "MIT"
30
+ }