@rainfall-devkit/sdk 0.1.8 → 0.2.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.
Files changed (58) hide show
  1. package/README.md +51 -0
  2. package/dist/chunk-7MRE4ZVI.mjs +662 -0
  3. package/dist/chunk-AQFC7YAX.mjs +27 -0
  4. package/dist/chunk-EI7SJH5K.mjs +85 -0
  5. package/dist/chunk-NTTAVKRT.mjs +89 -0
  6. package/dist/chunk-RVKW5KBT.mjs +269 -0
  7. package/dist/chunk-V5QWJVLC.mjs +662 -0
  8. package/dist/chunk-VDPKDC3R.mjs +869 -0
  9. package/dist/chunk-WOITG5TG.mjs +84 -0
  10. package/dist/chunk-XAHJQRBJ.mjs +269 -0
  11. package/dist/chunk-XEQ6U3JQ.mjs +269 -0
  12. package/dist/cli/index.js +3797 -632
  13. package/dist/cli/index.mjs +453 -36
  14. package/dist/config-7UT7GYSN.mjs +16 -0
  15. package/dist/config-DDTQQBN7.mjs +14 -0
  16. package/dist/config-MD45VGWD.mjs +14 -0
  17. package/dist/config-ZKNHII2A.mjs +8 -0
  18. package/dist/daemon/index.d.mts +168 -0
  19. package/dist/daemon/index.d.ts +168 -0
  20. package/dist/daemon/index.js +3182 -0
  21. package/dist/daemon/index.mjs +1548 -0
  22. package/dist/errors-BMPseAnM.d.mts +47 -0
  23. package/dist/errors-BMPseAnM.d.ts +47 -0
  24. package/dist/errors-CZdRoYyw.d.ts +332 -0
  25. package/dist/errors-Chjq1Mev.d.mts +332 -0
  26. package/dist/index.d.mts +249 -2
  27. package/dist/index.d.ts +249 -2
  28. package/dist/index.js +1247 -3
  29. package/dist/index.mjs +227 -2
  30. package/dist/listeners-B5Vy9Ao5.d.ts +372 -0
  31. package/dist/listeners-BbYIaNCs.d.mts +372 -0
  32. package/dist/listeners-CP2A9J_2.d.ts +372 -0
  33. package/dist/listeners-CTRSofnm.d.mts +372 -0
  34. package/dist/listeners-CYI-YwIF.d.mts +372 -0
  35. package/dist/listeners-DRwITBW_.d.mts +372 -0
  36. package/dist/listeners-DrMrvFT5.d.ts +372 -0
  37. package/dist/listeners-MNAnpZj-.d.mts +372 -0
  38. package/dist/listeners-PZI7iT85.d.ts +372 -0
  39. package/dist/listeners-QJeEtLbV.d.ts +372 -0
  40. package/dist/listeners-hp0Ib2Ox.d.ts +372 -0
  41. package/dist/listeners-jLwetUnx.d.mts +372 -0
  42. package/dist/mcp.d.mts +7 -2
  43. package/dist/mcp.d.ts +7 -2
  44. package/dist/mcp.js +92 -1
  45. package/dist/mcp.mjs +1 -1
  46. package/dist/sdk-4OvXPr8E.d.mts +1054 -0
  47. package/dist/sdk-4OvXPr8E.d.ts +1054 -0
  48. package/dist/sdk-CJ9g5lFo.d.mts +772 -0
  49. package/dist/sdk-CJ9g5lFo.d.ts +772 -0
  50. package/dist/sdk-CN1ezZrI.d.mts +1054 -0
  51. package/dist/sdk-CN1ezZrI.d.ts +1054 -0
  52. package/dist/sdk-DD1OeGRJ.d.mts +871 -0
  53. package/dist/sdk-DD1OeGRJ.d.ts +871 -0
  54. package/dist/sdk-Xw0BjsLd.d.mts +1054 -0
  55. package/dist/sdk-Xw0BjsLd.d.ts +1054 -0
  56. package/dist/types-GnRAfH-h.d.mts +489 -0
  57. package/dist/types-GnRAfH-h.d.ts +489 -0
  58. package/package.json +17 -5
