oblien 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Oblien
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 ADDED
@@ -0,0 +1,455 @@
1
+ # Oblien Core SDK
2
+
3
+ Server-side SDK for building AI-powered applications with Oblien platform.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install oblien-core
9
+ ```
10
+
11
+ ## What This SDK Does
12
+
13
+ **Server-Side Only** - This SDK is for creating and managing chat sessions on your server. It **does not** handle actual messaging - that happens client-side in the browser using the tokens this SDK generates.
14
+
15
+ ### Workflow:
16
+
17
+ 1. **Server:** Create session using this SDK → Get token
18
+ 2. **Server:** Send token to client (browser)
19
+ 3. **Client:** Use token to chat directly with Oblien API
20
+ 4. **Client:** Use [react-chat-agent](https://npmjs.com/package/react-chat-agent) or your own implementation
21
+
22
+ ## Quick Start
23
+
24
+ ### 1. Initialize Client
25
+
26
+ ```javascript
27
+ import { OblienClient } from 'oblien-core';
28
+
29
+ const client = new OblienClient({
30
+ apiKey: 'your-api-key',
31
+ apiSecret: 'your-api-secret', // For server-side
32
+ });
33
+ ```
34
+
35
+ ### 2. Create Chat Session
36
+
37
+ ```javascript
38
+ import { OblienChat } from 'oblien-core/chat';
39
+
40
+ const chat = new OblienChat(client);
41
+
42
+ // Create session
43
+ const session = await chat.createSession({
44
+ agentId: 'your-agent-id',
45
+ // workflowId: 'workflow-id', // Optional
46
+ // workspace: {}, // Optional
47
+ });
48
+
49
+ console.log(session);
50
+ // {
51
+ // sessionId: 'session-xxx',
52
+ // token: 'jwt-token-for-client',
53
+ // agentId: 'agent-id',
54
+ // namespace: null
55
+ // }
56
+ ```
57
+
58
+ ### 3. Send Token to Client
59
+
60
+ ```javascript
61
+ // Express example
62
+ app.post('/api/create-session', async (req, res) => {
63
+ const session = await chat.createSession({
64
+ agentId: req.body.agentId,
65
+ });
66
+
67
+ res.json({
68
+ sessionId: session.sessionId,
69
+ token: session.token, // Client uses this to chat
70
+ });
71
+ });
72
+ ```
73
+
74
+ ### 4. Client Uses Token
75
+
76
+ ```javascript
77
+ // In browser (using react-chat-agent)
78
+ import { ChatProvider } from 'react-chat-agent';
79
+
80
+ function App() {
81
+ const [sessionToken, setSessionToken] = useState(null);
82
+
83
+ useEffect(() => {
84
+ // Get token from your server
85
+ fetch('/api/create-session', {
86
+ method: 'POST',
87
+ body: JSON.stringify({ agentId: 'agent-id' }),
88
+ })
89
+ .then(r => r.json())
90
+ .then(data => setSessionToken(data.token));
91
+ }, []);
92
+
93
+ if (!sessionToken) return <div>Loading...</div>;
94
+
95
+ return (
96
+ <ChatProvider token={sessionToken}>
97
+ <ChatPanel />
98
+ </ChatProvider>
99
+ );
100
+ }
101
+ ```
102
+
103
+ ## Guest Sessions (Rate Limited)
104
+
105
+ For anonymous users, create guest sessions based on IP address:
106
+
107
+ ```javascript
108
+ import { OblienChat } from 'oblien-core/chat';
109
+
110
+ const chat = new OblienChat(client);
111
+
112
+ // Express route
113
+ app.post('/api/guest-session', async (req, res) => {
114
+ const ip = req.ip || req.headers['x-forwarded-for'];
115
+
116
+ const session = await chat.createGuestSession({
117
+ ip: ip,
118
+ agentId: 'your-agent-id',
119
+ metadata: {
120
+ userAgent: req.headers['user-agent'],
121
+ referrer: req.headers['referer'],
122
+ },
123
+ });
124
+
125
+ res.json({
126
+ sessionId: session.sessionId,
127
+ token: session.token,
128
+ guest: session.guest,
129
+ // Guest sessions are rate-limited automatically
130
+ });
131
+ });
132
+ ```
133
+
134
+ ### Guest Features:
135
+
136
+ - ✅ Automatic rate limiting (100K tokens/day, 50 messages/day)
137
+ - ✅ IP-based identification (privacy-friendly)
138
+ - ✅ Auto-expiring sessions (24h TTL)
139
+ - ✅ Built-in caching with `node-cache` (no Redis required!)
140
+ - ✅ Optional Redis support for distributed systems
141
+
142
+ ## Guest Storage Options
143
+
144
+ ### Default: NodeCache (Recommended)
145
+
146
+ Works out of the box - no setup needed:
147
+
148
+ ```javascript
149
+ import { OblienChat } from 'oblien-core/chat';
150
+
151
+ const chat = new OblienChat(client);
152
+ // Uses NodeCacheStorage by default
153
+ // Automatic expiration, memory management, and cleanup
154
+ ```
155
+
156
+ ### Option 1: Custom NodeCache Settings
157
+
158
+ ```javascript
159
+ import { OblienChat, NodeCacheStorage } from 'oblien-core/chat';
160
+
161
+ const storage = new NodeCacheStorage(86400); // 24 hours TTL
162
+
163
+ const chat = new OblienChat(client, {
164
+ guestStorage: storage,
165
+ });
166
+
167
+ // Get cache stats
168
+ console.log(storage.getStats());
169
+ ```
170
+
171
+ ### Option 2: Redis (For Distributed Systems)
172
+
173
+ ```javascript
174
+ import { createClient } from 'redis';
175
+ import { OblienChat, RedisStorage } from 'oblien-core/chat';
176
+
177
+ const redis = createClient();
178
+ await redis.connect();
179
+
180
+ const chat = new OblienChat(client, {
181
+ guestStorage: new RedisStorage(redis),
182
+ guestTTL: 86400, // 24 hours
183
+ });
184
+ ```
185
+
186
+ ### Option 3: Simple In-Memory (Dev Only)
187
+
188
+ ```javascript
189
+ import { OblienChat, InMemoryStorage } from 'oblien-core/chat';
190
+
191
+ const chat = new OblienChat(client, {
192
+ guestStorage: new InMemoryStorage(),
193
+ });
194
+ // Note: Basic Map storage, no advanced features
195
+ ```
196
+
197
+ ## API Reference
198
+
199
+ ### `OblienClient`
200
+
201
+ Main client for authentication:
202
+
203
+ ```javascript
204
+ const client = new OblienClient({
205
+ apiKey: string,
206
+ apiSecret?: string,
207
+ baseURL?: string,
208
+ });
209
+ ```
210
+
211
+ ### `OblienChat`
212
+
213
+ Session management:
214
+
215
+ ```javascript
216
+ const chat = new OblienChat(client, options?);
217
+
218
+ // Create regular session
219
+ await chat.createSession({ agentId, workflowId?, workspace? });
220
+
221
+ // Create guest session
222
+ await chat.createGuestSession({ ip, agentId, workflowId?, metadata?, workspace? });
223
+
224
+ // Get session info
225
+ await chat.getSession(sessionId);
226
+
227
+ // List sessions
228
+ await chat.listSessions({ page?, limit? });
229
+
230
+ // Delete session
231
+ await chat.deleteSession(sessionId);
232
+
233
+ // Guest management
234
+ await chat.getGuestByIP(ip);
235
+ await chat.getAllGuests(); // Admin only
236
+ await chat.cleanupGuests(); // Clean expired
237
+ ```
238
+
239
+ ### `GuestManager`
240
+
241
+ Manual guest management:
242
+
243
+ ```javascript
244
+ import { GuestManager } from 'oblien-core/chat';
245
+
246
+ const guestManager = new GuestManager({
247
+ storage?: StorageAdapter,
248
+ ttl?: number, // seconds
249
+ onGuestCreated?: (guest) => void,
250
+ });
251
+
252
+ await guestManager.getOrCreateGuest(ip, metadata?);
253
+ await guestManager.getGuest(guestId);
254
+ await guestManager.updateGuest(guestId, updates);
255
+ await guestManager.deleteGuest(guestId);
256
+ await guestManager.getAllGuests();
257
+ await guestManager.cleanup();
258
+ ```
259
+
260
+ ## Complete Example
261
+
262
+ ### Express Server
263
+
264
+ ```javascript
265
+ import express from 'express';
266
+ import { OblienClient, OblienChat } from 'oblien-core';
267
+
268
+ const app = express();
269
+ app.use(express.json());
270
+
271
+ // Initialize Oblien
272
+ const client = new OblienClient({
273
+ apiKey: process.env.OBLIEN_API_KEY,
274
+ apiSecret: process.env.OBLIEN_API_SECRET,
275
+ });
276
+
277
+ const chat = new OblienChat(client);
278
+
279
+ // Create authenticated session
280
+ app.post('/api/session', async (req, res) => {
281
+ try {
282
+ const session = await chat.createSession({
283
+ agentId: req.body.agentId,
284
+ });
285
+
286
+ res.json(session);
287
+ } catch (error) {
288
+ res.status(500).json({ error: error.message });
289
+ }
290
+ });
291
+
292
+ // Create guest session
293
+ app.post('/api/guest-session', async (req, res) => {
294
+ try {
295
+ const ip = req.ip;
296
+
297
+ const session = await chat.createGuestSession({
298
+ ip,
299
+ agentId: req.body.agentId,
300
+ });
301
+
302
+ res.json(session);
303
+ } catch (error) {
304
+ res.status(500).json({ error: error.message });
305
+ }
306
+ });
307
+
308
+ app.listen(3000);
309
+ ```
310
+
311
+ ### Next.js API Route
312
+
313
+ ```javascript
314
+ // pages/api/session.js
315
+ import { OblienClient, OblienChat } from 'oblien-core';
316
+
317
+ const client = new OblienClient({
318
+ apiKey: process.env.OBLIEN_API_KEY,
319
+ apiSecret: process.env.OBLIEN_API_SECRET,
320
+ });
321
+
322
+ const chat = new OblienChat(client);
323
+
324
+ export default async function handler(req, res) {
325
+ if (req.method !== 'POST') {
326
+ return res.status(405).json({ error: 'Method not allowed' });
327
+ }
328
+
329
+ try {
330
+ // For guests
331
+ if (!req.headers.authorization) {
332
+ const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
333
+
334
+ const session = await chat.createGuestSession({
335
+ ip,
336
+ agentId: req.body.agentId,
337
+ });
338
+
339
+ return res.json(session);
340
+ }
341
+
342
+ // For authenticated users
343
+ const session = await chat.createSession({
344
+ agentId: req.body.agentId,
345
+ });
346
+
347
+ res.json(session);
348
+ } catch (error) {
349
+ res.status(500).json({ error: error.message });
350
+ }
351
+ }
352
+ ```
353
+
354
+ ## Environment Variables
355
+
356
+ ```bash
357
+ OBLIEN_API_KEY=your-api-key
358
+ OBLIEN_API_SECRET=your-api-secret
359
+ OBLIEN_BASE_URL=https://api.oblien.com # Optional
360
+ ```
361
+
362
+ ## Storage Comparison
363
+
364
+ | Feature | NodeCache (Default) | InMemory | Redis |
365
+ |---------|-------------------|----------|-------|
366
+ | **Setup** | ✅ Zero config | ✅ Zero config | ⚠️ Requires Redis |
367
+ | **Auto-expiry** | ✅ Yes | ✅ Manual | ✅ Yes |
368
+ | **Memory limit** | ✅ Configurable | ❌ No | ✅ Configurable |
369
+ | **Statistics** | ✅ Yes | ❌ No | ⚠️ Via Redis |
370
+ | **Distributed** | ❌ Single instance | ❌ Single instance | ✅ Multi-server |
371
+ | **Persistence** | ❌ Memory only | ❌ Memory only | ✅ Disk backup |
372
+ | **Production** | ✅ Recommended | ❌ Dev only | ✅ High-traffic |
373
+
374
+ ### When to Use What:
375
+
376
+ - **NodeCache**: Most applications, single server, < 100K guests/day ✅ Recommended
377
+ - **InMemory**: Development, testing, quick prototypes
378
+ - **Redis**: Distributed systems, > 1M guests/day, need persistence
379
+
380
+ ## Examples
381
+
382
+ Check the `/examples` folder for complete examples:
383
+
384
+ - `express-server.js` - Full Express.js implementation
385
+ - `nextjs-api-route.js` - Next.js API routes (App Router & Pages Router)
386
+ - `with-redis.js` - Production setup with Redis
387
+
388
+ ## TypeScript Support
389
+
390
+ Full TypeScript definitions included:
391
+
392
+ ```typescript
393
+ import { OblienClient, OblienChat } from 'oblien-core';
394
+
395
+ const client: OblienClient = new OblienClient({
396
+ apiKey: string,
397
+ apiSecret?: string,
398
+ });
399
+
400
+ const chat: OblienChat = new OblienChat(client);
401
+ ```
402
+
403
+ ## FAQ
404
+
405
+ ### Q: Do I need Redis?
406
+
407
+ **A:** No! NodeCache works great for most applications. Use Redis only if you need multi-server support or very high traffic.
408
+
409
+ ### Q: How does guest rate limiting work?
410
+
411
+ **A:** Guest sessions are automatically rate-limited by the Oblien API based on the `namespace` (guest ID). Limits:
412
+ - 100K tokens/day
413
+ - 50 messages/day
414
+ - 20 messages/hour
415
+
416
+ ### Q: Can I use custom guest IDs instead of IP?
417
+
418
+ **A:** Yes! Just create your own guest ID and pass it as the `namespace`:
419
+
420
+ ```javascript
421
+ await chat.createSession({
422
+ agentId: 'agent-id',
423
+ isGuest: true,
424
+ namespace: 'custom-guest-id',
425
+ });
426
+ ```
427
+
428
+ ### Q: How do I clean up expired guests?
429
+
430
+ **A:** Call `chat.cleanupGuests()` periodically (e.g., cron job or `setInterval`).
431
+
432
+ ## Performance
433
+
434
+ Benchmarks on standard server:
435
+
436
+ - Session creation: ~50ms
437
+ - Guest lookup (cached): ~1ms
438
+ - Guest cleanup (1000 guests): ~100ms
439
+
440
+ ## Dependencies
441
+
442
+ - `node-cache` - Built-in caching (included)
443
+ - `redis` - Optional, for distributed systems (peer dependency)
444
+
445
+ ## License
446
+
447
+ MIT
448
+
449
+ ## Links
450
+
451
+ - [Documentation](https://oblien.com/docs/core-sdk)
452
+ - [GitHub](https://github.com/oblien/oblien-core)
453
+ - [Website](https://oblien.com)
454
+ - [React Chat Agent](https://npmjs.com/package/react-chat-agent) - Client-side chat component
455
+ - [Agent Sandbox](https://npmjs.com/package/agent-sandbox) - Sandbox SDK
package/chat.js ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Chat Module Entry Point
3
+ * Import this for chat session management only
4
+ */
5
+
6
+ export { OblienChat, ChatSession } from './src/chat/index.js';
7
+ export {
8
+ GuestManager,
9
+ NodeCacheStorage,
10
+ InMemoryStorage,
11
+ RedisStorage
12
+ } from './src/utils/guest-manager.js';
13
+
14
+ export default {
15
+ OblienChat,
16
+ ChatSession,
17
+ GuestManager,
18
+ NodeCacheStorage,
19
+ InMemoryStorage,
20
+ RedisStorage
21
+ };
package/index.d.ts ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * TypeScript definitions for oblien-core
3
+ */
4
+
5
+ // ============ Client Types ============
6
+
7
+ export interface OblienConfig {
8
+ apiKey: string;
9
+ apiSecret?: string;
10
+ baseURL?: string;
11
+ version?: string;
12
+ }
13
+
14
+ export class OblienClient {
15
+ constructor(config: OblienConfig);
16
+
17
+ authenticate(): Promise<string>;
18
+ getAuthHeaders(): Promise<Record<string, string>>;
19
+ get(path: string, params?: Record<string, any>): Promise<any>;
20
+ post(path: string, body?: Record<string, any>): Promise<any>;
21
+ put(path: string, body?: Record<string, any>): Promise<any>;
22
+ delete(path: string): Promise<any>;
23
+ }
24
+
25
+ // ============ Storage Adapters ============
26
+
27
+ export interface StorageAdapter {
28
+ get(key: string): Promise<any>;
29
+ set(key: string, value: any, ttl?: number): Promise<boolean>;
30
+ delete(key: string): Promise<boolean>;
31
+ getAll(pattern: string): Promise<any[]>;
32
+ }
33
+
34
+ export class NodeCacheStorage implements StorageAdapter {
35
+ constructor(ttl?: number);
36
+
37
+ get(key: string): Promise<any>;
38
+ set(key: string, value: any, ttl?: number): Promise<boolean>;
39
+ delete(key: string): Promise<boolean>;
40
+ getAll(pattern: string): Promise<any[]>;
41
+ getStats(): any;
42
+ clear(): void;
43
+ }
44
+
45
+ export class InMemoryStorage implements StorageAdapter {
46
+ get(key: string): Promise<any>;
47
+ set(key: string, value: any, ttl?: number): Promise<boolean>;
48
+ delete(key: string): Promise<boolean>;
49
+ getAll(pattern: string): Promise<any[]>;
50
+ }
51
+
52
+ export class RedisStorage implements StorageAdapter {
53
+ constructor(redisClient: any);
54
+
55
+ get(key: string): Promise<any>;
56
+ set(key: string, value: any, ttl?: number): Promise<boolean>;
57
+ delete(key: string): Promise<boolean>;
58
+ getAll(pattern: string): Promise<any[]>;
59
+ }
60
+
61
+ // ============ Guest Manager ============
62
+
63
+ export interface GuestManagerOptions {
64
+ storage?: StorageAdapter;
65
+ ttl?: number;
66
+ onGuestCreated?: (guest: Guest) => void;
67
+ }
68
+
69
+ export interface Guest {
70
+ id: string;
71
+ namespace: string;
72
+ ip: string;
73
+ isGuest: boolean;
74
+ createdAt: string;
75
+ lastSeen: string;
76
+ metadata: Record<string, any>;
77
+ sessions: string[];
78
+ }
79
+
80
+ export class GuestManager {
81
+ constructor(options?: GuestManagerOptions);
82
+
83
+ generateGuestId(ip: string): string;
84
+ getOrCreateGuest(ip: string, metadata?: Record<string, any>): Promise<Guest>;
85
+ getGuest(guestId: string): Promise<Guest | null>;
86
+ updateGuest(guestId: string, updates: Partial<Guest>): Promise<Guest>;
87
+ addSession(guestId: string, sessionId: string): Promise<Guest>;
88
+ deleteGuest(guestId: string): Promise<boolean>;
89
+ getAllGuests(): Promise<Guest[]>;
90
+ cleanup(): Promise<number>;
91
+ }
92
+
93
+ // ============ Chat Session ============
94
+
95
+ export interface SessionOptions {
96
+ client: OblienClient;
97
+ sessionId?: string;
98
+ agentId?: string;
99
+ workflowId?: string;
100
+ isGuest?: boolean;
101
+ namespace?: string;
102
+ workspace?: Record<string, any>;
103
+ }
104
+
105
+ export interface SessionData {
106
+ sessionId: string;
107
+ token: string;
108
+ agentId?: string;
109
+ workflowId?: string;
110
+ namespace?: string;
111
+ }
112
+
113
+ export class ChatSession {
114
+ constructor(options: SessionOptions);
115
+
116
+ sessionId: string | null;
117
+ token: string | null;
118
+
119
+ create(): Promise<SessionData>;
120
+ get(sessionId?: string): Promise<any>;
121
+ delete(sessionId?: string): Promise<any>;
122
+ list(options?: Record<string, any>): Promise<any[]>;
123
+ }
124
+
125
+ // ============ Chat Manager ============
126
+
127
+ export interface ChatOptions {
128
+ guestManager?: GuestManager;
129
+ guestStorage?: StorageAdapter;
130
+ guestTTL?: number;
131
+ }
132
+
133
+ export interface CreateSessionOptions {
134
+ agentId: string;
135
+ workflowId?: string;
136
+ workspace?: Record<string, any>;
137
+ }
138
+
139
+ export interface CreateGuestSessionOptions {
140
+ ip: string;
141
+ agentId: string;
142
+ workflowId?: string;
143
+ metadata?: Record<string, any>;
144
+ workspace?: Record<string, any>;
145
+ }
146
+
147
+ export interface GuestSessionData extends SessionData {
148
+ guest: {
149
+ id: string;
150
+ namespace: string;
151
+ createdAt: string;
152
+ };
153
+ }
154
+
155
+ export class OblienChat {
156
+ constructor(client: OblienClient, options?: ChatOptions);
157
+
158
+ createSession(options: CreateSessionOptions): Promise<SessionData>;
159
+ createGuestSession(options: CreateGuestSessionOptions): Promise<GuestSessionData>;
160
+ getGuestByIP(ip: string): Promise<Guest | null>;
161
+ getSession(sessionId: string): Promise<any>;
162
+ listSessions(options?: Record<string, any>): Promise<any[]>;
163
+ deleteSession(sessionId: string): Promise<any>;
164
+ getAllGuests(): Promise<Guest[]>;
165
+ cleanupGuests(): Promise<number>;
166
+ }
167
+
168
+ // ============ Exports ============
169
+
170
+ declare const _default: {
171
+ OblienClient: typeof OblienClient;
172
+ OblienChat: typeof OblienChat;
173
+ ChatSession: typeof ChatSession;
174
+ GuestManager: typeof GuestManager;
175
+ NodeCacheStorage: typeof NodeCacheStorage;
176
+ InMemoryStorage: typeof InMemoryStorage;
177
+ RedisStorage: typeof RedisStorage;
178
+ };
179
+
180
+ export default _default;
package/index.js ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Oblien Core SDK
3
+ * Server-side SDK for Oblien AI Platform
4
+ */
5
+
6
+ export { OblienClient } from './src/client.js';
7
+ export { OblienChat, ChatSession } from './src/chat/index.js';
8
+ export {
9
+ GuestManager,
10
+ NodeCacheStorage,
11
+ InMemoryStorage,
12
+ RedisStorage
13
+ } from './src/utils/guest-manager.js';
14
+
15
+ export default {
16
+ OblienClient,
17
+ OblienChat,
18
+ ChatSession,
19
+ GuestManager,
20
+ NodeCacheStorage,
21
+ InMemoryStorage,
22
+ RedisStorage,
23
+ };