@aliyun-rds/rag-agent-sdk 0.1.1

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/dist/index.mjs ADDED
@@ -0,0 +1,1546 @@
1
+ // src/errors.ts
2
+ var RagAgentError = class extends Error {
3
+ constructor(message, details) {
4
+ super(message);
5
+ this.name = "RagAgentError";
6
+ this.statusCode = details?.statusCode;
7
+ this.response = details?.response;
8
+ this.errorCode = details?.errorCode;
9
+ if (typeof Error.captureStackTrace === "function") {
10
+ Error.captureStackTrace(this, this.constructor);
11
+ }
12
+ }
13
+ toJSON() {
14
+ return {
15
+ message: this.message,
16
+ statusCode: this.statusCode,
17
+ response: this.response,
18
+ errorCode: this.errorCode
19
+ };
20
+ }
21
+ };
22
+ var AuthenticationError = class extends RagAgentError {
23
+ constructor(message = "Authentication failed", response) {
24
+ super(message, { statusCode: 401, response });
25
+ this.name = "AuthenticationError";
26
+ }
27
+ };
28
+ var AuthorizationError = class extends RagAgentError {
29
+ constructor(message = "Permission denied", response) {
30
+ super(message, { statusCode: 403, response });
31
+ this.name = "AuthorizationError";
32
+ }
33
+ };
34
+ var NotFoundError = class extends RagAgentError {
35
+ constructor(message = "Resource not found", options) {
36
+ super(message, { statusCode: 404, response: options?.response });
37
+ this.name = "NotFoundError";
38
+ this.resourceType = options?.resourceType;
39
+ this.resourceId = options?.resourceId;
40
+ }
41
+ };
42
+ var DatasetNotFoundError = class extends NotFoundError {
43
+ constructor(datasetId, message) {
44
+ super(message ?? `Dataset not found: ${datasetId}`, {
45
+ resourceType: "dataset",
46
+ resourceId: datasetId
47
+ });
48
+ this.name = "DatasetNotFoundError";
49
+ this.datasetId = datasetId;
50
+ }
51
+ };
52
+ var DocumentNotFoundError = class extends NotFoundError {
53
+ constructor(docId, datasetId, message) {
54
+ super(message ?? `Document not found: ${docId}`, {
55
+ resourceType: "document",
56
+ resourceId: docId
57
+ });
58
+ this.name = "DocumentNotFoundError";
59
+ this.docId = docId;
60
+ this.datasetId = datasetId;
61
+ }
62
+ };
63
+ var ValidationError = class extends RagAgentError {
64
+ constructor(message = "Validation error", options) {
65
+ super(message, { statusCode: 400, response: options?.response });
66
+ this.name = "ValidationError";
67
+ this.errors = options?.errors;
68
+ }
69
+ };
70
+ var RateLimitError = class extends RagAgentError {
71
+ constructor(message = "Rate limit exceeded", options) {
72
+ super(message, { statusCode: 429, response: options?.response });
73
+ this.name = "RateLimitError";
74
+ this.retryAfter = options?.retryAfter;
75
+ }
76
+ };
77
+ var ServerError = class extends RagAgentError {
78
+ constructor(message = "Internal server error", statusCode = 500, response) {
79
+ super(message, { statusCode, response });
80
+ this.name = "ServerError";
81
+ }
82
+ };
83
+ var ConnectionError = class extends RagAgentError {
84
+ constructor(message = "Failed to connect to server", originalError) {
85
+ super(message);
86
+ this.name = "ConnectionError";
87
+ this.originalError = originalError;
88
+ }
89
+ };
90
+ var TimeoutError = class extends RagAgentError {
91
+ constructor(message = "Request timed out", timeout) {
92
+ super(message);
93
+ this.name = "TimeoutError";
94
+ this.timeout = timeout;
95
+ }
96
+ };
97
+ function createErrorFromResponse(statusCode, data) {
98
+ const message = data.message || data.detail || JSON.stringify(data);
99
+ switch (statusCode) {
100
+ case 400:
101
+ return new ValidationError(message, { response: data });
102
+ case 401:
103
+ return new AuthenticationError(message, data);
104
+ case 403:
105
+ return new AuthorizationError(message, data);
106
+ case 404:
107
+ return new NotFoundError(message, { response: data });
108
+ case 429:
109
+ return new RateLimitError(message, { response: data });
110
+ default:
111
+ if (statusCode >= 500) {
112
+ return new ServerError(message, statusCode, data);
113
+ }
114
+ return new RagAgentError(message, { statusCode, response: data });
115
+ }
116
+ }
117
+
118
+ // src/http.ts
119
+ var HttpClient = class {
120
+ constructor(config) {
121
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
122
+ this.defaultHeaders = {
123
+ "Content-Type": "application/json",
124
+ ...config.headers
125
+ };
126
+ this.timeout = config.timeout ?? 3e4;
127
+ this.maxRetries = config.maxRetries ?? 3;
128
+ this.retryDelay = config.retryDelay ?? 1e3;
129
+ this.retryMultiplier = config.retryMultiplier ?? 2;
130
+ }
131
+ buildUrl(path, params) {
132
+ const url = path.startsWith("http") ? path : `${this.baseUrl}/${path.replace(/^\//, "")}`;
133
+ if (!params) return url;
134
+ const searchParams = new URLSearchParams();
135
+ for (const [key, value] of Object.entries(params)) {
136
+ if (value !== void 0) {
137
+ searchParams.append(key, String(value));
138
+ }
139
+ }
140
+ const queryString = searchParams.toString();
141
+ return queryString ? `${url}?${queryString}` : url;
142
+ }
143
+ async handleResponse(response) {
144
+ let data;
145
+ try {
146
+ const text = await response.text();
147
+ data = text ? JSON.parse(text) : {};
148
+ } catch {
149
+ data = { message: await response.text() };
150
+ }
151
+ if (response.ok) {
152
+ return data;
153
+ }
154
+ throw createErrorFromResponse(response.status, data);
155
+ }
156
+ isRetryable(error) {
157
+ if (error instanceof RateLimitError || error instanceof ServerError) {
158
+ return true;
159
+ }
160
+ if (error instanceof TypeError && error.message.includes("fetch")) {
161
+ return true;
162
+ }
163
+ return false;
164
+ }
165
+ async requestWithRetry(options) {
166
+ const url = this.buildUrl(options.path, options.params);
167
+ let lastError;
168
+ let delay = this.retryDelay;
169
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
170
+ try {
171
+ const controller = new AbortController();
172
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
173
+ const fetchOptions = {
174
+ method: options.method,
175
+ headers: {
176
+ ...this.defaultHeaders,
177
+ ...options.headers
178
+ },
179
+ signal: controller.signal
180
+ };
181
+ if (options.body !== void 0 && options.method !== "GET") {
182
+ fetchOptions.body = JSON.stringify(options.body);
183
+ }
184
+ const response = await fetch(url, fetchOptions);
185
+ clearTimeout(timeoutId);
186
+ return await this.handleResponse(response);
187
+ } catch (error) {
188
+ if (error instanceof Error && error.name === "AbortError") {
189
+ lastError = new TimeoutError("Request timed out", this.timeout);
190
+ } else if (error instanceof RagAgentError) {
191
+ if (!this.isRetryable(error) || attempt === this.maxRetries) {
192
+ throw error;
193
+ }
194
+ lastError = error;
195
+ if (error instanceof RateLimitError && error.retryAfter) {
196
+ delay = error.retryAfter * 1e3;
197
+ }
198
+ } else if (error instanceof TypeError) {
199
+ lastError = new ConnectionError(error.message, error);
200
+ } else {
201
+ throw error;
202
+ }
203
+ if (attempt < this.maxRetries) {
204
+ await this.sleep(delay);
205
+ delay *= this.retryMultiplier;
206
+ }
207
+ }
208
+ }
209
+ throw lastError ?? new RagAgentError("Request failed after retries");
210
+ }
211
+ sleep(ms) {
212
+ return new Promise((resolve) => setTimeout(resolve, ms));
213
+ }
214
+ async get(path, params, headers) {
215
+ return this.requestWithRetry({
216
+ method: "GET",
217
+ path,
218
+ params,
219
+ headers
220
+ });
221
+ }
222
+ async post(path, body, params, headers) {
223
+ return this.requestWithRetry({
224
+ method: "POST",
225
+ path,
226
+ body,
227
+ params,
228
+ headers
229
+ });
230
+ }
231
+ async put(path, body, headers) {
232
+ return this.requestWithRetry({
233
+ method: "PUT",
234
+ path,
235
+ body,
236
+ headers
237
+ });
238
+ }
239
+ async delete(path, params, headers) {
240
+ return this.requestWithRetry({
241
+ method: "DELETE",
242
+ path,
243
+ params,
244
+ headers
245
+ });
246
+ }
247
+ async *stream(path, body, headers) {
248
+ const url = this.buildUrl(path);
249
+ const response = await fetch(url, {
250
+ method: "POST",
251
+ headers: {
252
+ ...this.defaultHeaders,
253
+ ...headers
254
+ },
255
+ body: body ? JSON.stringify(body) : void 0
256
+ });
257
+ if (!response.ok) {
258
+ const data = await response.json().catch(() => ({}));
259
+ throw createErrorFromResponse(response.status, data);
260
+ }
261
+ const reader = response.body?.getReader();
262
+ if (!reader) {
263
+ throw new RagAgentError("Response body is not readable");
264
+ }
265
+ const decoder = new TextDecoder();
266
+ try {
267
+ while (true) {
268
+ const { done, value } = await reader.read();
269
+ if (done) break;
270
+ const text = decoder.decode(value, { stream: true });
271
+ const lines = text.split("\n").filter((line) => line.trim());
272
+ for (const line of lines) {
273
+ yield line;
274
+ }
275
+ }
276
+ } finally {
277
+ reader.releaseLock();
278
+ }
279
+ }
280
+ async uploadFile(path, file, filename, fieldName = "file", extraFields, headers) {
281
+ const url = this.buildUrl(path);
282
+ const formData = new FormData();
283
+ const blob = file instanceof ArrayBuffer ? new Blob([file]) : file;
284
+ formData.append(fieldName, blob, filename);
285
+ if (extraFields) {
286
+ for (const [key, value] of Object.entries(extraFields)) {
287
+ formData.append(key, value);
288
+ }
289
+ }
290
+ const uploadHeaders = { ...headers };
291
+ delete uploadHeaders["Content-Type"];
292
+ const response = await fetch(url, {
293
+ method: "POST",
294
+ headers: uploadHeaders,
295
+ body: formData
296
+ });
297
+ return this.handleResponse(response);
298
+ }
299
+ /**
300
+ * Update default headers
301
+ */
302
+ setHeaders(headers) {
303
+ Object.assign(this.defaultHeaders, headers);
304
+ }
305
+ };
306
+
307
+ // src/auth.ts
308
+ var AuthHandler = class {
309
+ constructor(config) {
310
+ this.config = {
311
+ apiKeyHeader: "X-API-Key",
312
+ ...config
313
+ };
314
+ }
315
+ /**
316
+ * Set HTTP client for login requests
317
+ */
318
+ setHttpClient(client) {
319
+ this.httpClient = client;
320
+ }
321
+ /**
322
+ * Check if any credentials are configured
323
+ */
324
+ hasCredentials() {
325
+ return !!(this.config.apiKey || this.config.jwtToken || this.config.supabaseServiceKey || this.config.supabaseAccessToken || this.config.username && this.config.password);
326
+ }
327
+ /**
328
+ * Get the active authentication method
329
+ */
330
+ getAuthMethod() {
331
+ if (this.config.apiKey) return "api_key";
332
+ if (this.config.supabaseServiceKey) return "supabase_service";
333
+ if (this.config.supabaseAnonKey && this.config.supabaseAccessToken) return "supabase_anon_jwt";
334
+ if (this.config.jwtToken) return "jwt_token";
335
+ if (this.config.username && this.config.password) return "password";
336
+ return null;
337
+ }
338
+ /**
339
+ * Get authentication headers for requests
340
+ */
341
+ async getHeaders() {
342
+ const headers = {};
343
+ const authMethod = this.getAuthMethod();
344
+ if (authMethod === "api_key") {
345
+ headers[this.config.apiKeyHeader] = this.config.apiKey;
346
+ return headers;
347
+ }
348
+ if (authMethod === "supabase_service") {
349
+ headers["apikey"] = this.config.supabaseServiceKey;
350
+ return headers;
351
+ }
352
+ if (authMethod === "supabase_anon_jwt") {
353
+ headers["apikey"] = this.config.supabaseAnonKey;
354
+ headers["Authorization"] = `Bearer ${this.config.supabaseAccessToken}`;
355
+ return headers;
356
+ }
357
+ const token = await this.getValidToken();
358
+ if (token) {
359
+ headers["Authorization"] = `Bearer ${token}`;
360
+ }
361
+ return headers;
362
+ }
363
+ /**
364
+ * Get a valid access token, refreshing if needed
365
+ */
366
+ async getValidToken() {
367
+ if (this.config.jwtToken) {
368
+ return this.config.jwtToken;
369
+ }
370
+ if (this.config.supabaseAccessToken) {
371
+ return this.config.supabaseAccessToken;
372
+ }
373
+ if (this.tokenInfo?.accessToken) {
374
+ if (this.isTokenValid()) {
375
+ return this.tokenInfo.accessToken;
376
+ }
377
+ if (this.tokenInfo.refreshToken) {
378
+ await this.refreshAccessToken();
379
+ if (this.tokenInfo?.accessToken) {
380
+ return this.tokenInfo.accessToken;
381
+ }
382
+ }
383
+ }
384
+ if (this.config.username && this.config.password) {
385
+ await this.login();
386
+ return this.tokenInfo?.accessToken ?? null;
387
+ }
388
+ return null;
389
+ }
390
+ /**
391
+ * Check if the current token is still valid
392
+ */
393
+ isTokenValid() {
394
+ if (!this.tokenInfo?.accessToken) {
395
+ return false;
396
+ }
397
+ if (!this.tokenInfo.expiresAt) {
398
+ return true;
399
+ }
400
+ const bufferMs = 5 * 60 * 1e3;
401
+ return (/* @__PURE__ */ new Date()).getTime() < this.tokenInfo.expiresAt.getTime() - bufferMs;
402
+ }
403
+ /**
404
+ * Login with username and password
405
+ */
406
+ async login() {
407
+ if (!this.httpClient) {
408
+ return;
409
+ }
410
+ try {
411
+ const response = await this.httpClient.post("/login", {
412
+ username: this.config.username,
413
+ password: this.config.password
414
+ });
415
+ const expiresIn = response.expires_in ?? 3600;
416
+ this.tokenInfo = {
417
+ accessToken: response.access_token,
418
+ expiresAt: new Date(Date.now() + expiresIn * 1e3),
419
+ refreshToken: response.refresh_token
420
+ };
421
+ } catch {
422
+ this.tokenInfo = void 0;
423
+ throw new Error("Login failed");
424
+ }
425
+ }
426
+ /**
427
+ * Refresh the access token using refresh token
428
+ */
429
+ async refreshAccessToken() {
430
+ if (!this.httpClient || !this.tokenInfo?.refreshToken) {
431
+ return;
432
+ }
433
+ try {
434
+ const response = await this.httpClient.post("/auth/refresh", {
435
+ refresh_token: this.tokenInfo.refreshToken
436
+ });
437
+ const expiresIn = response.expires_in ?? 3600;
438
+ this.tokenInfo = {
439
+ accessToken: response.access_token,
440
+ expiresAt: new Date(Date.now() + expiresIn * 1e3),
441
+ refreshToken: response.refresh_token ?? this.tokenInfo.refreshToken
442
+ };
443
+ } catch {
444
+ this.tokenInfo = void 0;
445
+ }
446
+ }
447
+ /**
448
+ * Clear authentication state
449
+ */
450
+ logout() {
451
+ this.tokenInfo = void 0;
452
+ }
453
+ /**
454
+ * Check if currently authenticated
455
+ */
456
+ isAuthenticated() {
457
+ return !!(this.config.apiKey || this.config.jwtToken || this.config.supabaseServiceKey || this.config.supabaseAccessToken || this.tokenInfo?.accessToken);
458
+ }
459
+ };
460
+
461
+ // src/datasets.ts
462
+ var DatasetsClient = class {
463
+ constructor(http) {
464
+ this.http = http;
465
+ }
466
+ /**
467
+ * Create a new dataset
468
+ */
469
+ async create(options) {
470
+ const response = await this.http.post("/datasets", options);
471
+ return "dataset" in response ? response.dataset : response;
472
+ }
473
+ /**
474
+ * Get dataset by ID
475
+ */
476
+ async get(datasetId) {
477
+ try {
478
+ const response = await this.http.get(`/datasets/${datasetId}`);
479
+ return "dataset" in response ? response.dataset : response;
480
+ } catch (error) {
481
+ if (error instanceof Error && error.message.toLowerCase().includes("not found")) {
482
+ throw new DatasetNotFoundError(datasetId);
483
+ }
484
+ throw error;
485
+ }
486
+ }
487
+ /**
488
+ * Get dataset by name
489
+ */
490
+ async getByName(name) {
491
+ const result = await this.list({ pageSize: 100 });
492
+ const dataset = result.datasets.find((d) => d.name === name);
493
+ return dataset ?? null;
494
+ }
495
+ /**
496
+ * List datasets
497
+ */
498
+ async list(options = {}) {
499
+ const params = {
500
+ page: options.page ?? 1,
501
+ page_size: options.pageSize ?? 20,
502
+ status: options.status,
503
+ visibility: options.visibility,
504
+ owner_id: options.ownerId
505
+ };
506
+ const response = await this.http.get("/datasets", params);
507
+ return response;
508
+ }
509
+ /**
510
+ * Update dataset
511
+ */
512
+ async update(datasetId, updates) {
513
+ const response = await this.http.put(
514
+ `/datasets/${datasetId}`,
515
+ updates
516
+ );
517
+ return "dataset" in response ? response.dataset : response;
518
+ }
519
+ /**
520
+ * Delete dataset
521
+ */
522
+ async delete(datasetId) {
523
+ return this.http.delete(`/datasets/${datasetId}`);
524
+ }
525
+ /**
526
+ * Update model configuration for a dataset
527
+ */
528
+ async updateModelConfig(datasetId, modelConfig, _force = false) {
529
+ const response = await this.http.put(
530
+ `/datasets/${datasetId}/model-config`,
531
+ modelConfig
532
+ );
533
+ return "dataset" in response ? response.dataset : response;
534
+ }
535
+ };
536
+
537
+ // src/documents.ts
538
+ var DocumentsClient = class {
539
+ constructor(http) {
540
+ this.http = http;
541
+ }
542
+ /**
543
+ * Upload a document file to a dataset
544
+ */
545
+ async upload(datasetId, file, options = {}) {
546
+ let filename = options.filename;
547
+ if (!filename && file instanceof File) {
548
+ filename = file.name;
549
+ }
550
+ if (!filename) {
551
+ throw new Error("filename is required when file is not a File object");
552
+ }
553
+ return this.http.uploadFile(
554
+ `/datasets/${datasetId}/documents/upload`,
555
+ file,
556
+ filename
557
+ );
558
+ }
559
+ /**
560
+ * Insert text content into a dataset
561
+ */
562
+ async insertText(datasetId, text, source) {
563
+ const body = { text };
564
+ if (source) {
565
+ body.file_source = source;
566
+ }
567
+ return this.http.post(
568
+ `/datasets/${datasetId}/documents/text`,
569
+ body
570
+ );
571
+ }
572
+ /**
573
+ * Insert multiple texts into a dataset
574
+ */
575
+ async insertBatch(datasetId, texts, sources) {
576
+ const body = { texts };
577
+ if (sources) {
578
+ body.file_sources = sources;
579
+ }
580
+ return this.http.post(
581
+ `/datasets/${datasetId}/documents/texts`,
582
+ body
583
+ );
584
+ }
585
+ /**
586
+ * List documents in a dataset
587
+ */
588
+ async list(datasetId, options = {}) {
589
+ const params = {
590
+ page: options.page ?? 1,
591
+ page_size: options.pageSize ?? 20,
592
+ status: options.status
593
+ };
594
+ return this.http.get(
595
+ `/datasets/${datasetId}/documents`,
596
+ params
597
+ );
598
+ }
599
+ /**
600
+ * Get document by ID
601
+ */
602
+ async get(datasetId, docId) {
603
+ try {
604
+ return await this.http.get(
605
+ `/datasets/${datasetId}/documents/${docId}`
606
+ );
607
+ } catch (error) {
608
+ if (error instanceof Error && error.message.toLowerCase().includes("not found")) {
609
+ throw new DocumentNotFoundError(docId, datasetId);
610
+ }
611
+ throw error;
612
+ }
613
+ }
614
+ /**
615
+ * Get document processing status by tracking ID
616
+ * @param datasetId - Dataset UUID
617
+ * @param trackId - Tracking ID returned from upload/insert operations
618
+ * @returns Object containing track_id, documents list, total_count, and status_summary
619
+ */
620
+ async getStatus(datasetId, trackId) {
621
+ return this.http.get(
622
+ `/datasets/${datasetId}/track_status/${trackId}`
623
+ );
624
+ }
625
+ /**
626
+ * Delete a document
627
+ */
628
+ async delete(datasetId, docId) {
629
+ return this.http.delete(
630
+ `/datasets/${datasetId}/documents/${docId}`
631
+ );
632
+ }
633
+ /**
634
+ * Delete multiple documents
635
+ */
636
+ async deleteBatch(datasetId, docIds) {
637
+ return this.http.post(
638
+ `/datasets/${datasetId}/documents/delete-batch`,
639
+ { doc_ids: docIds }
640
+ );
641
+ }
642
+ /**
643
+ * Scan and index new documents in the dataset
644
+ */
645
+ async scan(datasetId) {
646
+ return this.http.post(
647
+ `/datasets/${datasetId}/documents/scan`
648
+ );
649
+ }
650
+ /**
651
+ * Clear all documents in a dataset
652
+ */
653
+ async clear(datasetId) {
654
+ return this.http.post(
655
+ `/datasets/${datasetId}/documents/clear`
656
+ );
657
+ }
658
+ /**
659
+ * Upload a document from a remote URL
660
+ */
661
+ async uploadRemote(datasetId, url, filename) {
662
+ const body = { url };
663
+ if (filename) {
664
+ body.filename = filename;
665
+ }
666
+ return this.http.post(
667
+ `/datasets/${datasetId}/documents/upload-remote`,
668
+ body
669
+ );
670
+ }
671
+ };
672
+
673
+ // src/types.ts
674
+ var DocStatus = /* @__PURE__ */ ((DocStatus2) => {
675
+ DocStatus2["PENDING"] = "pending";
676
+ DocStatus2["PROCESSING"] = "processing";
677
+ DocStatus2["PROCESSED"] = "processed";
678
+ DocStatus2["FAILED"] = "failed";
679
+ DocStatus2["MULTIMODAL_PARSING"] = "multimodal_parsing";
680
+ DocStatus2["MULTIMODAL_PROCESSING"] = "multimodal_processing";
681
+ return DocStatus2;
682
+ })(DocStatus || {});
683
+ var QueryMode = /* @__PURE__ */ ((QueryMode2) => {
684
+ QueryMode2["LOCAL"] = "local";
685
+ QueryMode2["GLOBAL"] = "global";
686
+ QueryMode2["HYBRID"] = "hybrid";
687
+ QueryMode2["NAIVE"] = "naive";
688
+ QueryMode2["MIX"] = "mix";
689
+ QueryMode2["BYPASS"] = "bypass";
690
+ return QueryMode2;
691
+ })(QueryMode || {});
692
+ var StorageType = /* @__PURE__ */ ((StorageType2) => {
693
+ StorageType2["LOCAL"] = "local";
694
+ StorageType2["SUPABASE"] = "supabase";
695
+ StorageType2["S3"] = "s3";
696
+ StorageType2["ALIYUN_OSS"] = "aliyun-oss";
697
+ return StorageType2;
698
+ })(StorageType || {});
699
+ var ChunkEngine = /* @__PURE__ */ ((ChunkEngine2) => {
700
+ ChunkEngine2["TOKEN"] = "token";
701
+ ChunkEngine2["SENTENCE"] = "sentence";
702
+ ChunkEngine2["SEMANTIC"] = "semantic";
703
+ ChunkEngine2["RECURSIVE"] = "recursive";
704
+ return ChunkEngine2;
705
+ })(ChunkEngine || {});
706
+ var Visibility = /* @__PURE__ */ ((Visibility2) => {
707
+ Visibility2["PRIVATE"] = "private";
708
+ Visibility2["PUBLIC"] = "public";
709
+ return Visibility2;
710
+ })(Visibility || {});
711
+
712
+ // src/query.ts
713
+ function toSnakeCase(options) {
714
+ const result = {};
715
+ if (options.mode !== void 0) result.mode = options.mode;
716
+ if (options.onlyNeedContext !== void 0) result.only_need_context = options.onlyNeedContext;
717
+ if (options.onlyNeedPrompt !== void 0) result.only_need_prompt = options.onlyNeedPrompt;
718
+ if (options.responseType !== void 0) result.response_type = options.responseType;
719
+ if (options.topK !== void 0) result.top_k = options.topK;
720
+ if (options.chunkTopK !== void 0) result.chunk_top_k = options.chunkTopK;
721
+ if (options.maxEntityTokens !== void 0) result.max_entity_tokens = options.maxEntityTokens;
722
+ if (options.maxRelationTokens !== void 0) result.max_relation_tokens = options.maxRelationTokens;
723
+ if (options.maxTotalTokens !== void 0) result.max_total_tokens = options.maxTotalTokens;
724
+ if (options.conversationHistory !== void 0) result.conversation_history = options.conversationHistory;
725
+ if (options.historyTurns !== void 0) result.history_turns = options.historyTurns;
726
+ if (options.ids !== void 0) result.ids = options.ids;
727
+ if (options.userPrompt !== void 0) result.user_prompt = options.userPrompt;
728
+ if (options.enableRerank !== void 0) result.enable_rerank = options.enableRerank;
729
+ if (options.imageBase64 !== void 0) result.image_base64 = options.imageBase64;
730
+ if (options.imageUrl !== void 0) result.image_url = options.imageUrl;
731
+ return result;
732
+ }
733
+ var QueryClient = class {
734
+ constructor(http) {
735
+ this.http = http;
736
+ }
737
+ /**
738
+ * Execute a RAG query on a dataset
739
+ */
740
+ async query(datasetId, query, options = {}) {
741
+ const body = {
742
+ query,
743
+ ...toSnakeCase(options),
744
+ mode: options.mode ?? "mix" /* MIX */
745
+ };
746
+ return this.http.post(
747
+ `/datasets/${datasetId}/query`,
748
+ body
749
+ );
750
+ }
751
+ /**
752
+ * Execute a streaming RAG query
753
+ */
754
+ async *queryStream(datasetId, query, options = {}) {
755
+ const body = {
756
+ query,
757
+ ...toSnakeCase(options),
758
+ mode: options.mode ?? "mix" /* MIX */
759
+ };
760
+ for await (const line of this.http.stream(
761
+ `/datasets/${datasetId}/query/stream`,
762
+ body
763
+ )) {
764
+ try {
765
+ const data = JSON.parse(line);
766
+ if (typeof data.response === "string") {
767
+ yield data.response;
768
+ } else if (typeof data.error === "string") {
769
+ throw new Error(data.error);
770
+ }
771
+ } catch (e) {
772
+ if (e instanceof SyntaxError) {
773
+ yield line;
774
+ } else {
775
+ throw e;
776
+ }
777
+ }
778
+ }
779
+ }
780
+ /**
781
+ * Execute a query across multiple datasets
782
+ */
783
+ async crossDatasetQuery(query, datasetIds, options = {}) {
784
+ const body = {
785
+ query,
786
+ dataset_ids: datasetIds,
787
+ ...toSnakeCase(options),
788
+ mode: options.mode ?? "mix" /* MIX */
789
+ };
790
+ if (options.documentFilters) {
791
+ body.document_filters = options.documentFilters;
792
+ }
793
+ if (options.maxResultsPerDataset !== void 0) {
794
+ body.max_results_per_dataset = options.maxResultsPerDataset;
795
+ }
796
+ return this.http.post(
797
+ "/datasets/cross-query",
798
+ body
799
+ );
800
+ }
801
+ /**
802
+ * Execute an image-based RAG query
803
+ */
804
+ async imageQuery(datasetId, image, query, options = {}) {
805
+ const body = {
806
+ ...toSnakeCase(options),
807
+ mode: options.mode ?? "mix" /* MIX */
808
+ };
809
+ if (query) {
810
+ body.query = query;
811
+ }
812
+ if (typeof image === "string") {
813
+ if (image.startsWith("http://") || image.startsWith("https://")) {
814
+ body.image_url = image;
815
+ } else {
816
+ body.image_base64 = image;
817
+ }
818
+ } else {
819
+ const bytes = new Uint8Array(image);
820
+ let binary = "";
821
+ for (let i = 0; i < bytes.byteLength; i++) {
822
+ binary += String.fromCharCode(bytes[i]);
823
+ }
824
+ body.image_base64 = btoa(binary);
825
+ }
826
+ return this.http.post(
827
+ `/datasets/${datasetId}/query`,
828
+ body
829
+ );
830
+ }
831
+ /**
832
+ * Get only the retrieved context without generating a response
833
+ */
834
+ async getContext(datasetId, query, options = {}) {
835
+ return this.query(datasetId, query, {
836
+ ...options,
837
+ onlyNeedContext: true
838
+ });
839
+ }
840
+ };
841
+
842
+ // src/graph.ts
843
+ var GraphClient = class {
844
+ constructor(http) {
845
+ this.http = http;
846
+ }
847
+ /**
848
+ * Get knowledge graph subgraph by label
849
+ */
850
+ async getKnowledgeGraph(datasetId, label, options = {}) {
851
+ const params = {
852
+ label,
853
+ max_depth: options.maxDepth ?? 3,
854
+ max_nodes: options.maxNodes ?? 1e3
855
+ };
856
+ return this.http.get(
857
+ `/datasets/${datasetId}/graphs`,
858
+ params
859
+ );
860
+ }
861
+ /**
862
+ * Get all graph labels in a dataset
863
+ */
864
+ async getLabels(datasetId) {
865
+ const response = await this.http.get(
866
+ `/datasets/${datasetId}/graph/label/list`
867
+ );
868
+ return Array.isArray(response) ? response : response.labels;
869
+ }
870
+ /**
871
+ * Check if an entity exists in the knowledge graph
872
+ */
873
+ async checkEntityExists(datasetId, entityName) {
874
+ const response = await this.http.get(
875
+ `/datasets/${datasetId}/graph/entity/exists`,
876
+ { name: entityName }
877
+ );
878
+ return response.exists;
879
+ }
880
+ /**
881
+ * Get entity by name
882
+ */
883
+ async getEntity(datasetId, entityName) {
884
+ try {
885
+ return await this.http.get(
886
+ `/datasets/${datasetId}/graph/entity`,
887
+ { name: entityName }
888
+ );
889
+ } catch {
890
+ return null;
891
+ }
892
+ }
893
+ /**
894
+ * Edit an entity in the knowledge graph
895
+ */
896
+ async editEntity(datasetId, entityName, updatedData, allowRename = false) {
897
+ return this.http.post(
898
+ `/datasets/${datasetId}/graph/entity/edit`,
899
+ {
900
+ entity_name: entityName,
901
+ updated_data: updatedData,
902
+ allow_rename: allowRename
903
+ }
904
+ );
905
+ }
906
+ /**
907
+ * Edit a relation in the knowledge graph
908
+ */
909
+ async editRelation(datasetId, sourceId, targetId, updatedData) {
910
+ return this.http.post(
911
+ `/datasets/${datasetId}/graph/relation/edit`,
912
+ {
913
+ source_id: sourceId,
914
+ target_id: targetId,
915
+ updated_data: updatedData
916
+ }
917
+ );
918
+ }
919
+ /**
920
+ * Search for entities matching a query
921
+ */
922
+ async searchEntities(datasetId, query, topK = 10) {
923
+ const response = await this.http.get(
924
+ `/datasets/${datasetId}/graph/entity/search`,
925
+ { query, top_k: topK }
926
+ );
927
+ return Array.isArray(response) ? response : response.entities;
928
+ }
929
+ /**
930
+ * Search for relations matching a query
931
+ */
932
+ async searchRelations(datasetId, query, topK = 10) {
933
+ const response = await this.http.get(
934
+ `/datasets/${datasetId}/graph/relation/search`,
935
+ { query, top_k: topK }
936
+ );
937
+ return Array.isArray(response) ? response : response.relations;
938
+ }
939
+ /**
940
+ * Get neighboring entities of a given entity
941
+ */
942
+ async getEntityNeighbors(datasetId, entityName, maxDepth = 1) {
943
+ return this.getKnowledgeGraph(datasetId, entityName, { maxDepth });
944
+ }
945
+ };
946
+
947
+ // src/client.ts
948
+ var AuthenticatedHttpClient = class extends HttpClient {
949
+ constructor(baseUrl, authHandler, config) {
950
+ super({
951
+ baseUrl,
952
+ timeout: config.timeout ?? 3e4,
953
+ maxRetries: config.maxRetries ?? 3,
954
+ retryDelay: config.retryDelay ?? 1e3
955
+ });
956
+ this.authHandler = authHandler;
957
+ }
958
+ async injectAuthHeaders(headers) {
959
+ const authHeaders = await this.authHandler.getHeaders();
960
+ return { ...headers, ...authHeaders };
961
+ }
962
+ async get(path, params, headers) {
963
+ const authHeaders = await this.injectAuthHeaders(headers);
964
+ return super.get(path, params, authHeaders);
965
+ }
966
+ async post(path, body, params, headers) {
967
+ const authHeaders = await this.injectAuthHeaders(headers);
968
+ return super.post(path, body, params, authHeaders);
969
+ }
970
+ async put(path, body, headers) {
971
+ const authHeaders = await this.injectAuthHeaders(headers);
972
+ return super.put(path, body, authHeaders);
973
+ }
974
+ async delete(path, params, headers) {
975
+ const authHeaders = await this.injectAuthHeaders(headers);
976
+ return super.delete(path, params, authHeaders);
977
+ }
978
+ async *stream(path, body, headers) {
979
+ const authHeaders = await this.injectAuthHeaders(headers);
980
+ yield* super.stream(path, body, authHeaders);
981
+ }
982
+ async uploadFile(path, file, filename, fieldName, extraFields, headers) {
983
+ const authHeaders = await this.injectAuthHeaders(headers);
984
+ return super.uploadFile(path, file, filename, fieldName, extraFields, authHeaders);
985
+ }
986
+ };
987
+ var RagAgentClient = class {
988
+ /**
989
+ * Create a new RAG Agent client
990
+ */
991
+ constructor(config) {
992
+ const baseUrl = config.baseUrl.replace(/\/$/, "");
993
+ const authConfig = {
994
+ apiKey: config.apiKey,
995
+ apiKeyHeader: config.apiKeyHeader ?? "X-API-Key",
996
+ jwtToken: config.jwtToken,
997
+ supabaseUrl: config.supabaseUrl,
998
+ supabaseAnonKey: config.supabaseAnonKey,
999
+ supabaseServiceKey: config.supabaseServiceKey,
1000
+ supabaseAccessToken: config.supabaseAccessToken,
1001
+ username: config.username,
1002
+ password: config.password
1003
+ };
1004
+ this.authHandler = new AuthHandler(authConfig);
1005
+ this.http = new AuthenticatedHttpClient(baseUrl, this.authHandler, config);
1006
+ this.authHandler.setHttpClient(this.http);
1007
+ this.datasets = new DatasetsClient(this.http);
1008
+ this.documents = new DocumentsClient(this.http);
1009
+ this.query = new QueryClient(this.http);
1010
+ this.graph = new GraphClient(this.http);
1011
+ }
1012
+ /**
1013
+ * Get the base URL of the RAG Agent server
1014
+ */
1015
+ get baseUrl() {
1016
+ return this.http["baseUrl"];
1017
+ }
1018
+ /**
1019
+ * Check if the client is authenticated
1020
+ */
1021
+ get isAuthenticated() {
1022
+ return this.authHandler.isAuthenticated();
1023
+ }
1024
+ /**
1025
+ * Check server health
1026
+ */
1027
+ async healthCheck() {
1028
+ return this.http.get("/health");
1029
+ }
1030
+ /**
1031
+ * Get server version and configuration info
1032
+ */
1033
+ async getServerInfo() {
1034
+ try {
1035
+ return await this.http.get("/");
1036
+ } catch {
1037
+ return this.healthCheck();
1038
+ }
1039
+ }
1040
+ /**
1041
+ * Logout and clear authentication state
1042
+ */
1043
+ logout() {
1044
+ this.authHandler.logout();
1045
+ }
1046
+ };
1047
+
1048
+ // src/mock.ts
1049
+ function uuid() {
1050
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1051
+ const r = Math.random() * 16 | 0;
1052
+ const v = c === "x" ? r : r & 3 | 8;
1053
+ return v.toString(16);
1054
+ });
1055
+ }
1056
+ var MockDatasetsClient = class {
1057
+ constructor() {
1058
+ this.datasets = /* @__PURE__ */ new Map();
1059
+ }
1060
+ async create(options) {
1061
+ const datasetId = uuid();
1062
+ const dataset = {
1063
+ dataset_uuid: datasetId,
1064
+ name: options.name,
1065
+ description: options.description,
1066
+ rag_type: options.rag_type ?? "rag",
1067
+ storage_type: options.storage_type ?? "local",
1068
+ chunk_engine: options.chunk_engine ?? "token",
1069
+ status: "active",
1070
+ visibility: options.visibility ?? "private",
1071
+ default_permission: options.default_permission ?? "none",
1072
+ args: options.args ?? {},
1073
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
1074
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
1075
+ };
1076
+ this.datasets.set(datasetId, dataset);
1077
+ return dataset;
1078
+ }
1079
+ async get(datasetId) {
1080
+ const dataset = this.datasets.get(datasetId);
1081
+ if (!dataset) {
1082
+ throw new Error(`Dataset not found: ${datasetId}`);
1083
+ }
1084
+ return dataset;
1085
+ }
1086
+ async getByName(name) {
1087
+ for (const dataset of this.datasets.values()) {
1088
+ if (dataset.name === name) return dataset;
1089
+ }
1090
+ return null;
1091
+ }
1092
+ async list(options = {}) {
1093
+ const datasets = Array.from(this.datasets.values());
1094
+ const page = options.page ?? 1;
1095
+ const pageSize = options.pageSize ?? 20;
1096
+ const start = (page - 1) * pageSize;
1097
+ return {
1098
+ datasets: datasets.slice(start, start + pageSize),
1099
+ total: datasets.length,
1100
+ page,
1101
+ page_size: pageSize
1102
+ };
1103
+ }
1104
+ async update(datasetId, updates) {
1105
+ const dataset = await this.get(datasetId);
1106
+ Object.assign(dataset, updates, { updated_at: (/* @__PURE__ */ new Date()).toISOString() });
1107
+ return dataset;
1108
+ }
1109
+ async delete(datasetId) {
1110
+ this.datasets.delete(datasetId);
1111
+ return { status: "deleted", message: `Dataset ${datasetId} deleted` };
1112
+ }
1113
+ };
1114
+ var MockDocumentsClient = class {
1115
+ constructor() {
1116
+ this.documents = /* @__PURE__ */ new Map();
1117
+ }
1118
+ async upload(datasetId, _file, options) {
1119
+ return this.insertInternal(datasetId, `Uploaded: ${options?.filename ?? "file"}`);
1120
+ }
1121
+ async insertText(datasetId, text, _source) {
1122
+ return this.insertInternal(datasetId, text);
1123
+ }
1124
+ async insertInternal(datasetId, content) {
1125
+ const docId = uuid();
1126
+ const trackId = `track-${uuid().slice(0, 8)}`;
1127
+ if (!this.documents.has(datasetId)) {
1128
+ this.documents.set(datasetId, /* @__PURE__ */ new Map());
1129
+ }
1130
+ this.documents.get(datasetId).set(docId, {
1131
+ id: docId,
1132
+ content_summary: content.slice(0, 100),
1133
+ content_length: content.length,
1134
+ status: "processed" /* PROCESSED */,
1135
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1136
+ });
1137
+ return {
1138
+ status: "success",
1139
+ message: "Document inserted",
1140
+ track_id: trackId,
1141
+ doc_id: docId
1142
+ };
1143
+ }
1144
+ async insertBatch(datasetId, texts, _sources) {
1145
+ for (const text of texts) {
1146
+ await this.insertInternal(datasetId, text);
1147
+ }
1148
+ return {
1149
+ status: "success",
1150
+ message: `Inserted ${texts.length} documents`,
1151
+ track_id: `batch-${uuid().slice(0, 8)}`
1152
+ };
1153
+ }
1154
+ async list(datasetId, options = {}) {
1155
+ const docs = Array.from(this.documents.get(datasetId)?.values() ?? []);
1156
+ const page = options.page ?? 1;
1157
+ const pageSize = options.pageSize ?? 20;
1158
+ const start = (page - 1) * pageSize;
1159
+ return {
1160
+ documents: docs.slice(start, start + pageSize),
1161
+ total: docs.length,
1162
+ page,
1163
+ page_size: pageSize
1164
+ };
1165
+ }
1166
+ async get(datasetId, docId) {
1167
+ const doc = this.documents.get(datasetId)?.get(docId);
1168
+ if (!doc) throw new Error(`Document not found: ${docId}`);
1169
+ return doc;
1170
+ }
1171
+ async getStatus(datasetId, docId) {
1172
+ return this.get(datasetId, docId);
1173
+ }
1174
+ async delete(datasetId, docId) {
1175
+ this.documents.get(datasetId)?.delete(docId);
1176
+ return { status: "deleted" };
1177
+ }
1178
+ async scan(_datasetId) {
1179
+ return {
1180
+ status: "success",
1181
+ message: "Scan completed",
1182
+ track_id: `scan-${uuid().slice(0, 8)}`
1183
+ };
1184
+ }
1185
+ async clear(datasetId) {
1186
+ this.documents.set(datasetId, /* @__PURE__ */ new Map());
1187
+ return { status: "cleared" };
1188
+ }
1189
+ };
1190
+ var MockQueryClient = class {
1191
+ constructor(defaultResponse = "This is a mock response from RAG Agent SDK.") {
1192
+ this.responses = /* @__PURE__ */ new Map();
1193
+ this.defaultResponse = defaultResponse;
1194
+ }
1195
+ /**
1196
+ * Set a custom response for a specific query
1197
+ */
1198
+ setResponse(query, response) {
1199
+ this.responses.set(query, response);
1200
+ }
1201
+ async query(datasetId, query, options = {}) {
1202
+ const response = this.responses.get(query) ?? this.defaultResponse;
1203
+ return {
1204
+ response,
1205
+ dataset_id: datasetId,
1206
+ query_mode: options.mode ?? "mix" /* MIX */,
1207
+ entities: [{ name: "MockEntity", type: "test", description: "A mock entity", properties: {} }],
1208
+ chunks: []
1209
+ };
1210
+ }
1211
+ async *queryStream(_datasetId, query, _options = {}) {
1212
+ const response = this.responses.get(query) ?? this.defaultResponse;
1213
+ for (const word of response.split(" ")) {
1214
+ yield word + " ";
1215
+ }
1216
+ }
1217
+ async crossDatasetQuery(query, datasetIds, options = {}) {
1218
+ const response = this.responses.get(query) ?? this.defaultResponse;
1219
+ return {
1220
+ response,
1221
+ query,
1222
+ dataset_count: datasetIds.length,
1223
+ total_chunks: 0,
1224
+ query_mode: options.mode ?? "mix" /* MIX */,
1225
+ dataset_results: {}
1226
+ };
1227
+ }
1228
+ async getContext(_datasetId, _query, options = {}) {
1229
+ return {
1230
+ response: "",
1231
+ dataset_id: _datasetId,
1232
+ query_mode: options.mode ?? "mix" /* MIX */,
1233
+ entities: [
1234
+ { name: "MockEntity1", type: "concept", description: "Mock entity 1", properties: {} },
1235
+ { name: "MockEntity2", type: "concept", description: "Mock entity 2", properties: {} }
1236
+ ],
1237
+ relationships: [
1238
+ { source: "MockEntity1", target: "MockEntity2", type: "related_to", properties: {} }
1239
+ ],
1240
+ chunks: []
1241
+ };
1242
+ }
1243
+ };
1244
+ var MockGraphClient = class {
1245
+ async getKnowledgeGraph(_datasetId, label, _options) {
1246
+ return {
1247
+ nodes: [
1248
+ { id: "1", label, properties: {} },
1249
+ { id: "2", label: "RelatedNode", properties: {} }
1250
+ ],
1251
+ edges: [{ source: "1", target: "2", type: "connected_to" }]
1252
+ };
1253
+ }
1254
+ async getLabels(_datasetId) {
1255
+ return ["MockLabel1", "MockLabel2", "MockLabel3"];
1256
+ }
1257
+ async checkEntityExists(_datasetId, _entityName) {
1258
+ return true;
1259
+ }
1260
+ async getEntity(_datasetId, entityName) {
1261
+ return {
1262
+ name: entityName,
1263
+ type: "mock",
1264
+ description: `Mock entity: ${entityName}`,
1265
+ properties: {}
1266
+ };
1267
+ }
1268
+ async editEntity(_datasetId, entityName, _updatedData, _allowRename) {
1269
+ return { status: "updated", entity_name: entityName };
1270
+ }
1271
+ async searchEntities(_datasetId, _query, topK = 10) {
1272
+ return Array.from({ length: Math.min(topK, 3) }, (_, i) => ({
1273
+ name: `Result${i}`,
1274
+ type: "mock",
1275
+ description: `Search result ${i}`,
1276
+ properties: {}
1277
+ }));
1278
+ }
1279
+ };
1280
+ var MockRagAgentClient = class {
1281
+ constructor(defaultResponse = "This is a mock response.") {
1282
+ this.datasets = new MockDatasetsClient();
1283
+ this.documents = new MockDocumentsClient();
1284
+ this.graph = new MockGraphClient();
1285
+ this.query = new MockQueryClient(defaultResponse);
1286
+ }
1287
+ get baseUrl() {
1288
+ return "http://mock-server:9621";
1289
+ }
1290
+ get isAuthenticated() {
1291
+ return true;
1292
+ }
1293
+ async healthCheck() {
1294
+ return { status: "healthy", mock: true };
1295
+ }
1296
+ logout() {
1297
+ }
1298
+ };
1299
+
1300
+ // src/config.ts
1301
+ var ENV_BASE_URL = "RAG_AGENT_BASE_URL";
1302
+ var ENV_API_KEY = "RAG_AGENT_API_KEY";
1303
+ var ENV_JWT_TOKEN = "RAG_AGENT_JWT_TOKEN";
1304
+ var ENV_TIMEOUT = "RAG_AGENT_TIMEOUT";
1305
+ var ENV_MAX_RETRIES = "RAG_AGENT_MAX_RETRIES";
1306
+ var ENV_DEBUG = "RAG_AGENT_DEBUG";
1307
+ var ENV_SUPABASE_URL = "RAG_AGENT_SUPABASE_URL";
1308
+ var ENV_SUPABASE_ANON_KEY = "RAG_AGENT_SUPABASE_ANON_KEY";
1309
+ var ENV_SUPABASE_SERVICE_KEY = "RAG_AGENT_SUPABASE_SERVICE_KEY";
1310
+ var ENV_SUPABASE_ACCESS_TOKEN = "RAG_AGENT_SUPABASE_ACCESS_TOKEN";
1311
+ var DEFAULT_BASE_URL = "http://localhost:9621";
1312
+ var DEFAULT_TIMEOUT = 3e4;
1313
+ var DEFAULT_MAX_RETRIES = 3;
1314
+ var DEFAULT_RETRY_DELAY = 1e3;
1315
+ function getEnv(name) {
1316
+ if (typeof process !== "undefined" && process.env) {
1317
+ return process.env[name];
1318
+ }
1319
+ return void 0;
1320
+ }
1321
+ function getEnvBool(name, defaultValue = false) {
1322
+ const value = getEnv(name)?.toLowerCase();
1323
+ if (value === "true" || value === "1" || value === "yes") return true;
1324
+ if (value === "false" || value === "0" || value === "no") return false;
1325
+ return defaultValue;
1326
+ }
1327
+ function getEnvNumber(name, defaultValue) {
1328
+ const value = getEnv(name);
1329
+ if (value) {
1330
+ const num = parseInt(value, 10);
1331
+ if (!isNaN(num)) return num;
1332
+ }
1333
+ return defaultValue;
1334
+ }
1335
+ var SDKConfig = class _SDKConfig {
1336
+ constructor(options = {}) {
1337
+ this.sdkVersion = "0.1.0";
1338
+ this.baseUrl = options.baseUrl ?? getEnv(ENV_BASE_URL) ?? DEFAULT_BASE_URL;
1339
+ this.apiKey = options.apiKey ?? getEnv(ENV_API_KEY);
1340
+ this.jwtToken = options.jwtToken ?? getEnv(ENV_JWT_TOKEN);
1341
+ this.timeout = options.timeout ?? getEnvNumber(ENV_TIMEOUT, DEFAULT_TIMEOUT);
1342
+ this.maxRetries = options.maxRetries ?? getEnvNumber(ENV_MAX_RETRIES, DEFAULT_MAX_RETRIES);
1343
+ this.retryDelay = options.retryDelay ?? DEFAULT_RETRY_DELAY;
1344
+ this.apiKeyHeader = options.apiKeyHeader ?? "X-API-Key";
1345
+ this.supabaseUrl = options.supabaseUrl ?? getEnv(ENV_SUPABASE_URL);
1346
+ this.supabaseAnonKey = options.supabaseAnonKey ?? getEnv(ENV_SUPABASE_ANON_KEY);
1347
+ this.supabaseServiceKey = options.supabaseServiceKey ?? getEnv(ENV_SUPABASE_SERVICE_KEY);
1348
+ this.supabaseAccessToken = options.supabaseAccessToken ?? getEnv(ENV_SUPABASE_ACCESS_TOKEN);
1349
+ this.username = options.username;
1350
+ this.password = options.password;
1351
+ this.debug = options.debug ?? getEnvBool(ENV_DEBUG, false);
1352
+ }
1353
+ /**
1354
+ * Create configuration from environment variables with optional overrides
1355
+ */
1356
+ static fromEnv(overrides = {}) {
1357
+ return new _SDKConfig(overrides);
1358
+ }
1359
+ /**
1360
+ * Check if any authentication is configured
1361
+ */
1362
+ hasAuth() {
1363
+ return !!(this.apiKey || this.jwtToken || this.supabaseServiceKey || this.supabaseAccessToken || this.username && this.password);
1364
+ }
1365
+ /**
1366
+ * Validate configuration
1367
+ */
1368
+ validate() {
1369
+ if (!this.baseUrl) {
1370
+ throw new Error(
1371
+ `Missing base URL. Set ${ENV_BASE_URL} environment variable or pass baseUrl option.`
1372
+ );
1373
+ }
1374
+ if (!this.hasAuth()) {
1375
+ console.warn(
1376
+ `No authentication configured. Set ${ENV_API_KEY} environment variable or pass apiKey option for authenticated requests.`
1377
+ );
1378
+ }
1379
+ }
1380
+ /**
1381
+ * Get user agent string
1382
+ */
1383
+ getUserAgent() {
1384
+ return `rag-agent-sdk-typescript/${this.sdkVersion}`;
1385
+ }
1386
+ };
1387
+ function getDefaultConfig() {
1388
+ return SDKConfig.fromEnv();
1389
+ }
1390
+
1391
+ // src/logger.ts
1392
+ var REQUEST_ID_HEADER = "X-Request-ID";
1393
+ var SDK_VERSION_HEADER = "X-SDK-Version";
1394
+ var SDK_LANGUAGE_HEADER = "X-SDK-Language";
1395
+ var LOG_LEVELS = {
1396
+ debug: 0,
1397
+ info: 1,
1398
+ warn: 2,
1399
+ error: 3,
1400
+ none: 4
1401
+ };
1402
+ var SDKLogger = class {
1403
+ constructor(config = {}) {
1404
+ this.level = config.level ?? "warn";
1405
+ this.debug = config.debug ?? false;
1406
+ this.sdkVersion = config.sdkVersion ?? "0.1.0";
1407
+ if (this.debug) {
1408
+ this.level = "debug";
1409
+ }
1410
+ }
1411
+ /**
1412
+ * Generate a unique request ID for tracing
1413
+ */
1414
+ generateRequestId() {
1415
+ const random = Math.random().toString(36).substring(2, 10);
1416
+ const timestamp = Date.now().toString(36);
1417
+ return `sdk-${timestamp}${random}`;
1418
+ }
1419
+ /**
1420
+ * Get headers to include in API requests
1421
+ */
1422
+ getRequestHeaders(requestId) {
1423
+ return {
1424
+ [REQUEST_ID_HEADER]: requestId ?? this.generateRequestId(),
1425
+ [SDK_VERSION_HEADER]: this.sdkVersion,
1426
+ [SDK_LANGUAGE_HEADER]: "typescript"
1427
+ };
1428
+ }
1429
+ /**
1430
+ * Check if a log level is enabled
1431
+ */
1432
+ isEnabled(level) {
1433
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
1434
+ }
1435
+ /**
1436
+ * Format log message with request ID
1437
+ */
1438
+ formatMessage(requestId, message) {
1439
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1440
+ return `[${timestamp}] [${requestId}] ${message}`;
1441
+ }
1442
+ /**
1443
+ * Log a debug message
1444
+ */
1445
+ logDebug(requestId, message, data) {
1446
+ if (!this.isEnabled("debug")) return;
1447
+ console.debug(this.formatMessage(requestId, message), data ?? "");
1448
+ }
1449
+ /**
1450
+ * Log an info message
1451
+ */
1452
+ logInfo(requestId, message) {
1453
+ if (!this.isEnabled("info")) return;
1454
+ console.info(this.formatMessage(requestId, message));
1455
+ }
1456
+ /**
1457
+ * Log a warning
1458
+ */
1459
+ logWarn(requestId, message) {
1460
+ if (!this.isEnabled("warn")) return;
1461
+ console.warn(this.formatMessage(requestId, message));
1462
+ }
1463
+ /**
1464
+ * Log an error
1465
+ */
1466
+ logError(requestId, message, error) {
1467
+ if (!this.isEnabled("error")) return;
1468
+ console.error(this.formatMessage(requestId, message), error ?? "");
1469
+ }
1470
+ /**
1471
+ * Log an outgoing request
1472
+ */
1473
+ logRequest(method, url, requestId, body) {
1474
+ this.logDebug(requestId, `-> ${method} ${url}`);
1475
+ if (this.debug && body) {
1476
+ this.logDebug(requestId, `Request body: ${this.truncate(JSON.stringify(body))}`);
1477
+ }
1478
+ }
1479
+ /**
1480
+ * Log an incoming response
1481
+ */
1482
+ logResponse(requestId, statusCode, elapsedMs, body) {
1483
+ const level = statusCode >= 400 ? "warn" : "debug";
1484
+ const message = `<- ${statusCode} (${elapsedMs.toFixed(0)}ms)`;
1485
+ if (level === "warn") {
1486
+ this.logWarn(requestId, message);
1487
+ } else {
1488
+ this.logDebug(requestId, message);
1489
+ }
1490
+ if (this.debug && body) {
1491
+ this.logDebug(requestId, `Response body: ${this.truncate(JSON.stringify(body))}`);
1492
+ }
1493
+ }
1494
+ /**
1495
+ * Log a retry attempt
1496
+ */
1497
+ logRetry(requestId, attempt, maxAttempts, delayMs) {
1498
+ this.logWarn(
1499
+ requestId,
1500
+ `Retry ${attempt}/${maxAttempts} in ${delayMs}ms`
1501
+ );
1502
+ }
1503
+ /**
1504
+ * Truncate long strings for logging
1505
+ */
1506
+ truncate(str, maxLength = 500) {
1507
+ if (str.length > maxLength) {
1508
+ return str.substring(0, maxLength) + "... (truncated)";
1509
+ }
1510
+ return str;
1511
+ }
1512
+ };
1513
+ function configureLogging(level, debug = false) {
1514
+ return new SDKLogger({ level, debug });
1515
+ }
1516
+ export {
1517
+ AuthHandler,
1518
+ AuthenticationError,
1519
+ AuthorizationError,
1520
+ ChunkEngine,
1521
+ ConnectionError,
1522
+ DatasetNotFoundError,
1523
+ DatasetsClient,
1524
+ DocStatus,
1525
+ DocumentNotFoundError,
1526
+ DocumentsClient,
1527
+ GraphClient,
1528
+ HttpClient,
1529
+ MockQueryClient,
1530
+ MockRagAgentClient,
1531
+ NotFoundError,
1532
+ QueryClient,
1533
+ QueryMode,
1534
+ RagAgentClient,
1535
+ RagAgentError,
1536
+ RateLimitError,
1537
+ SDKConfig,
1538
+ SDKLogger,
1539
+ ServerError,
1540
+ StorageType,
1541
+ TimeoutError,
1542
+ ValidationError,
1543
+ Visibility,
1544
+ configureLogging,
1545
+ getDefaultConfig
1546
+ };