@@ -0,0 +1,869 @@
1
+ // src/errors.ts
2
+ var RainfallError = class _RainfallError extends Error {
3
+ constructor(message, code, statusCode, details) {
4
+ super(message);
5
+ this.code = code;
6
+ this.statusCode = statusCode;
7
+ this.details = details;
8
+ this.name = "RainfallError";
9
+ Object.setPrototypeOf(this, _RainfallError.prototype);
10
+ }
11
+ toJSON() {
12
+ return {
13
+ name: this.name,
14
+ code: this.code,
15
+ message: this.message,
16
+ statusCode: this.statusCode,
17
+ details: this.details
18
+ };
19
+ }
20
+ };
21
+ var AuthenticationError = class _AuthenticationError extends RainfallError {
22
+ constructor(message = "Invalid API key", details) {
23
+ super(message, "AUTHENTICATION_ERROR", 401, details);
24
+ this.name = "AuthenticationError";
25
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
26
+ }
27
+ };
28
+ var RateLimitError = class _RateLimitError extends RainfallError {
29
+ retryAfter;
30
+ limit;
31
+ remaining;
32
+ resetAt;
33
+ constructor(message = "Rate limit exceeded", retryAfter = 60, limit = 0, remaining = 0, resetAt) {
34
+ super(message, "RATE_LIMIT_ERROR", 429, { retryAfter, limit, remaining });
35
+ this.name = "RateLimitError";
36
+ this.retryAfter = retryAfter;
37
+ this.limit = limit;
38
+ this.remaining = remaining;
39
+ this.resetAt = resetAt || new Date(Date.now() + retryAfter * 1e3);
40
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
41
+ }
42
+ };
43
+ var ValidationError = class _ValidationError extends RainfallError {
44
+ constructor(message, details) {
45
+ super(message, "VALIDATION_ERROR", 400, details);
46
+ this.name = "ValidationError";
47
+ Object.setPrototypeOf(this, _ValidationError.prototype);
48
+ }
49
+ };
50
+ var NotFoundError = class _NotFoundError extends RainfallError {
51
+ constructor(resource, identifier) {
52
+ super(
53
+ `${resource}${identifier ? ` '${identifier}'` : ""} not found`,
54
+ "NOT_FOUND_ERROR",
55
+ 404,
56
+ { resource, identifier }
57
+ );
58
+ this.name = "NotFoundError";
59
+ Object.setPrototypeOf(this, _NotFoundError.prototype);
60
+ }
61
+ };
62
+ var ServerError = class _ServerError extends RainfallError {
63
+ constructor(message = "Internal server error", statusCode = 500) {
64
+ super(message, "SERVER_ERROR", statusCode);
65
+ this.name = "ServerError";
66
+ Object.setPrototypeOf(this, _ServerError.prototype);
67
+ }
68
+ };
69
+ var TimeoutError = class _TimeoutError extends RainfallError {
70
+ constructor(timeoutMs) {
71
+ super(`Request timed out after ${timeoutMs}ms`, "TIMEOUT_ERROR", 408);
72
+ this.name = "TimeoutError";
73
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
74
+ }
75
+ };
76
+ var NetworkError = class _NetworkError extends RainfallError {
77
+ constructor(message = "Network error", details) {
78
+ super(message, "NETWORK_ERROR", void 0, details);
79
+ this.name = "NetworkError";
80
+ Object.setPrototypeOf(this, _NetworkError.prototype);
81
+ }
82
+ };
83
+ var ToolNotFoundError = class _ToolNotFoundError extends RainfallError {
84
+ constructor(toolId) {
85
+ super(`Tool '${toolId}' not found`, "TOOL_NOT_FOUND", 404, { toolId });
86
+ this.name = "ToolNotFoundError";
87
+ Object.setPrototypeOf(this, _ToolNotFoundError.prototype);
88
+ }
89
+ };
90
+ function parseErrorResponse(response, data) {
91
+ const statusCode = response.status;
92
+ if (statusCode === 429) {
93
+ const retryAfter = parseInt(response.headers.get("retry-after") || "60", 10);
94
+ const limit = parseInt(response.headers.get("x-ratelimit-limit") || "0", 10);
95
+ const remaining = parseInt(response.headers.get("x-ratelimit-remaining") || "0", 10);
96
+ const resetHeader = response.headers.get("x-ratelimit-reset");
97
+ const resetAt = resetHeader ? new Date(parseInt(resetHeader, 10) * 1e3) : void 0;
98
+ return new RateLimitError(
99
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Rate limit exceeded",
100
+ retryAfter,
101
+ limit,
102
+ remaining,
103
+ resetAt
104
+ );
105
+ }
106
+ switch (statusCode) {
107
+ case 401:
108
+ return new AuthenticationError(
109
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Invalid API key"
110
+ );
111
+ case 404:
112
+ return new NotFoundError(
113
+ typeof data === "object" && data && "resource" in data ? String(data.resource) : "Resource",
114
+ typeof data === "object" && data && "identifier" in data ? String(data.identifier) : void 0
115
+ );
116
+ case 400:
117
+ return new ValidationError(
118
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Invalid request",
119
+ typeof data === "object" && data && "details" in data ? data.details : void 0
120
+ );
121
+ case 500:
122
+ case 502:
123
+ case 503:
124
+ case 504:
125
+ return new ServerError(
126
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Server error",
127
+ statusCode
128
+ );
129
+ default:
130
+ return new RainfallError(
131
+ typeof data === "object" && data && "message" in data ? String(data.message) : `HTTP ${statusCode}`,
132
+ "UNKNOWN_ERROR",
133
+ statusCode,
134
+ typeof data === "object" ? data : void 0
135
+ );
136
+ }
137
+ }
138
+
139
+ // src/client.ts
140
+ var DEFAULT_BASE_URL = "https://olympic-api.pragma-digital.org/v1";
141
+ var DEFAULT_TIMEOUT = 3e4;
142
+ var DEFAULT_RETRIES = 3;
143
+ var DEFAULT_RETRY_DELAY = 1e3;
144
+ var RainfallClient = class {
145
+ apiKey;
146
+ baseUrl;
147
+ defaultTimeout;
148
+ defaultRetries;
149
+ defaultRetryDelay;
150
+ lastRateLimitInfo;
151
+ subscriberId;
152
+ constructor(config) {
153
+ this.apiKey = config.apiKey;
154
+ this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;
155
+ this.defaultTimeout = config.timeout || DEFAULT_TIMEOUT;
156
+ this.defaultRetries = config.retries ?? DEFAULT_RETRIES;
157
+ this.defaultRetryDelay = config.retryDelay || DEFAULT_RETRY_DELAY;
158
+ }
159
+ /**
160
+ * Get the last rate limit info from the API
161
+ */
162
+ getRateLimitInfo() {
163
+ return this.lastRateLimitInfo;
164
+ }
165
+ /**
166
+ * Make an authenticated request to the Rainfall API
167
+ */
168
+ async request(path, options = {}, requestOptions) {
169
+ const timeout = requestOptions?.timeout ?? this.defaultTimeout;
170
+ const maxRetries = requestOptions?.retries ?? this.defaultRetries;
171
+ const retryDelay = requestOptions?.retryDelay ?? this.defaultRetryDelay;
172
+ const url = `${this.baseUrl}${path}`;
173
+ const method = options.method || "GET";
174
+ let lastError;
175
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
176
+ try {
177
+ const controller = new AbortController();
178
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
179
+ const response = await fetch(url, {
180
+ method,
181
+ headers: {
182
+ "x-api-key": this.apiKey,
183
+ "Content-Type": "application/json",
184
+ "Accept": "application/json",
185
+ "X-Rainfall-SDK-Version": "0.1.0",
186
+ ...options.headers
187
+ },
188
+ body: options.body ? JSON.stringify(options.body) : void 0,
189
+ signal: controller.signal
190
+ });
191
+ clearTimeout(timeoutId);
192
+ const limit = response.headers.get("x-ratelimit-limit");
193
+ const remaining = response.headers.get("x-ratelimit-remaining");
194
+ const reset = response.headers.get("x-ratelimit-reset");
195
+ if (limit && remaining && reset) {
196
+ this.lastRateLimitInfo = {
197
+ limit: parseInt(limit, 10),
198
+ remaining: parseInt(remaining, 10),
199
+ resetAt: new Date(parseInt(reset, 10) * 1e3)
200
+ };
201
+ }
202
+ let data;
203
+ const contentType = response.headers.get("content-type");
204
+ if (contentType?.includes("application/json")) {
205
+ data = await response.json();
206
+ } else {
207
+ data = await response.text();
208
+ }
209
+ if (!response.ok) {
210
+ throw parseErrorResponse(response, data);
211
+ }
212
+ return data;
213
+ } catch (error) {
214
+ if (error instanceof RainfallError) {
215
+ if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
216
+ throw error;
217
+ }
218
+ if (error.statusCode === 401) {
219
+ throw error;
220
+ }
221
+ }
222
+ if (error instanceof Error && error.name === "AbortError") {
223
+ lastError = new TimeoutError(timeout);
224
+ } else if (error instanceof TypeError) {
225
+ lastError = new NetworkError(error.message);
226
+ } else {
227
+ lastError = error instanceof Error ? error : new Error(String(error));
228
+ }
229
+ if (attempt >= maxRetries) {
230
+ break;
231
+ }
232
+ const delay = retryDelay * Math.pow(2, attempt) + Math.random() * 1e3;
233
+ await this.sleep(delay);
234
+ }
235
+ }
236
+ throw lastError || new RainfallError("Request failed", "REQUEST_FAILED");
237
+ }
238
+ /**
239
+ * Execute a tool/node by ID
240
+ */
241
+ async executeTool(toolId, params, options) {
242
+ const subscriberId = await this.ensureSubscriberId();
243
+ const response = await this.request(`/olympic/subscribers/${subscriberId}/nodes/${toolId}`, {
244
+ method: "POST",
245
+ body: params || {}
246
+ }, options);
247
+ return response.result;
248
+ }
249
+ /**
250
+ * List all available tools
251
+ */
252
+ async listTools() {
253
+ const subscriberId = await this.ensureSubscriberId();
254
+ const result = await this.request(`/olympic/subscribers/${subscriberId}/nodes/_utils/node-descriptions`);
255
+ if (result.success && result.nodes) {
256
+ return Object.values(result.nodes);
257
+ }
258
+ const legacyResult = await this.request(`/olympic/subscribers/${subscriberId}/nodes/_utils/node-list`);
259
+ if (legacyResult.keys && Array.isArray(legacyResult.keys)) {
260
+ return legacyResult.keys.map((key) => ({
261
+ id: key,
262
+ name: key,
263
+ description: "",
264
+ category: "general"
265
+ }));
266
+ }
267
+ return legacyResult.nodes || [];
268
+ }
269
+ /**
270
+ * Get tool schema/parameters
271
+ */
272
+ async getToolSchema(toolId) {
273
+ const subscriberId = await this.ensureSubscriberId();
274
+ const response = await this.request(`/olympic/subscribers/${subscriberId}/nodes/${toolId}/params`);
275
+ return response.params;
276
+ }
277
+ /**
278
+ * Get subscriber info
279
+ */
280
+ async getMe() {
281
+ const result = await this.request("/olympic/subscribers/me");
282
+ if (result.subscriber?.id) {
283
+ this.subscriberId = result.subscriber.id;
284
+ }
285
+ const subscriber = result.subscriber;
286
+ return {
287
+ id: subscriber.id,
288
+ name: subscriber.name,
289
+ email: subscriber.google_id,
290
+ billingStatus: subscriber.billing_status,
291
+ plan: subscriber.billing_status,
292
+ usage: {
293
+ callsThisMonth: subscriber.metadata?.usage?.callsThisMonth ?? 0,
294
+ callsLimit: subscriber.metadata?.usage?.callsLimit ?? 5e3
295
+ }
296
+ };
297
+ }
298
+ /**
299
+ * Ensure we have a subscriber ID, fetching it if necessary
300
+ */
301
+ async ensureSubscriberId() {
302
+ if (this.subscriberId) {
303
+ return this.subscriberId;
304
+ }
305
+ const me = await this.getMe();
306
+ if (!me.id) {
307
+ throw new RainfallError("Failed to get subscriber ID", "NO_SUBSCRIBER_ID");
308
+ }
309
+ return me.id;
310
+ }
311
+ sleep(ms) {
312
+ return new Promise((resolve) => setTimeout(resolve, ms));
313
+ }
314
+ /**
315
+ * OpenAI-compatible chat completions with tool support
316
+ */
317
+ async chatCompletions(params) {
318
+ const { subscriber_id, ...body } = params;
319
+ if (body.stream) {
320
+ const url = `${this.baseUrl}/olympic/subscribers/${subscriber_id}/v1/chat/completions`;
321
+ const response = await fetch(url, {
322
+ method: "POST",
323
+ headers: {
324
+ "x-api-key": this.apiKey,
325
+ "Content-Type": "application/json",
326
+ "Accept": "text/event-stream"
327
+ },
328
+ body: JSON.stringify(body)
329
+ });
330
+ if (!response.ok) {
331
+ const error = await response.text();
332
+ throw new RainfallError(`Chat completions failed: ${error}`, "CHAT_ERROR");
333
+ }
334
+ if (!response.body) {
335
+ throw new RainfallError("No response body", "CHAT_ERROR");
336
+ }
337
+ return response.body;
338
+ }
339
+ return this.request(
340
+ `/olympic/subscribers/${subscriber_id}/v1/chat/completions`,
341
+ {
342
+ method: "POST",
343
+ body
344
+ }
345
+ );
346
+ }
347
+ /**
348
+ * List available models (OpenAI-compatible format)
349
+ */
350
+ async listModels(subscriberId) {
351
+ const sid = subscriberId || this.subscriberId || await this.ensureSubscriberId();
352
+ const result = await this.request(
353
+ `/olympic/subscribers/${sid}/v1/models`
354
+ );
355
+ return result.data || [];
356
+ }
357
+ };
358
+
359
+ // src/namespaces/integrations.ts
360
+ function createIntegrations(client) {
361
+ return new IntegrationsNamespace(client);
362
+ }
363
+ var IntegrationsNamespace = class {
364
+ constructor(client) {
365
+ this.client = client;
366
+ }
367
+ get github() {
368
+ return {
369
+ issues: {
370
+ create: (params) => this.client.executeTool("github-create-issue", params),
371
+ list: (params) => this.client.executeTool("github-list-issues", params),
372
+ get: (params) => this.client.executeTool("github-get-issue", params),
373
+ update: (params) => this.client.executeTool("github-update-issue", params),
374
+ addComment: (params) => this.client.executeTool("github-add-issue-comment", params)
375
+ },
376
+ repos: {
377
+ get: (params) => this.client.executeTool("github-get-repository", params),
378
+ listBranches: (params) => this.client.executeTool("github-list-branches", params)
379
+ },
380
+ pullRequests: {
381
+ list: (params) => this.client.executeTool("github-list-pull-requests", params),
382
+ get: (params) => this.client.executeTool("github-get-pull-request", params)
383
+ }
384
+ };
385
+ }
386
+ get notion() {
387
+ return {
388
+ pages: {
389
+ create: (params) => this.client.executeTool("notion-pages-create", params),
390
+ retrieve: (params) => this.client.executeTool("notion-pages-retrieve", params),
391
+ update: (params) => this.client.executeTool("notion-pages-update", params)
392
+ },
393
+ databases: {
394
+ query: (params) => this.client.executeTool("notion-databases-query", params),
395
+ retrieve: (params) => this.client.executeTool("notion-databases-retrieve", params)
396
+ },
397
+ blocks: {
398
+ appendChildren: (params) => this.client.executeTool("notion-blocks-append-children", params),
399
+ retrieveChildren: (params) => this.client.executeTool("notion-blocks-retrieve-children", params)
400
+ }
401
+ };
402
+ }
403
+ get linear() {
404
+ return {
405
+ issues: {
406
+ create: (params) => this.client.executeTool("linear-core-issueCreate", params),
407
+ list: (params) => this.client.executeTool("linear-core-issues", params),
408
+ get: (params) => this.client.executeTool("linear-core-issue", params),
409
+ update: (params) => this.client.executeTool("linear-core-issueUpdate", params),
410
+ archive: (params) => this.client.executeTool("linear-core-issueArchive", params)
411
+ },
412
+ teams: {
413
+ list: () => this.client.executeTool("linear-core-teams", {})
414
+ }
415
+ };
416
+ }
417
+ get slack() {
418
+ return {
419
+ messages: {
420
+ send: (params) => this.client.executeTool("slack-core-postMessage", params),
421
+ list: (params) => this.client.executeTool("slack-core-listMessages", params)
422
+ },
423
+ channels: {
424
+ list: () => this.client.executeTool("slack-core-listChannels", {})
425
+ },
426
+ users: {
427
+ list: () => this.client.executeTool("slack-core-listUsers", {})
428
+ },
429
+ reactions: {
430
+ add: (params) => this.client.executeTool("slack-core-addReaction", params)
431
+ }
432
+ };
433
+ }
434
+ get figma() {
435
+ return {
436
+ files: {
437
+ get: (params) => this.client.executeTool("figma-files-getFile", { fileKey: params.fileKey }),
438
+ getNodes: (params) => this.client.executeTool("figma-files-getFileNodes", { fileKey: params.fileKey, nodeIds: params.nodeIds }),
439
+ getImages: (params) => this.client.executeTool("figma-files-getFileImage", { fileKey: params.fileKey, nodeIds: params.nodeIds, format: params.format }),
440
+ getComments: (params) => this.client.executeTool("figma-comments-getFileComments", { fileKey: params.fileKey }),
441
+ postComment: (params) => this.client.executeTool("figma-comments-postComment", { fileKey: params.fileKey, message: params.message, nodeId: params.nodeId })
442
+ },
443
+ projects: {
444
+ list: (params) => this.client.executeTool("figma-projects-getTeamProjects", { teamId: params.teamId }),
445
+ getFiles: (params) => this.client.executeTool("figma-projects-getProjectFiles", { projectId: params.projectId })
446
+ }
447
+ };
448
+ }
449
+ get stripe() {
450
+ return {
451
+ customers: {
452
+ create: (params) => this.client.executeTool("stripe-customers-create", params),
453
+ retrieve: (params) => this.client.executeTool("stripe-customers-retrieve", { customerId: params.customerId }),
454
+ update: (params) => this.client.executeTool("stripe-customers-update", params),
455
+ listPaymentMethods: (params) => this.client.executeTool("stripe-customers-list-payment-methods", { customerId: params.customerId })
456
+ },
457
+ paymentIntents: {
458
+ create: (params) => this.client.executeTool("stripe-payment-intents-create", params),
459
+ retrieve: (params) => this.client.executeTool("stripe-payment-intents-retrieve", { paymentIntentId: params.paymentIntentId }),
460
+ confirm: (params) => this.client.executeTool("stripe-payment-intents-confirm", { paymentIntentId: params.paymentIntentId })
461
+ },
462
+ subscriptions: {
463
+ create: (params) => this.client.executeTool("stripe-subscriptions-create", params),
464
+ retrieve: (params) => this.client.executeTool("stripe-subscriptions-retrieve", { subscriptionId: params.subscriptionId }),
465
+ cancel: (params) => this.client.executeTool("stripe-subscriptions-cancel", { subscriptionId: params.subscriptionId })
466
+ }
467
+ };
468
+ }
469
+ };
470
+
471
+ // src/namespaces/memory.ts
472
+ function createMemory(client) {
473
+ return {
474
+ create: (params) => client.executeTool("memory-create", params),
475
+ get: (params) => client.executeTool("memory-get", { memoryId: params.memoryId }),
476
+ recall: (params) => client.executeTool("memory-recall", params),
477
+ list: (params) => client.executeTool("memory-list", params ?? {}),
478
+ update: (params) => client.executeTool("memory-update", params),
479
+ delete: (params) => client.executeTool("memory-delete", { memoryId: params.memoryId })
480
+ };
481
+ }
482
+
483
+ // src/namespaces/articles.ts
484
+ function createArticles(client) {
485
+ return {
486
+ search: (params) => client.executeTool("article-search", params),
487
+ create: (params) => client.executeTool("article-create", params),
488
+ createFromUrl: (params) => client.executeTool("article-create-from-url", params),
489
+ fetch: (params) => client.executeTool("article-fetch", params),
490
+ recent: (params) => client.executeTool("article-recent", params ?? {}),
491
+ relevant: (params) => client.executeTool("article-relevant-news", params),
492
+ summarize: (params) => client.executeTool("article-summarize", params),
493
+ extractTopics: (params) => client.executeTool("article-topic-extractor", params)
494
+ };
495
+ }
496
+
497
+ // src/namespaces/web.ts
498
+ function createWeb(client) {
499
+ return {
500
+ search: {
501
+ exa: (params) => client.executeTool("exa-web-search", params),
502
+ perplexity: (params) => client.executeTool("perplexity-search", params)
503
+ },
504
+ fetch: (params) => client.executeTool("web-fetch", params),
505
+ htmlToMarkdown: (params) => client.executeTool("html-to-markdown-converter", params),
506
+ extractHtml: (params) => client.executeTool("extract-html-selector", params)
507
+ };
508
+ }
509
+
510
+ // src/namespaces/ai.ts
511
+ function createAI(client) {
512
+ return {
513
+ embeddings: {
514
+ document: (params) => client.executeTool("jina-document-embedding", params),
515
+ query: (params) => client.executeTool("jina-query-embedding", params),
516
+ image: (params) => client.executeTool("jina-image-embedding", { image: params.imageBase64 })
517
+ },
518
+ image: {
519
+ generate: (params) => client.executeTool("image-generation", params)
520
+ },
521
+ ocr: (params) => client.executeTool("ocr-text-extraction", { image: params.imageBase64 }),
522
+ vision: (params) => client.executeTool("llama-scout-vision", { image: params.imageBase64, prompt: params.prompt }),
523
+ chat: (params) => client.executeTool("xai-chat-completions", params),
524
+ complete: (params) => client.executeTool("fim", params),
525
+ classify: (params) => client.executeTool("jina-document-classifier", params),
526
+ segment: (params) => client.executeTool("jina-text-segmenter", params),
527
+ /**
528
+ * OpenAI-compatible chat completions with full tool support
529
+ * This is the recommended method for multi-turn conversations with tools
530
+ */
531
+ chatCompletions: (params) => client.chatCompletions(params)
532
+ };
533
+ }
534
+
535
+ // src/namespaces/data.ts
536
+ function createData(client) {
537
+ return {
538
+ csv: {
539
+ query: (params) => client.executeTool("query-csv", params),
540
+ convert: (params) => client.executeTool("csv-convert", params)
541
+ },
542
+ scripts: {
543
+ create: (params) => client.executeTool("create-saved-script", params),
544
+ execute: (params) => client.executeTool("execute-saved-script", params),
545
+ list: () => client.executeTool("list-saved-scripts", {}),
546
+ update: (params) => client.executeTool("update-saved-script", params),
547
+ delete: (params) => client.executeTool("delete-saved-script", params)
548
+ },
549
+ similarity: {
550
+ search: (params) => client.executeTool("duck-db-similarity-search", params),
551
+ duckDbSearch: (params) => client.executeTool("duck-db-similarity-search", params)
552
+ }
553
+ };
554
+ }
555
+
556
+ // src/namespaces/utils.ts
557
+ function createUtils(client) {
558
+ return {
559
+ mermaid: (params) => client.executeTool("mermaid-diagram-generator", { mermaid: params.diagram }),
560
+ documentConvert: (params) => client.executeTool("document-format-converter", {
561
+ base64: `data:${params.mimeType};base64,${Buffer.from(params.document).toString("base64")}`,
562
+ format: params.format
563
+ }),
564
+ regex: {
565
+ match: (params) => client.executeTool("regex-match", params),
566
+ replace: (params) => client.executeTool("regex-replace", params)
567
+ },
568
+ jsonExtract: (params) => client.executeTool("json-extract", params),
569
+ digest: (params) => client.executeTool("digest-generator", { text: params.data }),
570
+ monteCarlo: (params) => client.executeTool("monte-carlo-simulation", params)
571
+ };
572
+ }
573
+
574
+ // src/sdk.ts
575
+ var Rainfall = class {
576
+ client;
577
+ _integrations;
578
+ _memory;
579
+ _articles;
580
+ _web;
581
+ _ai;
582
+ _data;
583
+ _utils;
584
+ constructor(config) {
585
+ this.client = new RainfallClient(config);
586
+ }
587
+ /**
588
+ * Integrations namespace - GitHub, Notion, Linear, Slack, Figma, Stripe
589
+ *
590
+ * @example
591
+ * ```typescript
592
+ * // GitHub
593
+ * await rainfall.integrations.github.issues.create({
594
+ * owner: 'facebook',
595
+ * repo: 'react',
596
+ * title: 'Bug report'
597
+ * });
598
+ *
599
+ * // Slack
600
+ * await rainfall.integrations.slack.messages.send({
601
+ * channelId: 'C123456',
602
+ * text: 'Hello team!'
603
+ * });
604
+ *
605
+ * // Linear
606
+ * const issues = await rainfall.integrations.linear.issues.list();
607
+ * ```
608
+ */
609
+ get integrations() {
610
+ if (!this._integrations) {
611
+ this._integrations = createIntegrations(this.client);
612
+ }
613
+ return this._integrations;
614
+ }
615
+ /**
616
+ * Memory namespace - Semantic memory storage and retrieval
617
+ *
618
+ * @example
619
+ * ```typescript
620
+ * // Store a memory
621
+ * await rainfall.memory.create({
622
+ * content: 'User prefers dark mode',
623
+ * keywords: ['preference', 'ui']
624
+ * });
625
+ *
626
+ * // Recall similar memories
627
+ * const memories = await rainfall.memory.recall({
628
+ * query: 'user preferences',
629
+ * topK: 5
630
+ * });
631
+ * ```
632
+ */
633
+ get memory() {
634
+ if (!this._memory) {
635
+ this._memory = createMemory(this.client);
636
+ }
637
+ return this._memory;
638
+ }
639
+ /**
640
+ * Articles namespace - News aggregation and article management
641
+ *
642
+ * @example
643
+ * ```typescript
644
+ * // Search news
645
+ * const articles = await rainfall.articles.search({
646
+ * query: 'artificial intelligence'
647
+ * });
648
+ *
649
+ * // Create from URL
650
+ * const article = await rainfall.articles.createFromUrl({
651
+ * url: 'https://example.com/article'
652
+ * });
653
+ *
654
+ * // Summarize
655
+ * const summary = await rainfall.articles.summarize({
656
+ * text: article.content
657
+ * });
658
+ * ```
659
+ */
660
+ get articles() {
661
+ if (!this._articles) {
662
+ this._articles = createArticles(this.client);
663
+ }
664
+ return this._articles;
665
+ }
666
+ /**
667
+ * Web namespace - Web search, scraping, and content extraction
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * // Search with Exa
672
+ * const results = await rainfall.web.search.exa({
673
+ * query: 'latest AI research'
674
+ * });
675
+ *
676
+ * // Fetch and convert
677
+ * const html = await rainfall.web.fetch({ url: 'https://example.com' });
678
+ * const markdown = await rainfall.web.htmlToMarkdown({ html });
679
+ *
680
+ * // Extract specific elements
681
+ * const links = await rainfall.web.extractHtml({
682
+ * html,
683
+ * selector: 'a[href]'
684
+ * });
685
+ * ```
686
+ */
687
+ get web() {
688
+ if (!this._web) {
689
+ this._web = createWeb(this.client);
690
+ }
691
+ return this._web;
692
+ }
693
+ /**
694
+ * AI namespace - Embeddings, image generation, OCR, vision, chat
695
+ *
696
+ * @example
697
+ * ```typescript
698
+ * // Generate embeddings
699
+ * const embedding = await rainfall.ai.embeddings.document({
700
+ * text: 'Hello world'
701
+ * });
702
+ *
703
+ * // Generate image
704
+ * const image = await rainfall.ai.image.generate({
705
+ * prompt: 'A serene mountain landscape'
706
+ * });
707
+ *
708
+ * // OCR
709
+ * const text = await rainfall.ai.ocr({ imageBase64: '...' });
710
+ *
711
+ * // Chat
712
+ * const response = await rainfall.ai.chat({
713
+ * messages: [{ role: 'user', content: 'Hello!' }]
714
+ * });
715
+ * ```
716
+ */
717
+ get ai() {
718
+ if (!this._ai) {
719
+ this._ai = createAI(this.client);
720
+ }
721
+ return this._ai;
722
+ }
723
+ /**
724
+ * Data namespace - CSV processing, scripts, similarity search
725
+ *
726
+ * @example
727
+ * ```typescript
728
+ * // Query CSV with SQL
729
+ * const results = await rainfall.data.csv.query({
730
+ * sql: 'SELECT * FROM data WHERE value > 100'
731
+ * });
732
+ *
733
+ * // Execute saved script
734
+ * const result = await rainfall.data.scripts.execute({
735
+ * name: 'my-script',
736
+ * params: { input: 'data' }
737
+ * });
738
+ * ```
739
+ */
740
+ get data() {
741
+ if (!this._data) {
742
+ this._data = createData(this.client);
743
+ }
744
+ return this._data;
745
+ }
746
+ /**
747
+ * Utils namespace - Mermaid diagrams, document conversion, regex, JSON extraction
748
+ *
749
+ * @example
750
+ * ```typescript
751
+ * // Generate diagram
752
+ * const diagram = await rainfall.utils.mermaid({
753
+ * diagram: 'graph TD; A-->B;'
754
+ * });
755
+ *
756
+ * // Convert document
757
+ * const pdf = await rainfall.utils.documentConvert({
758
+ * document: markdownContent,
759
+ * mimeType: 'text/markdown',
760
+ * format: 'pdf'
761
+ * });
762
+ *
763
+ * // Extract JSON from text
764
+ * const json = await rainfall.utils.jsonExtract({
765
+ * text: 'Here is some data: {"key": "value"}'
766
+ * });
767
+ * ```
768
+ */
769
+ get utils() {
770
+ if (!this._utils) {
771
+ this._utils = createUtils(this.client);
772
+ }
773
+ return this._utils;
774
+ }
775
+ /**
776
+ * Get the underlying HTTP client for advanced usage
777
+ */
778
+ getClient() {
779
+ return this.client;
780
+ }
781
+ /**
782
+ * List all available tools
783
+ */
784
+ async listTools() {
785
+ return this.client.listTools();
786
+ }
787
+ /**
788
+ * Get schema for a specific tool
789
+ */
790
+ async getToolSchema(toolId) {
791
+ return this.client.getToolSchema(toolId);
792
+ }
793
+ /**
794
+ * Execute any tool by ID (low-level access)
795
+ */
796
+ async executeTool(toolId, params) {
797
+ return this.client.executeTool(toolId, params);
798
+ }
799
+ /**
800
+ * Get current subscriber info and usage
801
+ */
802
+ async getMe() {
803
+ return this.client.getMe();
804
+ }
805
+ /**
806
+ * Get current rate limit info
807
+ */
808
+ getRateLimitInfo() {
809
+ return this.client.getRateLimitInfo();
810
+ }
811
+ /**
812
+ * OpenAI-compatible chat completions with tool support
813
+ *
814
+ * @example
815
+ * ```typescript
816
+ * // Simple chat
817
+ * const response = await rainfall.chatCompletions({
818
+ * subscriber_id: 'my-subscriber',
819
+ * messages: [{ role: 'user', content: 'Hello!' }],
820
+ * model: 'llama-3.3-70b-versatile'
821
+ * });
822
+ *
823
+ * // With tools
824
+ * const response = await rainfall.chatCompletions({
825
+ * subscriber_id: 'my-subscriber',
826
+ * messages: [{ role: 'user', content: 'Search for AI news' }],
827
+ * tools: [{ type: 'function', function: { name: 'web-search' } }],
828
+ * enable_stacked: true
829
+ * });
830
+ *
831
+ * // Streaming
832
+ * const stream = await rainfall.chatCompletions({
833
+ * subscriber_id: 'my-subscriber',
834
+ * messages: [{ role: 'user', content: 'Tell me a story' }],
835
+ * stream: true
836
+ * });
837
+ * ```
838
+ */
839
+ async chatCompletions(params) {
840
+ return this.client.chatCompletions(params);
841
+ }
842
+ /**
843
+ * List available models (OpenAI-compatible format)
844
+ *
845
+ * @example
846
+ * ```typescript
847
+ * const models = await rainfall.listModels();
848
+ * console.log(models); // [{ id: 'llama-3.3-70b-versatile', ... }]
849
+ * ```
850
+ */
851
+ async listModels(subscriberId) {
852
+ return this.client.listModels(subscriberId);
853
+ }
854
+ };
855
+
856
+ export {
857
+ RainfallError,
858
+ AuthenticationError,
859
+ RateLimitError,
860
+ ValidationError,
861
+ NotFoundError,
862
+ ServerError,
863
+ TimeoutError,
864
+ NetworkError,
865
+ ToolNotFoundError,
866
+ parseErrorResponse,
867
+ RainfallClient,
868
+ Rainfall
869
+ };