oblien 1.3.0 → 2.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.
Files changed (187) hide show
  1. package/dist/client.d.ts +31 -0
  2. package/dist/client.d.ts.map +1 -0
  3. package/dist/client.js +33 -0
  4. package/dist/client.js.map +1 -0
  5. package/dist/error.d.ts +29 -0
  6. package/dist/error.d.ts.map +1 -0
  7. package/dist/error.js +52 -0
  8. package/dist/error.js.map +1 -0
  9. package/dist/http.d.ts +20 -0
  10. package/dist/http.d.ts.map +1 -0
  11. package/dist/http.js +108 -0
  12. package/dist/http.js.map +1 -0
  13. package/dist/index.d.ts +8 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +10 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/resources/api-access.d.ts +21 -0
  18. package/dist/resources/api-access.d.ts.map +1 -0
  19. package/dist/resources/api-access.js +32 -0
  20. package/dist/resources/api-access.js.map +1 -0
  21. package/dist/resources/base.d.ts +17 -0
  22. package/dist/resources/base.d.ts.map +1 -0
  23. package/dist/resources/base.js +21 -0
  24. package/dist/resources/base.js.map +1 -0
  25. package/dist/resources/images.d.ts +11 -0
  26. package/dist/resources/images.d.ts.map +1 -0
  27. package/dist/resources/images.js +16 -0
  28. package/dist/resources/images.js.map +1 -0
  29. package/dist/resources/lifecycle.d.ts +23 -0
  30. package/dist/resources/lifecycle.d.ts.map +1 -0
  31. package/dist/resources/lifecycle.js +32 -0
  32. package/dist/resources/lifecycle.js.map +1 -0
  33. package/dist/resources/logs.d.ts +25 -0
  34. package/dist/resources/logs.d.ts.map +1 -0
  35. package/dist/resources/logs.js +51 -0
  36. package/dist/resources/logs.js.map +1 -0
  37. package/dist/resources/metadata.d.ts +15 -0
  38. package/dist/resources/metadata.d.ts.map +1 -0
  39. package/dist/resources/metadata.js +20 -0
  40. package/dist/resources/metadata.js.map +1 -0
  41. package/dist/resources/metrics.d.ts +17 -0
  42. package/dist/resources/metrics.d.ts.map +1 -0
  43. package/dist/resources/metrics.js +27 -0
  44. package/dist/resources/metrics.js.map +1 -0
  45. package/dist/resources/network.d.ts +17 -0
  46. package/dist/resources/network.d.ts.map +1 -0
  47. package/dist/resources/network.js +20 -0
  48. package/dist/resources/network.js.map +1 -0
  49. package/dist/resources/public-access.d.ts +15 -0
  50. package/dist/resources/public-access.d.ts.map +1 -0
  51. package/dist/resources/public-access.js +21 -0
  52. package/dist/resources/public-access.js.map +1 -0
  53. package/dist/resources/resources.d.ts +15 -0
  54. package/dist/resources/resources.d.ts.map +1 -0
  55. package/dist/resources/resources.js +20 -0
  56. package/dist/resources/resources.js.map +1 -0
  57. package/dist/resources/snapshots.d.ts +27 -0
  58. package/dist/resources/snapshots.d.ts.map +1 -0
  59. package/dist/resources/snapshots.js +45 -0
  60. package/dist/resources/snapshots.js.map +1 -0
  61. package/dist/resources/ssh.d.ts +19 -0
  62. package/dist/resources/ssh.d.ts.map +1 -0
  63. package/dist/resources/ssh.js +28 -0
  64. package/dist/resources/ssh.js.map +1 -0
  65. package/dist/resources/usage.d.ts +25 -0
  66. package/dist/resources/usage.d.ts.map +1 -0
  67. package/dist/resources/usage.js +44 -0
  68. package/dist/resources/usage.js.map +1 -0
  69. package/dist/resources/workloads.d.ts +39 -0
  70. package/dist/resources/workloads.d.ts.map +1 -0
  71. package/dist/resources/workloads.js +83 -0
  72. package/dist/resources/workloads.js.map +1 -0
  73. package/dist/runtime/exec.d.ts +71 -0
  74. package/dist/runtime/exec.d.ts.map +1 -0
  75. package/dist/runtime/exec.js +163 -0
  76. package/dist/runtime/exec.js.map +1 -0
  77. package/dist/runtime/files.d.ts +39 -0
  78. package/dist/runtime/files.d.ts.map +1 -0
  79. package/dist/runtime/files.js +143 -0
  80. package/dist/runtime/files.js.map +1 -0
  81. package/dist/runtime/search.d.ts +23 -0
  82. package/dist/runtime/search.d.ts.map +1 -0
  83. package/dist/runtime/search.js +65 -0
  84. package/dist/runtime/search.js.map +1 -0
  85. package/dist/runtime/terminal.d.ts +29 -0
  86. package/dist/runtime/terminal.d.ts.map +1 -0
  87. package/dist/runtime/terminal.js +58 -0
  88. package/dist/runtime/terminal.js.map +1 -0
  89. package/dist/runtime/watcher.d.ts +27 -0
  90. package/dist/runtime/watcher.d.ts.map +1 -0
  91. package/dist/runtime/watcher.js +53 -0
  92. package/dist/runtime/watcher.js.map +1 -0
  93. package/dist/runtime/ws.d.ts +92 -0
  94. package/dist/runtime/ws.d.ts.map +1 -0
  95. package/dist/runtime/ws.js +228 -0
  96. package/dist/runtime/ws.js.map +1 -0
  97. package/dist/runtime-http.d.ts +35 -0
  98. package/dist/runtime-http.d.ts.map +1 -0
  99. package/dist/runtime-http.js +99 -0
  100. package/dist/runtime-http.js.map +1 -0
  101. package/dist/runtime.d.ts +77 -0
  102. package/dist/runtime.d.ts.map +1 -0
  103. package/dist/runtime.js +97 -0
  104. package/dist/runtime.js.map +1 -0
  105. package/dist/types/client.d.ts +7 -0
  106. package/dist/types/client.d.ts.map +1 -0
  107. package/dist/types/client.js +3 -0
  108. package/dist/types/client.js.map +1 -0
  109. package/dist/types/common.d.ts +13 -0
  110. package/dist/types/common.d.ts.map +1 -0
  111. package/dist/types/common.js +3 -0
  112. package/dist/types/common.js.map +1 -0
  113. package/dist/types/index.d.ts +8 -0
  114. package/dist/types/index.d.ts.map +1 -0
  115. package/dist/types/index.js +2 -0
  116. package/dist/types/index.js.map +1 -0
  117. package/dist/types/network.d.ts +15 -0
  118. package/dist/types/network.d.ts.map +1 -0
  119. package/dist/types/network.js +3 -0
  120. package/dist/types/network.js.map +1 -0
  121. package/dist/types/resources.d.ts +10 -0
  122. package/dist/types/resources.d.ts.map +1 -0
  123. package/dist/types/resources.js +3 -0
  124. package/dist/types/resources.js.map +1 -0
  125. package/dist/types/runtime.d.ts +302 -0
  126. package/dist/types/runtime.d.ts.map +1 -0
  127. package/dist/types/runtime.js +3 -0
  128. package/dist/types/runtime.js.map +1 -0
  129. package/dist/types/workspace-resources.d.ts +186 -0
  130. package/dist/types/workspace-resources.d.ts.map +1 -0
  131. package/dist/types/workspace-resources.js +3 -0
  132. package/dist/types/workspace-resources.js.map +1 -0
  133. package/dist/types/workspace.d.ts +41 -0
  134. package/dist/types/workspace.d.ts.map +1 -0
  135. package/dist/types/workspace.js +3 -0
  136. package/dist/types/workspace.js.map +1 -0
  137. package/dist/workspace.d.ts +135 -0
  138. package/dist/workspace.d.ts.map +1 -0
  139. package/dist/workspace.js +194 -0
  140. package/dist/workspace.js.map +1 -0
  141. package/package.json +30 -69
  142. package/LICENSE +0 -21
  143. package/README.md +0 -574
  144. package/agents.js +0 -14
  145. package/browser.js +0 -6
  146. package/cdn.js +0 -6
  147. package/chat.js +0 -21
  148. package/credits.js +0 -11
  149. package/icons.js +0 -11
  150. package/index.d.ts +0 -986
  151. package/index.js +0 -63
  152. package/namespaces.js +0 -12
  153. package/sandbox.js +0 -12
  154. package/search.js +0 -11
  155. package/src/agents/agent.js +0 -229
  156. package/src/agents/index.js +0 -227
  157. package/src/agents/settings.js +0 -100
  158. package/src/agents/tools.js +0 -155
  159. package/src/browser/index.js +0 -474
  160. package/src/cdn/index.js +0 -769
  161. package/src/chat/index.js +0 -724
  162. package/src/chat/session.js +0 -93
  163. package/src/client.js +0 -175
  164. package/src/credits/index.js +0 -492
  165. package/src/icons/index.js +0 -185
  166. package/src/namespaces/index.js +0 -236
  167. package/src/namespaces/namespace.js +0 -274
  168. package/src/sandbox/core/api/base.js +0 -89
  169. package/src/sandbox/core/api/database.js +0 -340
  170. package/src/sandbox/core/api/files.js +0 -141
  171. package/src/sandbox/core/api/git.js +0 -174
  172. package/src/sandbox/core/api/search.js +0 -29
  173. package/src/sandbox/core/api/snapshots.js +0 -132
  174. package/src/sandbox/core/api/terminal.js +0 -20
  175. package/src/sandbox/core/auth.js +0 -256
  176. package/src/sandbox/core/client.js +0 -197
  177. package/src/sandbox/core/index.js +0 -22
  178. package/src/sandbox/core/managers/terminal.js +0 -453
  179. package/src/sandbox/core/managers/watcher.js +0 -197
  180. package/src/sandbox/core/types.js +0 -92
  181. package/src/sandbox/core/utils/http.js +0 -89
  182. package/src/sandbox/core/websocket/connection.js +0 -479
  183. package/src/sandbox/index.d.ts +0 -542
  184. package/src/sandbox/index.js +0 -234
  185. package/src/sandbox/sandbox.js +0 -313
  186. package/src/search/index.js +0 -206
  187. package/src/utils/guest-manager.js +0 -454
