@olbrain/js-sdk 1.0.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.
package/README.md ADDED
@@ -0,0 +1,488 @@
1
+ # Olbrain JavaScript SDK
2
+
3
+ Official JavaScript/TypeScript SDK for Olbrain Agent Cloud. Add AI agent chatbots to your website or application with a single line of code.
4
+
5
+ ## 🚀 Quick Start
6
+
7
+ ### For Websites (One-Line Integration)
8
+
9
+ ```html
10
+ <!DOCTYPE html>
11
+ <html>
12
+ <head>
13
+ <title>My Website</title>
14
+ </head>
15
+ <body>
16
+ <h1>Welcome to my website</h1>
17
+
18
+ <!-- ONE LINE: Load and initialize chat widget -->
19
+ <script src="https://unpkg.com/@olbrain/js-sdk@latest/dist/widget.widget.global.js"></script>
20
+ <script>
21
+ new OlbrainWidget.ChatWidget({
22
+ agentId: 'your-agent-id',
23
+ apiKey: 'sk_live_your_key'
24
+ }).mount();
25
+ </script>
26
+ </body>
27
+ </html>
28
+ ```
29
+
30
+ ### For npm Projects
31
+
32
+ ```bash
33
+ npm install @olbrain/js-sdk
34
+ ```
35
+
36
+ **Node.js Example:**
37
+ ```javascript
38
+ import { AgentClient } from '@olbrain/js-sdk';
39
+
40
+ const client = new AgentClient({
41
+ agentId: 'your-agent-id',
42
+ apiKey: 'sk_live_your_key'
43
+ });
44
+
45
+ async function chat() {
46
+ const sessionId = await client.createSession();
47
+ const response = await client.sendAndWait(sessionId, 'Hello!');
48
+ console.log(response.text);
49
+ }
50
+
51
+ chat();
52
+ ```
53
+
54
+ ## 📦 Installation
55
+
56
+ ### Browser (Via CDN)
57
+
58
+ **Core API only:**
59
+ ```html
60
+ <script src="https://unpkg.com/@olbrain/js-sdk@latest/dist/index.global.js"></script>
61
+ <script>
62
+ const client = new Olbrain.AgentClient({ agentId: '...', apiKey: '...' });
63
+ </script>
64
+ ```
65
+
66
+ **With Chat Widget:**
67
+ ```html
68
+ <script src="https://unpkg.com/@olbrain/js-sdk@latest/dist/widget.widget.global.js"></script>
69
+ <script>
70
+ new OlbrainWidget.ChatWidget({ agentId: '...', apiKey: '...' }).mount();
71
+ </script>
72
+ ```
73
+
74
+ ### npm / Node.js
75
+
76
+ ```bash
77
+ npm install @olbrain/js-sdk
78
+
79
+ # For Node.js streaming support (optional)
80
+ npm install eventsource
81
+ ```
82
+
83
+ ### TypeScript
84
+
85
+ The SDK is written in TypeScript and includes full type definitions.
86
+
87
+ ```typescript
88
+ import { AgentClient, ChatResponse } from '@olbrain/js-sdk';
89
+
90
+ const client = new AgentClient({ agentId: '...', apiKey: '...' });
91
+ const response: ChatResponse = await client.sendAndWait(sessionId, 'Hi!');
92
+ ```
93
+
94
+ ## 🎯 Core Concepts
95
+
96
+ ### AgentClient
97
+
98
+ The main API client for communicating with Olbrain agents.
99
+
100
+ ```javascript
101
+ const client = new AgentClient({
102
+ agentId: 'your-agent-id',
103
+ apiKey: 'sk_live_your_key',
104
+ baseUrl: 'https://...', // Optional, defaults to production
105
+ });
106
+ ```
107
+
108
+ ### Sessions
109
+
110
+ Each conversation is managed through a session. Sessions maintain message history and context.
111
+
112
+ ```javascript
113
+ // Create a new session
114
+ const sessionId = await client.createSession({
115
+ title: 'My Chat',
116
+ userId: 'user123',
117
+ metadata: { custom: 'data' }
118
+ });
119
+
120
+ // Get session info
121
+ const session = await client.getSession(sessionId);
122
+
123
+ // Update session
124
+ await client.updateSession(sessionId, { title: 'New Title' });
125
+
126
+ // Delete session
127
+ await client.deleteSession(sessionId);
128
+ ```
129
+
130
+ ### Messaging
131
+
132
+ Send messages and receive responses.
133
+
134
+ ```javascript
135
+ // Send and wait for response (blocking)
136
+ const response = await client.sendAndWait(sessionId, 'Your message', {
137
+ timeout: 30000,
138
+ metadata: { source: 'web' }
139
+ });
140
+
141
+ console.log(response.text); // Agent's response
142
+ console.log(response.tokenUsage); // Token usage stats
143
+ console.log(response.responseTimeMs); // Response latency
144
+
145
+ // Send without waiting (fire and forget)
146
+ await client.send(sessionId, 'Your message');
147
+ ```
148
+
149
+ ### Streaming (Real-time Messages)
150
+
151
+ Listen for messages in real-time via Server-Sent Events.
152
+
153
+ ```javascript
154
+ // Start listening for messages
155
+ await client.listen(
156
+ sessionId,
157
+ (message) => {
158
+ console.log(`${message.role}: ${message.content}`);
159
+ },
160
+ (error) => {
161
+ console.error('Stream error:', error);
162
+ }
163
+ );
164
+
165
+ // Send message (will be received via stream)
166
+ await client.send(sessionId, 'Tell me a story');
167
+
168
+ // Stop listening
169
+ client.stopListening(sessionId);
170
+ ```
171
+
172
+ ## 🎨 Chat Widget
173
+
174
+ Ready-to-use chat widget component for instant deployment.
175
+
176
+ ### Basic Usage
177
+
178
+ ```html
179
+ <script src="https://unpkg.com/@olbrain/js-sdk@latest/dist/widget.widget.global.js"></script>
180
+ <script>
181
+ new OlbrainWidget.ChatWidget({
182
+ agentId: 'your-agent-id',
183
+ apiKey: 'sk_live_your_key'
184
+ }).mount();
185
+ </script>
186
+ ```
187
+
188
+ ### Configuration Options
189
+
190
+ ```javascript
191
+ new OlbrainWidget.ChatWidget({
192
+ // Required
193
+ agentId: 'your-agent-id',
194
+ apiKey: 'sk_live_your_key',
195
+
196
+ // UI Options
197
+ position: 'bottom-right', // 'bottom-right' | 'bottom-left' | 'custom'
198
+ title: 'Chat with us', // Widget header title
199
+ greeting: 'Hi! How can I help?', // Initial greeting message
200
+ placeholder: 'Type here...', // Input placeholder text
201
+ theme: 'light', // 'light' | 'dark' | 'auto'
202
+ primaryColor: '#667eea', // Brand color
203
+
204
+ // Behavior
205
+ autoOpen: false, // Auto-open on load
206
+ persistSession: true, // Save session in localStorage
207
+
208
+ // Advanced
209
+ target: document.body, // Where to mount (selector or element)
210
+ onMessage: (msg) => {}, // Custom message callback
211
+ baseUrl: '...', // Custom API base URL
212
+ }).mount();
213
+ ```
214
+
215
+ ### Widget Methods
216
+
217
+ ```javascript
218
+ const widget = new OlbrainWidget.ChatWidget({ agentId: '...', apiKey: '...' });
219
+
220
+ widget.mount(); // Mount to page (required)
221
+ widget.unmount(); // Remove from page
222
+ widget.open(); // Open chat window
223
+ widget.close(); // Close chat window
224
+ await widget.sendMessage('Hello!'); // Send message programmatically
225
+ ```
226
+
227
+ ## 📚 API Reference
228
+
229
+ ### AgentClient Methods
230
+
231
+ #### Session Management
232
+
233
+ ```javascript
234
+ // Create session
235
+ await client.createSession(options?: CreateSessionOptions): Promise<string>
236
+
237
+ // Get session info
238
+ await client.getSession(sessionId: string): Promise<SessionInfo>
239
+
240
+ // Update session
241
+ await client.updateSession(sessionId: string, updates: SessionUpdates): Promise<SessionInfo>
242
+
243
+ // Delete session
244
+ await client.deleteSession(sessionId: string): Promise<void>
245
+
246
+ // Get session messages
247
+ await client.getMessages(sessionId: string, limit?: number): Promise<Message[]>
248
+
249
+ // Get session statistics
250
+ await client.getSessionStats(sessionId: string): Promise<SessionStats>
251
+ ```
252
+
253
+ #### Messaging
254
+
255
+ ```javascript
256
+ // Send message and wait for response
257
+ await client.sendAndWait(
258
+ sessionId: string,
259
+ message: string,
260
+ options?: SendOptions
261
+ ): Promise<ChatResponse>
262
+
263
+ // Send message without waiting
264
+ await client.send(sessionId: string, message: string): Promise<void>
265
+ ```
266
+
267
+ #### Streaming
268
+
269
+ ```javascript
270
+ // Start listening for real-time messages
271
+ await client.listen(
272
+ sessionId: string,
273
+ onMessage: MessageCallback,
274
+ onError?: ErrorCallback
275
+ ): Promise<void>
276
+
277
+ // Stop listening
278
+ client.stopListening(sessionId: string): void
279
+ ```
280
+
281
+ #### Lifecycle
282
+
283
+ ```javascript
284
+ // Close client and cleanup resources
285
+ client.close(): void
286
+ ```
287
+
288
+ ### Type Definitions
289
+
290
+ ```typescript
291
+ interface AgentConfig {
292
+ agentId: string;
293
+ apiKey: string;
294
+ baseUrl?: string;
295
+ }
296
+
297
+ interface ChatResponse {
298
+ text: string;
299
+ sessionId: string;
300
+ success: boolean;
301
+ tokenUsage?: TokenUsage;
302
+ modelUsed?: string;
303
+ responseTimeMs?: number;
304
+ error?: string;
305
+ }
306
+
307
+ interface Message {
308
+ role: 'user' | 'assistant';
309
+ content: string;
310
+ timestamp: string;
311
+ metadata?: Record<string, any>;
312
+ }
313
+
314
+ interface SessionInfo {
315
+ sessionId: string;
316
+ title: string;
317
+ status: 'active' | 'archived';
318
+ createdAt: string;
319
+ messageCount: number;
320
+ userId?: string;
321
+ metadata: Record<string, any>;
322
+ }
323
+
324
+ interface TokenUsage {
325
+ promptTokens: number;
326
+ completionTokens: number;
327
+ totalTokens: number;
328
+ cost?: number;
329
+ }
330
+ ```
331
+
332
+ ## 🔐 Error Handling
333
+
334
+ The SDK provides typed error classes for precise error handling.
335
+
336
+ ```javascript
337
+ import {
338
+ OlbrainError,
339
+ AuthenticationError,
340
+ SessionNotFoundError,
341
+ RateLimitError,
342
+ NetworkError,
343
+ ValidationError,
344
+ StreamingError
345
+ } from '@olbrain/js-sdk';
346
+
347
+ try {
348
+ const response = await client.sendAndWait(sessionId, 'Hello!');
349
+ } catch (error) {
350
+ if (error instanceof AuthenticationError) {
351
+ console.error('Invalid API key');
352
+ } else if (error instanceof RateLimitError) {
353
+ console.error(`Rate limited. Retry after ${error.retryAfter}s`);
354
+ } else if (error instanceof SessionNotFoundError) {
355
+ console.error(`Session ${error.sessionId} not found`);
356
+ } else if (error instanceof OlbrainError) {
357
+ console.error('API error:', error.message);
358
+ }
359
+ }
360
+ ```
361
+
362
+ ## 📖 Examples
363
+
364
+ See the `examples/` directory for complete working examples:
365
+
366
+ - **Browser Examples:**
367
+ - `examples/browser/chat-widget.html` - One-line widget embed
368
+ - `examples/browser/api-client.html` - Core API usage
369
+ - `examples/browser/streaming.html` - Real-time messaging
370
+
371
+ - **Node.js Examples:**
372
+ - `examples/node/basic.js` - Basic usage
373
+ - `examples/node/streaming.js` - Streaming with Node.js
374
+
375
+ - **TypeScript Examples:**
376
+ - `examples/typescript/advanced.ts` - Advanced patterns with full type safety
377
+
378
+ ## 🌐 Browser Compatibility
379
+
380
+ - Chrome 90+
381
+ - Firefox 88+
382
+ - Safari 14+
383
+ - Edge 90+
384
+ - Mobile browsers (iOS Safari, Chrome Mobile)
385
+
386
+ ## 📦 Build Outputs
387
+
388
+ The SDK includes multiple build formats for different use cases:
389
+
390
+ - **CJS** (`dist/index.js`) - CommonJS for Node.js
391
+ - **ESM** (`dist/index.mjs`) - ES Modules for modern tooling
392
+ - **UMD** (`dist/index.global.js`) - Universal Module for browsers and Node.js
393
+ - **UMD Widget** (`dist/widget.widget.global.js`) - Pre-built widget
394
+
395
+ ## 🔧 Development
396
+
397
+ ### Setup
398
+
399
+ ```bash
400
+ npm install
401
+ npm run build
402
+ npm test
403
+ npm run typecheck
404
+ ```
405
+
406
+ ### Build
407
+
408
+ ```bash
409
+ npm run build # Production build
410
+ npm run dev # Watch mode
411
+ npm run clean # Clean dist/
412
+ ```
413
+
414
+ ### Testing
415
+
416
+ ```bash
417
+ npm test # Run tests
418
+ npm test -- --ui # Watch with UI
419
+ ```
420
+
421
+ ### Type Checking
422
+
423
+ ```bash
424
+ npm run typecheck
425
+ ```
426
+
427
+ ## 📝 API Key Format
428
+
429
+ API keys start with specific prefixes:
430
+ - `sk_live_*` - Production secret key
431
+ - `org_live_*` - Organization key
432
+ - `sk_*` - Development secret key
433
+ - `org_*` - Development organization key
434
+
435
+ ## 🚀 Performance
436
+
437
+ - **Bundle Size:** ~30KB for core API, ~50KB for widget (gzipped)
438
+ - **Zero Runtime Dependencies:** No external dependencies for browser builds
439
+ - **Optional Dependencies:** `eventsource` for Node.js streaming
440
+
441
+ ## 🔄 Session Persistence
442
+
443
+ The widget automatically saves sessions to localStorage:
444
+
445
+ ```javascript
446
+ // Auto-saved in localStorage as 'olbrain_widget_session_id'
447
+ // Sessions persist across page reloads by default
448
+ // Disable with: persistSession: false
449
+ ```
450
+
451
+ ## 🌟 Features
452
+
453
+ - ✅ One-line browser integration
454
+ - ✅ Full TypeScript support
455
+ - ✅ Real-time SSE streaming
456
+ - ✅ Session persistence
457
+ - ✅ Error handling with typed exceptions
458
+ - ✅ Customizable UI theme and colors
459
+ - ✅ Mobile responsive widget
460
+ - ✅ Keyboard shortcuts (Enter to send)
461
+ - ✅ Message history
462
+ - ✅ Token usage tracking
463
+ - ✅ Response latency metrics
464
+ - ✅ Automatic reconnection
465
+ - ✅ ARIA labels & accessibility
466
+
467
+ ## 📄 License
468
+
469
+ MIT
470
+
471
+ ## 🤝 Support
472
+
473
+ For issues, feature requests, or questions:
474
+
475
+ 1. Check [existing issues](https://github.com/anthropics/olbrain-js-sdk/issues)
476
+ 2. [Create a new issue](https://github.com/anthropics/olbrain-js-sdk/issues/new)
477
+ 3. Visit the [Olbrain documentation](https://docs.olbrain.com)
478
+
479
+ ## 📚 Related Resources
480
+
481
+ - [Python SDK](https://github.com/anthropics/olbrain-python-sdk)
482
+ - [Olbrain Documentation](https://docs.olbrain.com)
483
+ - [API Reference](https://docs.olbrain.com/api)
484
+ - [Getting Started Guide](https://docs.olbrain.com/getting-started)
485
+
486
+ ---
487
+
488
+ Made with ❤️ by the Olbrain team
@@ -0,0 +1,29 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require2() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+
15
+ // node_modules/tsup/assets/esm_shims.js
16
+ import path from "path";
17
+ import { fileURLToPath } from "url";
18
+ var init_esm_shims = __esm({
19
+ "node_modules/tsup/assets/esm_shims.js"() {
20
+ "use strict";
21
+ }
22
+ });
23
+
24
+ export {
25
+ __require,
26
+ __commonJS,
27
+ init_esm_shims
28
+ };
29
+ //# sourceMappingURL=chunk-QEZYOGUI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n"],"mappings":";;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;","names":[]}