package/src/chat/index.js DELETED
@@ -1,724 +0,0 @@
1
- /**
2
- * Chat Module (Server-Side Session Management)
3
- * Creates sessions and returns tokens for client-side chat
4
- */
5
-
6
- import { OblienClient } from '../client.js';
7
- import { ChatSession } from './session.js';
8
- import { GuestManager } from '../utils/guest-manager.js';
9
-
10
- export class OblienChat {
11
- /**
12
- * @param {import('../client.js').OblienClient|Object} clientOrConfig - Oblien client instance or { clientId, clientSecret }
13
- * @param {Object} [options] - Configuration options
14
- * @param {Object} [options.guestManager] - Custom guest manager instance
15
- * @param {Object} [options.guestStorage] - Storage adapter for guest manager
16
- * @param {number} [options.guestTTL] - Guest session TTL in seconds
17
- */
18
- constructor(clientOrConfig, options = {}) {
19
- if (!clientOrConfig) {
20
- throw new Error('Either provide OblienClient instance or { clientId, clientSecret }');
21
- }
22
-
23
- // If it's already a client instance
24
- if (clientOrConfig.clientId && clientOrConfig.clientSecret && typeof clientOrConfig.get === 'function') {
25
- this.client = clientOrConfig;
26
- }
27
- // If credentials provided, create client
28
- else if (clientOrConfig.clientId && clientOrConfig.clientSecret) {
29
- // Extract options if passed in clientOrConfig
30
- if (clientOrConfig.guestManager || clientOrConfig.guestStorage || clientOrConfig.guestTTL) {
31
- options = {
32
- guestManager: clientOrConfig.guestManager,
33
- guestStorage: clientOrConfig.guestStorage,
34
- guestTTL: clientOrConfig.guestTTL,
35
- ...options
36
- };
37
- }
38
- this.client = new OblienClient(clientOrConfig);
39
- }
40
- else {
41
- throw new Error('Either provide OblienClient instance or { clientId, clientSecret }');
42
- }
43
-
44
- // Initialize guest manager if not provided
45
- this.guestManager = options.guestManager || new GuestManager({
46
- storage: options.guestStorage,
47
- ttl: options.guestTTL,
48
- });
49
- }
50
-
51
- /**
52
- * Create a new session and return token for client
53
- * @param {Object} options - Session options
54
- * @param {string} options.agentId - Agent ID to chat with
55
- * @param {string} [options.workflowId] - Workflow ID (if using workflow)
56
- * @param {Object} [options.workspace] - Workspace configuration
57
- * @param {string} [options.endUserId] - End user ID (for client's end users)
58
- * @param {string} [options.namespace] - Guest namespace for rate limiting
59
- * @param {boolean} [options.isGuest] - Is this a guest session
60
- * @param {string} [options.ipAddress] - IP address of the user
61
- * @param {string} [options.userAgent] - User agent of the user
62
- * @param {string} [options.fingerprint] - Fingerprint of the user
63
- * @returns {Promise<Object>} Session data with token
64
- */
65
- async createSession(options) {
66
- const session = new ChatSession({
67
- client: this.client,
68
- });
69
-
70
- return await session.create(options);
71
- }
72
-
73
- /**
74
- * Create a guest session based on IP and fingerprint (dual-layer identification)
75
- *
76
- * Namespace handling:
77
- * - If `namespace` is provided: Uses it as the session namespace
78
- * - If `namespace` is NOT provided: Uses guest's auto-generated namespace (based on IP)
79
- * - `endUserId`: Optional identifier for your end user (tracked separately)
80
- *
81
- * @param {Object} options - Guest session options
82
- * @param {string} options.ip - Client IP address (required)
83
- * @param {string} [options.fingerprint] - Client fingerprint for identification
84
- * @param {string} options.agentId - Agent ID to chat with
85
- * @param {string} [options.workflowId] - Workflow ID
86
- * @param {string} [options.namespace] - Custom namespace (e.g., 'my-app-guests'). If not provided, uses auto-generated guest namespace
87
- * @param {string} [options.endUserId] - Your end user's ID (e.g., from your database)
88
- * @param {Object} [options.metadata] - Additional guest metadata (userAgent, etc.)
89
- * @param {Object} [options.workspace] - Workspace configuration
90
- * @returns {Promise<Object>} Session data with token and guest info
91
- *
92
- * @example
93
- * // Simple guest session (auto namespace)
94
- * await chat.createGuestSession({
95
- * ip: '1.2.3.4',
96
- * agentId: 'my-agent-id'
97
- * });
98
- *
99
- * @example
100
- * // With custom namespace and end user ID
101
- * await chat.createGuestSession({
102
- * ip: '1.2.3.4',
103
- * fingerprint: 'abc123',
104
- * agentId: 'my-agent-id',
105
- * namespace: 'my-app-guests',
106
- * endUserId: 'user_12345'
107
- * });
108
- */
109
- async createGuestSession(options) {
110
- const {
111
- ip,
112
- fingerprint,
113
- agentId,
114
- workflowId,
115
- namespace,
116
- endUserId,
117
- metadata = {},
118
- workspace,
119
- useLocalStorage = false
120
- } = options;
121
-
122
- if (!ip) {
123
- throw new Error('IP address is required for guest sessions');
124
- }
125
-
126
- if (!agentId) {
127
- throw new Error('Agent ID is required for guest sessions');
128
- }
129
-
130
- // Create session via API (API will handle guest creation in Oblien database)
131
- const session = new ChatSession({
132
- client: this.client,
133
- });
134
-
135
- const sessionData = await session.create({
136
- agentId,
137
- workflowId,
138
- workspace,
139
- isGuest: true,
140
- namespace: namespace,
141
- ipAddress: ip,
142
- userAgent: metadata.userAgent,
143
- fingerprint: fingerprint,
144
- endUserId: endUserId,
145
- });
146
-
147
- // If using local storage, also store guest locally for caching
148
- if (useLocalStorage) {
149
- const guest = await this.guestManager.getOrCreateGuest(ip, fingerprint, {
150
- ...metadata,
151
- fingerprint,
152
- ip,
153
- });
154
-
155
- await this.guestManager.addSession(guest.id, sessionData.sessionId);
156
- }
157
-
158
- return sessionData
159
- }
160
-
161
- /**
162
- * Get guest sessions by namespace, IP, or fingerprint from Oblien API (server-side)
163
- * @param {string|Object} options - Namespace string or query options object
164
- * @param {string} [options.ip] - IP address
165
- * @param {string} [options.fingerprint] - Client fingerprint
166
- * @param {string} [options.namespace] - Guest namespace
167
- * @returns {Promise<Object|null>} Guest object with sessions array or null
168
- *
169
- * @example
170
- * // Get by namespace (string)
171
- * const guest = await chat.getGuest('guest-1-2-3-4');
172
- *
173
- * @example
174
- * // Get by IP and fingerprint (object)
175
- * const guest = await chat.getGuest({ ip: '1.2.3.4', fingerprint: 'abc123' });
176
- *
177
- * @example
178
- * // Get by namespace (object)
179
- * const guest = await chat.getGuest({ namespace: 'guest-1-2-3-4' });
180
- */
181
- async getGuest(options, getSessions = false) {
182
- // Handle string usage: getGuest('namespace')
183
- if (typeof options === 'string') {
184
- options = { namespace: options };
185
- }
186
-
187
- const agentId = options.agentId || options.agent_id;
188
- const sessionId = options.sessionId || options.session_id;
189
- const guestId = options.guestId || options.namespace;
190
- const ip = options.ip;
191
- const fingerprint = options.fingerprint;
192
-
193
- if (!agentId && !sessionId && !guestId) {
194
- throw new Error('Either agentId, sessionId, or guestId is required');
195
- }
196
-
197
- try {
198
- const response = await this.client.post(getSessions ? `ai/guest/sessions` : `ai/guest/info`, {
199
- ip,
200
- fingerprint,
201
- namespace: guestId,
202
- agent_id: agentId,
203
- session_id: sessionId,
204
- });
205
- return response;
206
- } catch (error) {
207
- // Return null if guest not found (404)
208
- if (error.message?.includes('not_found') || error.message?.includes('404')) {
209
- return null;
210
- }
211
- throw error;
212
- }
213
- }
214
-
215
- /**
216
- * Get guest from local cache/storage (for internal use)
217
- * @param {string} ip - IP address
218
- * @param {string} [fingerprint] - Client fingerprint (optional)
219
- * @returns {Promise<Object|null>} Guest object from cache or null
220
- */
221
- async getGuestFromCache(ip, fingerprint = null) {
222
- // Try fingerprint first if provided
223
- if (fingerprint) {
224
- const guestIdByFingerprint = await this.guestManager.storage.get(`fingerprint:${fingerprint}`);
225
- if (guestIdByFingerprint) {
226
- const guest = await this.guestManager.getGuest(guestIdByFingerprint);
227
- if (guest) return guest;
228
- }
229
- }
230
-
231
- // Fallback to IP
232
- if (ip) {
233
- const guestIdByIp = await this.guestManager.storage.get(`ip:${ip}`);
234
- if (guestIdByIp) {
235
- const guest = await this.guestManager.getGuest(guestIdByIp);
236
- if (guest) return guest;
237
- }
238
-
239
- // Fallback to old method (generate guest ID from IP)
240
- const fallbackGuestId = this.guestManager.generateGuestId(ip);
241
- return await this.guestManager.getGuest(fallbackGuestId);
242
- }
243
-
244
- return null;
245
- }
246
-
247
- /**
248
- * Send a message in a chat session
249
- * Hybrid mode: Works with session token OR client credentials
250
- *
251
- * @param {Object} options - Send options
252
- * @param {string} [options.token] - Session token (optional, uses client credentials if not provided)
253
- * @param {string} options.message - Message to send
254
- * @param {string} [options.uploadId] - Upload ID for attached files
255
- * @param {Array} [options.files] - File attachments (alternative to uploadId)
256
- * @param {boolean} [options.stream] - Enable streaming response
257
- * @param {Function} [options.onChunk] - Callback for streaming chunks (data) => void
258
- * @param {Function} [options.onError] - Callback for errors (error) => void
259
- * @param {Function} [options.onComplete] - Callback when stream completes () => void
260
- * @param {Object} [options.metadata] - Additional metadata
261
- * @returns {Promise<Object>} Response data
262
- */
263
- async send(options = {}) {
264
- const {
265
- token,
266
- message,
267
- uploadId,
268
- files,
269
- stream = false,
270
- onChunk,
271
- onError,
272
- onComplete,
273
- metadata = {}
274
- } = options;
275
-
276
- if (!message || !message.trim()) {
277
- throw new Error('Message is required');
278
- }
279
-
280
- const payload = {
281
- message,
282
- stream,
283
- ...metadata,
284
- };
285
-
286
- if (uploadId) {
287
- payload.upload_id = uploadId;
288
- }
289
-
290
- if (files) {
291
- payload.files = files;
292
- }
293
-
294
- // Build headers - use token if provided, otherwise use client credentials
295
- const headers = {
296
- ...this.client.getAuthHeaders(),
297
- 'Content-Type': 'application/json',
298
- };
299
-
300
- if (token) {
301
- headers['Authorization'] = `Bearer ${token}`;
302
- }
303
-
304
- const url = this.client._buildURL('ai/chat/send');
305
-
306
- if (stream) {
307
- // Handle streaming response
308
- const response = await fetch(url, {
309
- method: 'POST',
310
- headers,
311
- body: JSON.stringify(payload),
312
- });
313
-
314
- if (!response.ok) {
315
- const error = await response.text();
316
- throw new Error(error || `API error: ${response.status}`);
317
- }
318
-
319
- // Process SSE stream
320
- const reader = response.body.getReader();
321
- const decoder = new TextDecoder();
322
- let buffer = '';
323
-
324
- try {
325
- while (true) {
326
- const { done, value } = await reader.read();
327
-
328
- if (done) {
329
- if (onComplete) onComplete();
330
- break;
331
- }
332
-
333
- buffer += decoder.decode(value, { stream: true });
334
- const lines = buffer.split('\n');
335
- buffer = lines.pop() || '';
336
-
337
- for (const line of lines) {
338
- if (line.trim() === '') continue;
339
-
340
- try {
341
- const data = JSON.parse(line);
342
- if (onChunk) onChunk(data);
343
- } catch (e) {
344
- // Skip non-JSON lines (SSE format)
345
- if (line.startsWith('data: ')) {
346
- try {
347
- const jsonStr = line.substring(6);
348
- const data = JSON.parse(jsonStr);
349
- if (onChunk) onChunk(data);
350
- } catch (parseError) {
351
- console.warn('Failed to parse chunk:', line);
352
- }
353
- }
354
- }
355
- }
356
- }
357
-
358
- return { success: true, stream: true };
359
- } catch (error) {
360
- if (onError) onError(error);
361
- throw error;
362
- }
363
- } else {
364
- // Regular non-streaming request
365
- const response = await fetch(url, {
366
- method: 'POST',
367
- headers,
368
- body: JSON.stringify(payload),
369
- });
370
-
371
- if (!response.ok) {
372
- const error = await response.json().catch(() => ({ message: response.statusText }));
373
- throw new Error(error.message || error.error || `API error: ${response.status}`);
374
- }
375
-
376
- return await response.json();
377
- }
378
- }
379
-
380
- /**
381
- * Upload files for a chat session
382
- * Hybrid mode: Works with session token OR client credentials
383
- *
384
- * @param {Object} options - Upload options
385
- * @param {string} [options.token] - Session token (optional, uses client credentials if not provided)
386
- * @param {Array|Object} options.files - Files to upload
387
- * @param {Object} [options.metadata] - Additional metadata
388
- * @returns {Promise<Object>} Upload result with uploadId
389
- */
390
- async upload(options = {}) {
391
- const { token, files, metadata } = options;
392
-
393
- if (!files || (Array.isArray(files) && files.length === 0)) {
394
- throw new Error('Files are required');
395
- }
396
-
397
- const formData = new FormData();
398
-
399
- // Handle both single file and array of files
400
- const fileArray = Array.isArray(files) ? files : [files];
401
-
402
- fileArray.forEach((file, index) => {
403
- if (file instanceof File || file instanceof Blob) {
404
- formData.append('files', file);
405
- } else if (file.path && file.buffer) {
406
- // Node.js file object
407
- formData.append('files', file.buffer, file.originalname || file.path);
408
- } else {
409
- throw new Error(`Invalid file at index ${index}`);
410
- }
411
- });
412
-
413
- // Add any additional options
414
- if (metadata) {
415
- formData.append('metadata', JSON.stringify(metadata));
416
- }
417
-
418
- // Build headers - use token if provided, otherwise use client credentials
419
- const headers = {
420
- ...this.client.getAuthHeaders(),
421
- };
422
-
423
- if (token) {
424
- headers['Authorization'] = `Bearer ${token}`;
425
- }
426
-
427
- // Remove Content-Type for FormData (browser will set it with boundary)
428
- delete headers['Content-Type'];
429
-
430
- const url = this.client._buildURL('ai/chat/upload');
431
-
432
- const response = await fetch(url, {
433
- method: 'POST',
434
- headers,
435
- body: formData,
436
- });
437
-
438
- if (!response.ok) {
439
- const error = await response.json().catch(() => ({ message: response.statusText }));
440
- throw new Error(error.message || error.error || `API error: ${response.status}`);
441
- }
442
-
443
- return await response.json();
444
- }
445
-
446
- /**
447
- * Get session info (server-side)
448
- * @param {string} sessionId - Session ID
449
- * @returns {Promise<Object>} Session details
450
- */
451
- async getSession(sessionId) {
452
- if (!sessionId) {
453
- throw new Error('Session ID is required');
454
- }
455
- return await this.client.get(`ai/session/${sessionId}`);
456
- }
457
-
458
- /**
459
- * Create a session token for client-side access (server-side)
460
- * @param {string} sessionId - Session ID
461
- * @returns {Promise<Object>} Token data (accessToken, refreshToken)
462
- */
463
- async createSessionToken(sessionId) {
464
- if (!sessionId) {
465
- throw new Error('Session ID is required');
466
- }
467
- return await this.client.post(`ai/session/${sessionId}/token/create`);
468
- }
469
-
470
- /**
471
- * Revoke a session token (server-side)
472
- * @param {string} sessionId - Session ID
473
- * @returns {Promise<Object>} Revocation result
474
- */
475
- async revokeSessionToken(sessionId) {
476
- if (!sessionId) {
477
- throw new Error('Session ID is required');
478
- }
479
- return await this.client.post(`ai/session/${sessionId}/token/revoke`);
480
- }
481
-
482
- /**
483
- * Get session history by session ID (server-side)
484
- * @param {string} sessionId - Session ID
485
- * @param {Object} [options] - Query options
486
- * @param {number} [options.limit] - Number of messages (max 100)
487
- * @param {number} [options.offset] - Offset for pagination
488
- * @returns {Promise<Object>} Session history with messages
489
- */
490
- async getSessionHistory(sessionId, options = {}) {
491
- if (!sessionId) {
492
- throw new Error('Session ID is required');
493
- }
494
-
495
- const params = new URLSearchParams();
496
- if (options.limit) params.append('limit', Math.min(options.limit, 100).toString());
497
- if (options.offset) params.append('offset', Math.max(options.offset, 0).toString());
498
-
499
- const url = `ai/session/${sessionId}/history${params.toString() ? `?${params.toString()}` : ''}`;
500
- return await this.client.get(url);
501
- }
502
-
503
- /**
504
- * Ban a user from a session (server-side)
505
- * @param {string} sessionId - Session ID
506
- * @param {Object} [options] - Ban options
507
- * @param {string} [options.reason] - Reason for ban
508
- * @returns {Promise<Object>} Ban result
509
- */
510
- async banUser(sessionId, options = {}) {
511
- if (!sessionId) {
512
- throw new Error('Session ID is required');
513
- }
514
- return await this.client.post(`ai/session/${sessionId}/ban`, options);
515
- }
516
-
517
- /**
518
- * Unban a user from a session (server-side)
519
- * @param {string} sessionId - Session ID
520
- * @returns {Promise<Object>} Unban result
521
- */
522
- async unbanUser(sessionId) {
523
- if (!sessionId) {
524
- throw new Error('Session ID is required');
525
- }
526
- return await this.client.post(`ai/session/${sessionId}/unban`);
527
- }
528
-
529
- /**
530
- * Lock or unlock a session (server-side)
531
- * @param {string} sessionId - Session ID
532
- * @param {Object} [options] - Lock options
533
- * @param {boolean} [options.locked] - Lock state (true to lock, false to unlock)
534
- * @returns {Promise<Object>} Lock result
535
- */
536
- async lockSession(sessionId, options = {}) {
537
- if (!sessionId) {
538
- throw new Error('Session ID is required');
539
- }
540
- return await this.client.post(`ai/session/${sessionId}/lock`, options);
541
- }
542
-
543
- /**
544
- * List sessions (server-side)
545
- * @param {Object} [options] - Query options
546
- * @param {string} [options.namespace] - Filter by namespace
547
- * @param {string} [options.agentId] - Filter by agent ID
548
- * @param {string} [options.endUserId] - Filter by end user ID
549
- * @param {number} [options.limit] - Number of results (max 100)
550
- * @param {number} [options.offset] - Offset for pagination
551
- * @param {string} [options.search] - Search in title and user ID
552
- * @param {string} [options.sortBy] - Sort by 'time' or 'tokens'
553
- * @param {string} [options.sortOrder] - 'asc' or 'desc'
554
- * @param {boolean} [options.includeStats] - Include message count and tokens
555
- * @param {boolean} [options.includeGuests] - Include guest information
556
- * @returns {Promise<Array>} Array of sessions
557
- */
558
- async listSessions(options = {}) {
559
- const session = new ChatSession({
560
- client: this.client,
561
- });
562
-
563
- return await session.list(options);
564
- }
565
-
566
- /**
567
- * Delete a session (server-side)
568
- * @param {string} sessionId - Session ID to delete
569
- * @returns {Promise<Object>} Deletion result
570
- */
571
- async deleteSession(sessionId) {
572
- if (!sessionId) {
573
- throw new Error('Session ID is required');
574
- }
575
- return await this.client.delete(`ai/session/${sessionId}`);
576
- }
577
-
578
- /**
579
- * Get all active guests (admin/monitoring)
580
- * @returns {Promise<Array>} Array of guest objects
581
- */
582
- async getAllGuests() {
583
- return await this.guestManager.getAllGuests();
584
- }
585
-
586
- /**
587
- * Clean up expired guests
588
- * @returns {Promise<number>} Number of cleaned guests
589
- */
590
- async cleanupGuests() {
591
- return await this.guestManager.cleanup();
592
- }
593
-
594
- /**
595
- * Get guest usage information (server-side)
596
- * @param {string} namespace - Guest namespace
597
- * @param {string} [agentId] - Agent ID (optional)
598
- * @returns {Promise<Object>} Usage information for the guest
599
- */
600
- async getGuestUsage(namespace, agentId = null) {
601
- if (!namespace) {
602
- throw new Error('Namespace is required');
603
- }
604
-
605
- const params = new URLSearchParams();
606
- params.append('namespace', namespace);
607
- if (agentId) params.append('agent_id', agentId);
608
-
609
- return await this.client.get(`ai/guest/usage?${params.toString()}`);
610
- }
611
-
612
- /**
613
- * Get cache statistics (admin/monitoring)
614
- * @returns {Promise<Object>} Cache statistics
615
- */
616
- async getCacheStatistics() {
617
- const data = await this.client.get('ai/guest/cache-stats');
618
- return data;
619
- }
620
-
621
- /**
622
- * Refresh session token (client-side)
623
- * Uses refresh token to get new access token
624
- *
625
- * @param {string} refreshToken - Refresh token from session
626
- * @returns {Promise<Object>} New tokens
627
- */
628
- async refreshToken(refreshToken) {
629
- if (!refreshToken) {
630
- throw new Error('Refresh token is required');
631
- }
632
-
633
- const url = this.client._buildURL('ai/session/token/refresh');
634
- const response = await fetch(url, {
635
- method: 'POST',
636
- headers: {
637
- 'Authorization': `Bearer ${refreshToken}`,
638
- 'Content-Type': 'application/json',
639
- },
640
- });
641
-
642
- if (!response.ok) {
643
- const error = await response.json().catch(() => ({ message: response.statusText }));
644
- throw new Error(error.message || error.error || `API error: ${response.status}`);
645
- }
646
-
647
- return await response.json();
648
- }
649
-
650
- /**
651
- * Get chat history (client-side)
652
- * Uses session token to get chat history
653
- *
654
- * @param {Object} options - History options
655
- * @param {string} options.token - Session token (required for client-side)
656
- * @param {string} [options.namespace] - Namespace filter
657
- * @param {number} [options.limit] - Number of messages (max 50)
658
- * @param {number} [options.offset] - Offset for pagination
659
- * @returns {Promise<Object>} Chat history with messages
660
- */
661
- async getHistory(options = {}) {
662
- const { token, namespace, limit = 50, offset = 0 } = options;
663
-
664
- if (!token) {
665
- throw new Error('Session token is required for client-side history');
666
- }
667
-
668
- const params = new URLSearchParams();
669
- if (namespace) params.append('namespace', namespace);
670
- params.append('limit', Math.min(limit, 50).toString());
671
- params.append('offset', Math.max(offset, 0).toString());
672
-
673
- const url = `${this.client._buildURL('ai/session/history')}?${params.toString()}`;
674
- const response = await fetch(url, {
675
- method: 'GET',
676
- headers: {
677
- 'Authorization': `Bearer ${token}`,
678
- 'Content-Type': 'application/json',
679
- },
680
- });
681
-
682
- if (!response.ok) {
683
- const error = await response.json().catch(() => ({ message: response.statusText }));
684
- throw new Error(error.message || error.error || `API error: ${response.status}`);
685
- }
686
-
687
- return await response.json();
688
- }
689
-
690
- /**
691
- * Prepare session (client-side)
692
- * Prepares session for app/container usage
693
- *
694
- * @param {Object} options - Prepare options
695
- * @param {string} options.token - Session token (required for client-side)
696
- * @returns {Promise<Object>} Preparation result
697
- */
698
- async prepareSession(options = {}) {
699
- const { token } = options;
700
-
701
- if (!token) {
702
- throw new Error('Session token is required for client-side prepare');
703
- }
704
-
705
- const url = this.client._buildURL('ai/session/prepare');
706
- const response = await fetch(url, {
707
- method: 'POST',
708
- headers: {
709
- 'Authorization': `Bearer ${token}`,
710
- 'Content-Type': 'application/json',
711
- },
712
- });
713
-
714
- if (!response.ok) {
715
- const error = await response.json().catch(() => ({ message: response.statusText }));
716
- throw new Error(error.message || error.error || `API error: ${response.status}`);
717
- }
718
-
719
- return await response.json();
720
- }
721
- }
722
-
723
- export { ChatSession } from './session.js';
724
- export default OblienChat;