@rainfall-devkit/sdk 0.1.8 → 0.2.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 (39) 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-V5QWJVLC.mjs +662 -0
  5. package/dist/chunk-VDPKDC3R.mjs +869 -0
  6. package/dist/chunk-WOITG5TG.mjs +84 -0
  7. package/dist/cli/index.js +2799 -713
  8. package/dist/cli/index.mjs +354 -36
  9. package/dist/config-DDTQQBN7.mjs +14 -0
  10. package/dist/config-ZKNHII2A.mjs +8 -0
  11. package/dist/daemon/index.d.mts +136 -0
  12. package/dist/daemon/index.d.ts +136 -0
  13. package/dist/daemon/index.js +2473 -0
  14. package/dist/daemon/index.mjs +836 -0
  15. package/dist/errors-BMPseAnM.d.mts +47 -0
  16. package/dist/errors-BMPseAnM.d.ts +47 -0
  17. package/dist/errors-CZdRoYyw.d.ts +332 -0
  18. package/dist/errors-Chjq1Mev.d.mts +332 -0
  19. package/dist/index.d.mts +3 -1
  20. package/dist/index.d.ts +3 -1
  21. package/dist/index.js +759 -3
  22. package/dist/index.mjs +14 -2
  23. package/dist/listeners-BbYIaNCs.d.mts +372 -0
  24. package/dist/listeners-CP2A9J_2.d.ts +372 -0
  25. package/dist/listeners-CTRSofnm.d.mts +372 -0
  26. package/dist/listeners-CYI-YwIF.d.mts +372 -0
  27. package/dist/listeners-QJeEtLbV.d.ts +372 -0
  28. package/dist/listeners-hp0Ib2Ox.d.ts +372 -0
  29. package/dist/mcp.d.mts +3 -2
  30. package/dist/mcp.d.ts +3 -2
  31. package/dist/mcp.js +92 -1
  32. package/dist/mcp.mjs +1 -1
  33. package/dist/sdk-CJ9g5lFo.d.mts +772 -0
  34. package/dist/sdk-CJ9g5lFo.d.ts +772 -0
  35. package/dist/sdk-DD1OeGRJ.d.mts +871 -0
  36. package/dist/sdk-DD1OeGRJ.d.ts +871 -0
  37. package/dist/types-GnRAfH-h.d.mts +489 -0
  38. package/dist/types-GnRAfH-h.d.ts +489 -0
  39. package/package.json +14 -5
@@ -0,0 +1,2473 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // node_modules/tsup/assets/cjs_shims.js
34
+ var init_cjs_shims = __esm({
35
+ "node_modules/tsup/assets/cjs_shims.js"() {
36
+ "use strict";
37
+ }
38
+ });
39
+
40
+ // src/cli/config.ts
41
+ var config_exports = {};
42
+ __export(config_exports, {
43
+ getLLMConfig: () => getLLMConfig,
44
+ getProviderBaseUrl: () => getProviderBaseUrl,
45
+ isLocalProvider: () => isLocalProvider,
46
+ loadConfig: () => loadConfig,
47
+ saveConfig: () => saveConfig
48
+ });
49
+ function loadConfig() {
50
+ let config = {};
51
+ if ((0, import_fs.existsSync)(CONFIG_FILE)) {
52
+ try {
53
+ config = JSON.parse((0, import_fs.readFileSync)(CONFIG_FILE, "utf8"));
54
+ } catch {
55
+ config = {};
56
+ }
57
+ }
58
+ if (process.env.RAINFALL_API_KEY) {
59
+ config.apiKey = process.env.RAINFALL_API_KEY;
60
+ }
61
+ if (process.env.RAINFALL_BASE_URL) {
62
+ config.baseUrl = process.env.RAINFALL_BASE_URL;
63
+ }
64
+ if (!config.llm) {
65
+ config.llm = { provider: "rainfall" };
66
+ }
67
+ if (process.env.OPENAI_API_KEY) {
68
+ config.llm.provider = config.llm.provider || "openai";
69
+ config.llm.apiKey = process.env.OPENAI_API_KEY;
70
+ }
71
+ if (process.env.ANTHROPIC_API_KEY) {
72
+ config.llm.provider = "anthropic";
73
+ config.llm.apiKey = process.env.ANTHROPIC_API_KEY;
74
+ }
75
+ if (process.env.OLLAMA_HOST || process.env.OLLAMA_URL) {
76
+ config.llm.provider = "ollama";
77
+ config.llm.baseUrl = process.env.OLLAMA_HOST || process.env.OLLAMA_URL;
78
+ }
79
+ if (process.env.LLM_MODEL) {
80
+ config.llm.model = process.env.LLM_MODEL;
81
+ }
82
+ return config;
83
+ }
84
+ function saveConfig(config) {
85
+ if (!(0, import_fs.existsSync)(CONFIG_DIR)) {
86
+ (0, import_fs.mkdirSync)(CONFIG_DIR, { recursive: true });
87
+ }
88
+ (0, import_fs.writeFileSync)(CONFIG_FILE, JSON.stringify(config, null, 2));
89
+ }
90
+ function getLLMConfig(config) {
91
+ const defaults = {
92
+ provider: "rainfall",
93
+ apiKey: config.apiKey || "",
94
+ baseUrl: config.baseUrl || "https://api.rainfall.com",
95
+ model: "llama-3.3-70b-versatile",
96
+ options: {}
97
+ };
98
+ return { ...defaults, ...config.llm };
99
+ }
100
+ function isLocalProvider(config) {
101
+ return config.llm?.provider === "ollama" || config.llm?.provider === "local";
102
+ }
103
+ function getProviderBaseUrl(config) {
104
+ const provider = config.llm?.provider || "rainfall";
105
+ switch (provider) {
106
+ case "openai":
107
+ return config.llm?.baseUrl || "https://api.openai.com/v1";
108
+ case "anthropic":
109
+ return config.llm?.baseUrl || "https://api.anthropic.com/v1";
110
+ case "ollama":
111
+ return config.llm?.baseUrl || "http://localhost:11434/v1";
112
+ case "local":
113
+ return config.llm?.baseUrl || "http://localhost:1234/v1";
114
+ case "rainfall":
115
+ default:
116
+ return config.baseUrl || "https://api.rainfall.com";
117
+ }
118
+ }
119
+ var import_fs, import_path, import_os, CONFIG_DIR, CONFIG_FILE;
120
+ var init_config = __esm({
121
+ "src/cli/config.ts"() {
122
+ "use strict";
123
+ init_cjs_shims();
124
+ import_fs = require("fs");
125
+ import_path = require("path");
126
+ import_os = require("os");
127
+ CONFIG_DIR = (0, import_path.join)((0, import_os.homedir)(), ".rainfall");
128
+ CONFIG_FILE = (0, import_path.join)(CONFIG_DIR, "config.json");
129
+ }
130
+ });
131
+
132
+ // src/daemon/index.ts
133
+ var daemon_exports = {};
134
+ __export(daemon_exports, {
135
+ RainfallDaemon: () => RainfallDaemon,
136
+ getDaemonInstance: () => getDaemonInstance,
137
+ getDaemonStatus: () => getDaemonStatus,
138
+ startDaemon: () => startDaemon,
139
+ stopDaemon: () => stopDaemon
140
+ });
141
+ module.exports = __toCommonJS(daemon_exports);
142
+ init_cjs_shims();
143
+ var import_ws = require("ws");
144
+ var import_express = __toESM(require("express"));
145
+
146
+ // src/sdk.ts
147
+ init_cjs_shims();
148
+
149
+ // src/client.ts
150
+ init_cjs_shims();
151
+
152
+ // src/errors.ts
153
+ init_cjs_shims();
154
+ var RainfallError = class _RainfallError extends Error {
155
+ constructor(message, code, statusCode, details) {
156
+ super(message);
157
+ this.code = code;
158
+ this.statusCode = statusCode;
159
+ this.details = details;
160
+ this.name = "RainfallError";
161
+ Object.setPrototypeOf(this, _RainfallError.prototype);
162
+ }
163
+ toJSON() {
164
+ return {
165
+ name: this.name,
166
+ code: this.code,
167
+ message: this.message,
168
+ statusCode: this.statusCode,
169
+ details: this.details
170
+ };
171
+ }
172
+ };
173
+ var AuthenticationError = class _AuthenticationError extends RainfallError {
174
+ constructor(message = "Invalid API key", details) {
175
+ super(message, "AUTHENTICATION_ERROR", 401, details);
176
+ this.name = "AuthenticationError";
177
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
178
+ }
179
+ };
180
+ var RateLimitError = class _RateLimitError extends RainfallError {
181
+ retryAfter;
182
+ limit;
183
+ remaining;
184
+ resetAt;
185
+ constructor(message = "Rate limit exceeded", retryAfter = 60, limit = 0, remaining = 0, resetAt) {
186
+ super(message, "RATE_LIMIT_ERROR", 429, { retryAfter, limit, remaining });
187
+ this.name = "RateLimitError";
188
+ this.retryAfter = retryAfter;
189
+ this.limit = limit;
190
+ this.remaining = remaining;
191
+ this.resetAt = resetAt || new Date(Date.now() + retryAfter * 1e3);
192
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
193
+ }
194
+ };
195
+ var ValidationError = class _ValidationError extends RainfallError {
196
+ constructor(message, details) {
197
+ super(message, "VALIDATION_ERROR", 400, details);
198
+ this.name = "ValidationError";
199
+ Object.setPrototypeOf(this, _ValidationError.prototype);
200
+ }
201
+ };
202
+ var NotFoundError = class _NotFoundError extends RainfallError {
203
+ constructor(resource, identifier) {
204
+ super(
205
+ `${resource}${identifier ? ` '${identifier}'` : ""} not found`,
206
+ "NOT_FOUND_ERROR",
207
+ 404,
208
+ { resource, identifier }
209
+ );
210
+ this.name = "NotFoundError";
211
+ Object.setPrototypeOf(this, _NotFoundError.prototype);
212
+ }
213
+ };
214
+ var ServerError = class _ServerError extends RainfallError {
215
+ constructor(message = "Internal server error", statusCode = 500) {
216
+ super(message, "SERVER_ERROR", statusCode);
217
+ this.name = "ServerError";
218
+ Object.setPrototypeOf(this, _ServerError.prototype);
219
+ }
220
+ };
221
+ var TimeoutError = class _TimeoutError extends RainfallError {
222
+ constructor(timeoutMs) {
223
+ super(`Request timed out after ${timeoutMs}ms`, "TIMEOUT_ERROR", 408);
224
+ this.name = "TimeoutError";
225
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
226
+ }
227
+ };
228
+ var NetworkError = class _NetworkError extends RainfallError {
229
+ constructor(message = "Network error", details) {
230
+ super(message, "NETWORK_ERROR", void 0, details);
231
+ this.name = "NetworkError";
232
+ Object.setPrototypeOf(this, _NetworkError.prototype);
233
+ }
234
+ };
235
+ function parseErrorResponse(response, data) {
236
+ const statusCode = response.status;
237
+ if (statusCode === 429) {
238
+ const retryAfter = parseInt(response.headers.get("retry-after") || "60", 10);
239
+ const limit = parseInt(response.headers.get("x-ratelimit-limit") || "0", 10);
240
+ const remaining = parseInt(response.headers.get("x-ratelimit-remaining") || "0", 10);
241
+ const resetHeader = response.headers.get("x-ratelimit-reset");
242
+ const resetAt = resetHeader ? new Date(parseInt(resetHeader, 10) * 1e3) : void 0;
243
+ return new RateLimitError(
244
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Rate limit exceeded",
245
+ retryAfter,
246
+ limit,
247
+ remaining,
248
+ resetAt
249
+ );
250
+ }
251
+ switch (statusCode) {
252
+ case 401:
253
+ return new AuthenticationError(
254
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Invalid API key"
255
+ );
256
+ case 404:
257
+ return new NotFoundError(
258
+ typeof data === "object" && data && "resource" in data ? String(data.resource) : "Resource",
259
+ typeof data === "object" && data && "identifier" in data ? String(data.identifier) : void 0
260
+ );
261
+ case 400:
262
+ return new ValidationError(
263
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Invalid request",
264
+ typeof data === "object" && data && "details" in data ? data.details : void 0
265
+ );
266
+ case 500:
267
+ case 502:
268
+ case 503:
269
+ case 504:
270
+ return new ServerError(
271
+ typeof data === "object" && data && "message" in data ? String(data.message) : "Server error",
272
+ statusCode
273
+ );
274
+ default:
275
+ return new RainfallError(
276
+ typeof data === "object" && data && "message" in data ? String(data.message) : `HTTP ${statusCode}`,
277
+ "UNKNOWN_ERROR",
278
+ statusCode,
279
+ typeof data === "object" ? data : void 0
280
+ );
281
+ }
282
+ }
283
+
284
+ // src/client.ts
285
+ var DEFAULT_BASE_URL = "https://olympic-api.pragma-digital.org/v1";
286
+ var DEFAULT_TIMEOUT = 3e4;
287
+ var DEFAULT_RETRIES = 3;
288
+ var DEFAULT_RETRY_DELAY = 1e3;
289
+ var RainfallClient = class {
290
+ apiKey;
291
+ baseUrl;
292
+ defaultTimeout;
293
+ defaultRetries;
294
+ defaultRetryDelay;
295
+ lastRateLimitInfo;
296
+ subscriberId;
297
+ constructor(config) {
298
+ this.apiKey = config.apiKey;
299
+ this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;
300
+ this.defaultTimeout = config.timeout || DEFAULT_TIMEOUT;
301
+ this.defaultRetries = config.retries ?? DEFAULT_RETRIES;
302
+ this.defaultRetryDelay = config.retryDelay || DEFAULT_RETRY_DELAY;
303
+ }
304
+ /**
305
+ * Get the last rate limit info from the API
306
+ */
307
+ getRateLimitInfo() {
308
+ return this.lastRateLimitInfo;
309
+ }
310
+ /**
311
+ * Make an authenticated request to the Rainfall API
312
+ */
313
+ async request(path, options = {}, requestOptions) {
314
+ const timeout = requestOptions?.timeout ?? this.defaultTimeout;
315
+ const maxRetries = requestOptions?.retries ?? this.defaultRetries;
316
+ const retryDelay = requestOptions?.retryDelay ?? this.defaultRetryDelay;
317
+ const url = `${this.baseUrl}${path}`;
318
+ const method = options.method || "GET";
319
+ let lastError;
320
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
321
+ try {
322
+ const controller = new AbortController();
323
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
324
+ const response = await fetch(url, {
325
+ method,
326
+ headers: {
327
+ "x-api-key": this.apiKey,
328
+ "Content-Type": "application/json",
329
+ "Accept": "application/json",
330
+ "X-Rainfall-SDK-Version": "0.1.0",
331
+ ...options.headers
332
+ },
333
+ body: options.body ? JSON.stringify(options.body) : void 0,
334
+ signal: controller.signal
335
+ });
336
+ clearTimeout(timeoutId);
337
+ const limit = response.headers.get("x-ratelimit-limit");
338
+ const remaining = response.headers.get("x-ratelimit-remaining");
339
+ const reset = response.headers.get("x-ratelimit-reset");
340
+ if (limit && remaining && reset) {
341
+ this.lastRateLimitInfo = {
342
+ limit: parseInt(limit, 10),
343
+ remaining: parseInt(remaining, 10),
344
+ resetAt: new Date(parseInt(reset, 10) * 1e3)
345
+ };
346
+ }
347
+ let data;
348
+ const contentType = response.headers.get("content-type");
349
+ if (contentType?.includes("application/json")) {
350
+ data = await response.json();
351
+ } else {
352
+ data = await response.text();
353
+ }
354
+ if (!response.ok) {
355
+ throw parseErrorResponse(response, data);
356
+ }
357
+ return data;
358
+ } catch (error) {
359
+ if (error instanceof RainfallError) {
360
+ if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
361
+ throw error;
362
+ }
363
+ if (error.statusCode === 401) {
364
+ throw error;
365
+ }
366
+ }
367
+ if (error instanceof Error && error.name === "AbortError") {
368
+ lastError = new TimeoutError(timeout);
369
+ } else if (error instanceof TypeError) {
370
+ lastError = new NetworkError(error.message);
371
+ } else {
372
+ lastError = error instanceof Error ? error : new Error(String(error));
373
+ }
374
+ if (attempt >= maxRetries) {
375
+ break;
376
+ }
377
+ const delay = retryDelay * Math.pow(2, attempt) + Math.random() * 1e3;
378
+ await this.sleep(delay);
379
+ }
380
+ }
381
+ throw lastError || new RainfallError("Request failed", "REQUEST_FAILED");
382
+ }
383
+ /**
384
+ * Execute a tool/node by ID
385
+ */
386
+ async executeTool(toolId, params, options) {
387
+ const subscriberId = await this.ensureSubscriberId();
388
+ const response = await this.request(`/olympic/subscribers/${subscriberId}/nodes/${toolId}`, {
389
+ method: "POST",
390
+ body: params || {}
391
+ }, options);
392
+ return response.result;
393
+ }
394
+ /**
395
+ * List all available tools
396
+ */
397
+ async listTools() {
398
+ const subscriberId = await this.ensureSubscriberId();
399
+ const result = await this.request(`/olympic/subscribers/${subscriberId}/nodes/_utils/node-descriptions`);
400
+ if (result.success && result.nodes) {
401
+ return Object.values(result.nodes);
402
+ }
403
+ const legacyResult = await this.request(`/olympic/subscribers/${subscriberId}/nodes/_utils/node-list`);
404
+ if (legacyResult.keys && Array.isArray(legacyResult.keys)) {
405
+ return legacyResult.keys.map((key) => ({
406
+ id: key,
407
+ name: key,
408
+ description: "",
409
+ category: "general"
410
+ }));
411
+ }
412
+ return legacyResult.nodes || [];
413
+ }
414
+ /**
415
+ * Get tool schema/parameters
416
+ */
417
+ async getToolSchema(toolId) {
418
+ const subscriberId = await this.ensureSubscriberId();
419
+ const response = await this.request(`/olympic/subscribers/${subscriberId}/nodes/${toolId}/params`);
420
+ return response.params;
421
+ }
422
+ /**
423
+ * Get subscriber info
424
+ */
425
+ async getMe() {
426
+ const result = await this.request("/olympic/subscribers/me");
427
+ if (result.subscriber?.id) {
428
+ this.subscriberId = result.subscriber.id;
429
+ }
430
+ const subscriber = result.subscriber;
431
+ return {
432
+ id: subscriber.id,
433
+ name: subscriber.name,
434
+ email: subscriber.google_id,
435
+ billingStatus: subscriber.billing_status,
436
+ plan: subscriber.billing_status,
437
+ usage: {
438
+ callsThisMonth: subscriber.metadata?.usage?.callsThisMonth ?? 0,
439
+ callsLimit: subscriber.metadata?.usage?.callsLimit ?? 5e3
440
+ }
441
+ };
442
+ }
443
+ /**
444
+ * Ensure we have a subscriber ID, fetching it if necessary
445
+ */
446
+ async ensureSubscriberId() {
447
+ if (this.subscriberId) {
448
+ return this.subscriberId;
449
+ }
450
+ const me = await this.getMe();
451
+ if (!me.id) {
452
+ throw new RainfallError("Failed to get subscriber ID", "NO_SUBSCRIBER_ID");
453
+ }
454
+ return me.id;
455
+ }
456
+ sleep(ms) {
457
+ return new Promise((resolve) => setTimeout(resolve, ms));
458
+ }
459
+ /**
460
+ * OpenAI-compatible chat completions with tool support
461
+ */
462
+ async chatCompletions(params) {
463
+ const { subscriber_id, ...body } = params;
464
+ if (body.stream) {
465
+ const url = `${this.baseUrl}/olympic/subscribers/${subscriber_id}/v1/chat/completions`;
466
+ const response = await fetch(url, {
467
+ method: "POST",
468
+ headers: {
469
+ "x-api-key": this.apiKey,
470
+ "Content-Type": "application/json",
471
+ "Accept": "text/event-stream"
472
+ },
473
+ body: JSON.stringify(body)
474
+ });
475
+ if (!response.ok) {
476
+ const error = await response.text();
477
+ throw new RainfallError(`Chat completions failed: ${error}`, "CHAT_ERROR");
478
+ }
479
+ if (!response.body) {
480
+ throw new RainfallError("No response body", "CHAT_ERROR");
481
+ }
482
+ return response.body;
483
+ }
484
+ return this.request(
485
+ `/olympic/subscribers/${subscriber_id}/v1/chat/completions`,
486
+ {
487
+ method: "POST",
488
+ body
489
+ }
490
+ );
491
+ }
492
+ /**
493
+ * List available models (OpenAI-compatible format)
494
+ */
495
+ async listModels(subscriberId) {
496
+ const sid = subscriberId || this.subscriberId || await this.ensureSubscriberId();
497
+ const result = await this.request(
498
+ `/olympic/subscribers/${sid}/v1/models`
499
+ );
500
+ return result.data || [];
501
+ }
502
+ };
503
+
504
+ // src/namespaces/integrations.ts
505
+ init_cjs_shims();
506
+ function createIntegrations(client) {
507
+ return new IntegrationsNamespace(client);
508
+ }
509
+ var IntegrationsNamespace = class {
510
+ constructor(client) {
511
+ this.client = client;
512
+ }
513
+ get github() {
514
+ return {
515
+ issues: {
516
+ create: (params) => this.client.executeTool("github-create-issue", params),
517
+ list: (params) => this.client.executeTool("github-list-issues", params),
518
+ get: (params) => this.client.executeTool("github-get-issue", params),
519
+ update: (params) => this.client.executeTool("github-update-issue", params),
520
+ addComment: (params) => this.client.executeTool("github-add-issue-comment", params)
521
+ },
522
+ repos: {
523
+ get: (params) => this.client.executeTool("github-get-repository", params),
524
+ listBranches: (params) => this.client.executeTool("github-list-branches", params)
525
+ },
526
+ pullRequests: {
527
+ list: (params) => this.client.executeTool("github-list-pull-requests", params),
528
+ get: (params) => this.client.executeTool("github-get-pull-request", params)
529
+ }
530
+ };
531
+ }
532
+ get notion() {
533
+ return {
534
+ pages: {
535
+ create: (params) => this.client.executeTool("notion-pages-create", params),
536
+ retrieve: (params) => this.client.executeTool("notion-pages-retrieve", params),
537
+ update: (params) => this.client.executeTool("notion-pages-update", params)
538
+ },
539
+ databases: {
540
+ query: (params) => this.client.executeTool("notion-databases-query", params),
541
+ retrieve: (params) => this.client.executeTool("notion-databases-retrieve", params)
542
+ },
543
+ blocks: {
544
+ appendChildren: (params) => this.client.executeTool("notion-blocks-append-children", params),
545
+ retrieveChildren: (params) => this.client.executeTool("notion-blocks-retrieve-children", params)
546
+ }
547
+ };
548
+ }
549
+ get linear() {
550
+ return {
551
+ issues: {
552
+ create: (params) => this.client.executeTool("linear-core-issueCreate", params),
553
+ list: (params) => this.client.executeTool("linear-core-issues", params),
554
+ get: (params) => this.client.executeTool("linear-core-issue", params),
555
+ update: (params) => this.client.executeTool("linear-core-issueUpdate", params),
556
+ archive: (params) => this.client.executeTool("linear-core-issueArchive", params)
557
+ },
558
+ teams: {
559
+ list: () => this.client.executeTool("linear-core-teams", {})
560
+ }
561
+ };
562
+ }
563
+ get slack() {
564
+ return {
565
+ messages: {
566
+ send: (params) => this.client.executeTool("slack-core-postMessage", params),
567
+ list: (params) => this.client.executeTool("slack-core-listMessages", params)
568
+ },
569
+ channels: {
570
+ list: () => this.client.executeTool("slack-core-listChannels", {})
571
+ },
572
+ users: {
573
+ list: () => this.client.executeTool("slack-core-listUsers", {})
574
+ },
575
+ reactions: {
576
+ add: (params) => this.client.executeTool("slack-core-addReaction", params)
577
+ }
578
+ };
579
+ }
580
+ get figma() {
581
+ return {
582
+ files: {
583
+ get: (params) => this.client.executeTool("figma-files-getFile", { fileKey: params.fileKey }),
584
+ getNodes: (params) => this.client.executeTool("figma-files-getFileNodes", { fileKey: params.fileKey, nodeIds: params.nodeIds }),
585
+ getImages: (params) => this.client.executeTool("figma-files-getFileImage", { fileKey: params.fileKey, nodeIds: params.nodeIds, format: params.format }),
586
+ getComments: (params) => this.client.executeTool("figma-comments-getFileComments", { fileKey: params.fileKey }),
587
+ postComment: (params) => this.client.executeTool("figma-comments-postComment", { fileKey: params.fileKey, message: params.message, nodeId: params.nodeId })
588
+ },
589
+ projects: {
590
+ list: (params) => this.client.executeTool("figma-projects-getTeamProjects", { teamId: params.teamId }),
591
+ getFiles: (params) => this.client.executeTool("figma-projects-getProjectFiles", { projectId: params.projectId })
592
+ }
593
+ };
594
+ }
595
+ get stripe() {
596
+ return {
597
+ customers: {
598
+ create: (params) => this.client.executeTool("stripe-customers-create", params),
599
+ retrieve: (params) => this.client.executeTool("stripe-customers-retrieve", { customerId: params.customerId }),
600
+ update: (params) => this.client.executeTool("stripe-customers-update", params),
601
+ listPaymentMethods: (params) => this.client.executeTool("stripe-customers-list-payment-methods", { customerId: params.customerId })
602
+ },
603
+ paymentIntents: {
604
+ create: (params) => this.client.executeTool("stripe-payment-intents-create", params),
605
+ retrieve: (params) => this.client.executeTool("stripe-payment-intents-retrieve", { paymentIntentId: params.paymentIntentId }),
606
+ confirm: (params) => this.client.executeTool("stripe-payment-intents-confirm", { paymentIntentId: params.paymentIntentId })
607
+ },
608
+ subscriptions: {
609
+ create: (params) => this.client.executeTool("stripe-subscriptions-create", params),
610
+ retrieve: (params) => this.client.executeTool("stripe-subscriptions-retrieve", { subscriptionId: params.subscriptionId }),
611
+ cancel: (params) => this.client.executeTool("stripe-subscriptions-cancel", { subscriptionId: params.subscriptionId })
612
+ }
613
+ };
614
+ }
615
+ };
616
+
617
+ // src/namespaces/memory.ts
618
+ init_cjs_shims();
619
+ function createMemory(client) {
620
+ return {
621
+ create: (params) => client.executeTool("memory-create", params),
622
+ get: (params) => client.executeTool("memory-get", { memoryId: params.memoryId }),
623
+ recall: (params) => client.executeTool("memory-recall", params),
624
+ list: (params) => client.executeTool("memory-list", params ?? {}),
625
+ update: (params) => client.executeTool("memory-update", params),
626
+ delete: (params) => client.executeTool("memory-delete", { memoryId: params.memoryId })
627
+ };
628
+ }
629
+
630
+ // src/namespaces/articles.ts
631
+ init_cjs_shims();
632
+ function createArticles(client) {
633
+ return {
634
+ search: (params) => client.executeTool("article-search", params),
635
+ create: (params) => client.executeTool("article-create", params),
636
+ createFromUrl: (params) => client.executeTool("article-create-from-url", params),
637
+ fetch: (params) => client.executeTool("article-fetch", params),
638
+ recent: (params) => client.executeTool("article-recent", params ?? {}),
639
+ relevant: (params) => client.executeTool("article-relevant-news", params),
640
+ summarize: (params) => client.executeTool("article-summarize", params),
641
+ extractTopics: (params) => client.executeTool("article-topic-extractor", params)
642
+ };
643
+ }
644
+
645
+ // src/namespaces/web.ts
646
+ init_cjs_shims();
647
+ function createWeb(client) {
648
+ return {
649
+ search: {
650
+ exa: (params) => client.executeTool("exa-web-search", params),
651
+ perplexity: (params) => client.executeTool("perplexity-search", params)
652
+ },
653
+ fetch: (params) => client.executeTool("web-fetch", params),
654
+ htmlToMarkdown: (params) => client.executeTool("html-to-markdown-converter", params),
655
+ extractHtml: (params) => client.executeTool("extract-html-selector", params)
656
+ };
657
+ }
658
+
659
+ // src/namespaces/ai.ts
660
+ init_cjs_shims();
661
+ function createAI(client) {
662
+ return {
663
+ embeddings: {
664
+ document: (params) => client.executeTool("jina-document-embedding", params),
665
+ query: (params) => client.executeTool("jina-query-embedding", params),
666
+ image: (params) => client.executeTool("jina-image-embedding", { image: params.imageBase64 })
667
+ },
668
+ image: {
669
+ generate: (params) => client.executeTool("image-generation", params)
670
+ },
671
+ ocr: (params) => client.executeTool("ocr-text-extraction", { image: params.imageBase64 }),
672
+ vision: (params) => client.executeTool("llama-scout-vision", { image: params.imageBase64, prompt: params.prompt }),
673
+ chat: (params) => client.executeTool("xai-chat-completions", params),
674
+ complete: (params) => client.executeTool("fim", params),
675
+ classify: (params) => client.executeTool("jina-document-classifier", params),
676
+ segment: (params) => client.executeTool("jina-text-segmenter", params),
677
+ /**
678
+ * OpenAI-compatible chat completions with full tool support
679
+ * This is the recommended method for multi-turn conversations with tools
680
+ */
681
+ chatCompletions: (params) => client.chatCompletions(params)
682
+ };
683
+ }
684
+
685
+ // src/namespaces/data.ts
686
+ init_cjs_shims();
687
+ function createData(client) {
688
+ return {
689
+ csv: {
690
+ query: (params) => client.executeTool("query-csv", params),
691
+ convert: (params) => client.executeTool("csv-convert", params)
692
+ },
693
+ scripts: {
694
+ create: (params) => client.executeTool("create-saved-script", params),
695
+ execute: (params) => client.executeTool("execute-saved-script", params),
696
+ list: () => client.executeTool("list-saved-scripts", {}),
697
+ update: (params) => client.executeTool("update-saved-script", params),
698
+ delete: (params) => client.executeTool("delete-saved-script", params)
699
+ },
700
+ similarity: {
701
+ search: (params) => client.executeTool("duck-db-similarity-search", params),
702
+ duckDbSearch: (params) => client.executeTool("duck-db-similarity-search", params)
703
+ }
704
+ };
705
+ }
706
+
707
+ // src/namespaces/utils.ts
708
+ init_cjs_shims();
709
+ function createUtils(client) {
710
+ return {
711
+ mermaid: (params) => client.executeTool("mermaid-diagram-generator", { mermaid: params.diagram }),
712
+ documentConvert: (params) => client.executeTool("document-format-converter", {
713
+ base64: `data:${params.mimeType};base64,${Buffer.from(params.document).toString("base64")}`,
714
+ format: params.format
715
+ }),
716
+ regex: {
717
+ match: (params) => client.executeTool("regex-match", params),
718
+ replace: (params) => client.executeTool("regex-replace", params)
719
+ },
720
+ jsonExtract: (params) => client.executeTool("json-extract", params),
721
+ digest: (params) => client.executeTool("digest-generator", { text: params.data }),
722
+ monteCarlo: (params) => client.executeTool("monte-carlo-simulation", params)
723
+ };
724
+ }
725
+
726
+ // src/sdk.ts
727
+ var Rainfall = class {
728
+ client;
729
+ _integrations;
730
+ _memory;
731
+ _articles;
732
+ _web;
733
+ _ai;
734
+ _data;
735
+ _utils;
736
+ constructor(config) {
737
+ this.client = new RainfallClient(config);
738
+ }
739
+ /**
740
+ * Integrations namespace - GitHub, Notion, Linear, Slack, Figma, Stripe
741
+ *
742
+ * @example
743
+ * ```typescript
744
+ * // GitHub
745
+ * await rainfall.integrations.github.issues.create({
746
+ * owner: 'facebook',
747
+ * repo: 'react',
748
+ * title: 'Bug report'
749
+ * });
750
+ *
751
+ * // Slack
752
+ * await rainfall.integrations.slack.messages.send({
753
+ * channelId: 'C123456',
754
+ * text: 'Hello team!'
755
+ * });
756
+ *
757
+ * // Linear
758
+ * const issues = await rainfall.integrations.linear.issues.list();
759
+ * ```
760
+ */
761
+ get integrations() {
762
+ if (!this._integrations) {
763
+ this._integrations = createIntegrations(this.client);
764
+ }
765
+ return this._integrations;
766
+ }
767
+ /**
768
+ * Memory namespace - Semantic memory storage and retrieval
769
+ *
770
+ * @example
771
+ * ```typescript
772
+ * // Store a memory
773
+ * await rainfall.memory.create({
774
+ * content: 'User prefers dark mode',
775
+ * keywords: ['preference', 'ui']
776
+ * });
777
+ *
778
+ * // Recall similar memories
779
+ * const memories = await rainfall.memory.recall({
780
+ * query: 'user preferences',
781
+ * topK: 5
782
+ * });
783
+ * ```
784
+ */
785
+ get memory() {
786
+ if (!this._memory) {
787
+ this._memory = createMemory(this.client);
788
+ }
789
+ return this._memory;
790
+ }
791
+ /**
792
+ * Articles namespace - News aggregation and article management
793
+ *
794
+ * @example
795
+ * ```typescript
796
+ * // Search news
797
+ * const articles = await rainfall.articles.search({
798
+ * query: 'artificial intelligence'
799
+ * });
800
+ *
801
+ * // Create from URL
802
+ * const article = await rainfall.articles.createFromUrl({
803
+ * url: 'https://example.com/article'
804
+ * });
805
+ *
806
+ * // Summarize
807
+ * const summary = await rainfall.articles.summarize({
808
+ * text: article.content
809
+ * });
810
+ * ```
811
+ */
812
+ get articles() {
813
+ if (!this._articles) {
814
+ this._articles = createArticles(this.client);
815
+ }
816
+ return this._articles;
817
+ }
818
+ /**
819
+ * Web namespace - Web search, scraping, and content extraction
820
+ *
821
+ * @example
822
+ * ```typescript
823
+ * // Search with Exa
824
+ * const results = await rainfall.web.search.exa({
825
+ * query: 'latest AI research'
826
+ * });
827
+ *
828
+ * // Fetch and convert
829
+ * const html = await rainfall.web.fetch({ url: 'https://example.com' });
830
+ * const markdown = await rainfall.web.htmlToMarkdown({ html });
831
+ *
832
+ * // Extract specific elements
833
+ * const links = await rainfall.web.extractHtml({
834
+ * html,
835
+ * selector: 'a[href]'
836
+ * });
837
+ * ```
838
+ */
839
+ get web() {
840
+ if (!this._web) {
841
+ this._web = createWeb(this.client);
842
+ }
843
+ return this._web;
844
+ }
845
+ /**
846
+ * AI namespace - Embeddings, image generation, OCR, vision, chat
847
+ *
848
+ * @example
849
+ * ```typescript
850
+ * // Generate embeddings
851
+ * const embedding = await rainfall.ai.embeddings.document({
852
+ * text: 'Hello world'
853
+ * });
854
+ *
855
+ * // Generate image
856
+ * const image = await rainfall.ai.image.generate({
857
+ * prompt: 'A serene mountain landscape'
858
+ * });
859
+ *
860
+ * // OCR
861
+ * const text = await rainfall.ai.ocr({ imageBase64: '...' });
862
+ *
863
+ * // Chat
864
+ * const response = await rainfall.ai.chat({
865
+ * messages: [{ role: 'user', content: 'Hello!' }]
866
+ * });
867
+ * ```
868
+ */
869
+ get ai() {
870
+ if (!this._ai) {
871
+ this._ai = createAI(this.client);
872
+ }
873
+ return this._ai;
874
+ }
875
+ /**
876
+ * Data namespace - CSV processing, scripts, similarity search
877
+ *
878
+ * @example
879
+ * ```typescript
880
+ * // Query CSV with SQL
881
+ * const results = await rainfall.data.csv.query({
882
+ * sql: 'SELECT * FROM data WHERE value > 100'
883
+ * });
884
+ *
885
+ * // Execute saved script
886
+ * const result = await rainfall.data.scripts.execute({
887
+ * name: 'my-script',
888
+ * params: { input: 'data' }
889
+ * });
890
+ * ```
891
+ */
892
+ get data() {
893
+ if (!this._data) {
894
+ this._data = createData(this.client);
895
+ }
896
+ return this._data;
897
+ }
898
+ /**
899
+ * Utils namespace - Mermaid diagrams, document conversion, regex, JSON extraction
900
+ *
901
+ * @example
902
+ * ```typescript
903
+ * // Generate diagram
904
+ * const diagram = await rainfall.utils.mermaid({
905
+ * diagram: 'graph TD; A-->B;'
906
+ * });
907
+ *
908
+ * // Convert document
909
+ * const pdf = await rainfall.utils.documentConvert({
910
+ * document: markdownContent,
911
+ * mimeType: 'text/markdown',
912
+ * format: 'pdf'
913
+ * });
914
+ *
915
+ * // Extract JSON from text
916
+ * const json = await rainfall.utils.jsonExtract({
917
+ * text: 'Here is some data: {"key": "value"}'
918
+ * });
919
+ * ```
920
+ */
921
+ get utils() {
922
+ if (!this._utils) {
923
+ this._utils = createUtils(this.client);
924
+ }
925
+ return this._utils;
926
+ }
927
+ /**
928
+ * Get the underlying HTTP client for advanced usage
929
+ */
930
+ getClient() {
931
+ return this.client;
932
+ }
933
+ /**
934
+ * List all available tools
935
+ */
936
+ async listTools() {
937
+ return this.client.listTools();
938
+ }
939
+ /**
940
+ * Get schema for a specific tool
941
+ */
942
+ async getToolSchema(toolId) {
943
+ return this.client.getToolSchema(toolId);
944
+ }
945
+ /**
946
+ * Execute any tool by ID (low-level access)
947
+ */
948
+ async executeTool(toolId, params) {
949
+ return this.client.executeTool(toolId, params);
950
+ }
951
+ /**
952
+ * Get current subscriber info and usage
953
+ */
954
+ async getMe() {
955
+ return this.client.getMe();
956
+ }
957
+ /**
958
+ * Get current rate limit info
959
+ */
960
+ getRateLimitInfo() {
961
+ return this.client.getRateLimitInfo();
962
+ }
963
+ /**
964
+ * OpenAI-compatible chat completions with tool support
965
+ *
966
+ * @example
967
+ * ```typescript
968
+ * // Simple chat
969
+ * const response = await rainfall.chatCompletions({
970
+ * subscriber_id: 'my-subscriber',
971
+ * messages: [{ role: 'user', content: 'Hello!' }],
972
+ * model: 'llama-3.3-70b-versatile'
973
+ * });
974
+ *
975
+ * // With tools
976
+ * const response = await rainfall.chatCompletions({
977
+ * subscriber_id: 'my-subscriber',
978
+ * messages: [{ role: 'user', content: 'Search for AI news' }],
979
+ * tools: [{ type: 'function', function: { name: 'web-search' } }],
980
+ * enable_stacked: true
981
+ * });
982
+ *
983
+ * // Streaming
984
+ * const stream = await rainfall.chatCompletions({
985
+ * subscriber_id: 'my-subscriber',
986
+ * messages: [{ role: 'user', content: 'Tell me a story' }],
987
+ * stream: true
988
+ * });
989
+ * ```
990
+ */
991
+ async chatCompletions(params) {
992
+ return this.client.chatCompletions(params);
993
+ }
994
+ /**
995
+ * List available models (OpenAI-compatible format)
996
+ *
997
+ * @example
998
+ * ```typescript
999
+ * const models = await rainfall.listModels();
1000
+ * console.log(models); // [{ id: 'llama-3.3-70b-versatile', ... }]
1001
+ * ```
1002
+ */
1003
+ async listModels(subscriberId) {
1004
+ return this.client.listModels(subscriberId);
1005
+ }
1006
+ };
1007
+
1008
+ // src/services/networked.ts
1009
+ init_cjs_shims();
1010
+ var RainfallNetworkedExecutor = class {
1011
+ rainfall;
1012
+ options;
1013
+ edgeNodeId;
1014
+ jobCallbacks = /* @__PURE__ */ new Map();
1015
+ resultPollingInterval;
1016
+ constructor(rainfall, options = {}) {
1017
+ this.rainfall = rainfall;
1018
+ this.options = {
1019
+ wsPort: 8765,
1020
+ httpPort: 8787,
1021
+ hostname: process.env.HOSTNAME || "local-daemon",
1022
+ capabilities: {
1023
+ localExec: true,
1024
+ fileWatch: true,
1025
+ passiveListen: true
1026
+ },
1027
+ ...options
1028
+ };
1029
+ }
1030
+ /**
1031
+ * Register this edge node with the Rainfall backend
1032
+ */
1033
+ async registerEdgeNode() {
1034
+ const capabilities = this.buildCapabilitiesList();
1035
+ try {
1036
+ const result = await this.rainfall.executeTool("register-edge-node", {
1037
+ hostname: this.options.hostname,
1038
+ capabilities,
1039
+ wsPort: this.options.wsPort,
1040
+ httpPort: this.options.httpPort,
1041
+ version: "0.1.0"
1042
+ });
1043
+ this.edgeNodeId = result.edgeNodeId;
1044
+ console.log(`\u{1F310} Edge node registered with Rainfall as ${this.edgeNodeId}`);
1045
+ return this.edgeNodeId;
1046
+ } catch (error) {
1047
+ this.edgeNodeId = `edge-${this.options.hostname}-${Date.now()}`;
1048
+ console.log(`\u{1F310} Edge node running in local mode (ID: ${this.edgeNodeId})`);
1049
+ return this.edgeNodeId;
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Unregister this edge node on shutdown
1054
+ */
1055
+ async unregisterEdgeNode() {
1056
+ if (!this.edgeNodeId) return;
1057
+ try {
1058
+ await this.rainfall.executeTool("unregister-edge-node", {
1059
+ edgeNodeId: this.edgeNodeId
1060
+ });
1061
+ console.log(`\u{1F310} Edge node ${this.edgeNodeId} unregistered`);
1062
+ } catch {
1063
+ }
1064
+ if (this.resultPollingInterval) {
1065
+ clearInterval(this.resultPollingInterval);
1066
+ }
1067
+ }
1068
+ /**
1069
+ * Queue a tool execution for distributed processing
1070
+ * Non-blocking - returns immediately with a job ID
1071
+ */
1072
+ async queueToolExecution(toolId, params, options = {}) {
1073
+ const executionMode = options.executionMode || "any";
1074
+ try {
1075
+ const result = await this.rainfall.executeTool("queue-job", {
1076
+ toolId,
1077
+ params,
1078
+ executionMode,
1079
+ requesterEdgeNodeId: this.edgeNodeId
1080
+ });
1081
+ if (options.callback) {
1082
+ this.jobCallbacks.set(result.jobId, options.callback);
1083
+ this.startResultPolling();
1084
+ }
1085
+ return result.jobId;
1086
+ } catch (error) {
1087
+ if (executionMode === "local-only" || executionMode === "any") {
1088
+ try {
1089
+ const result = await this.rainfall.executeTool(toolId, params);
1090
+ if (options.callback) {
1091
+ options.callback(result);
1092
+ }
1093
+ return `local-${Date.now()}`;
1094
+ } catch (execError) {
1095
+ if (options.callback) {
1096
+ options.callback(null, String(execError));
1097
+ }
1098
+ throw execError;
1099
+ }
1100
+ }
1101
+ throw error;
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Get status of a queued job
1106
+ */
1107
+ async getJobStatus(jobId) {
1108
+ try {
1109
+ const result = await this.rainfall.executeTool("get-job-status", {
1110
+ jobId
1111
+ });
1112
+ return result.job;
1113
+ } catch {
1114
+ return null;
1115
+ }
1116
+ }
1117
+ /**
1118
+ * Subscribe to job results via polling (WebSocket fallback)
1119
+ * In the future, this will use WebSocket push from ApresMoi
1120
+ */
1121
+ async subscribeToResults(callback) {
1122
+ console.log("\u{1F4E1} Subscribed to job results via Rainfall (polling mode)");
1123
+ this.onResultReceived = callback;
1124
+ }
1125
+ onResultReceived;
1126
+ /**
1127
+ * Start polling for job results (fallback until WebSocket push is ready)
1128
+ */
1129
+ startResultPolling() {
1130
+ if (this.resultPollingInterval) return;
1131
+ this.resultPollingInterval = setInterval(async () => {
1132
+ for (const [jobId, callback] of this.jobCallbacks) {
1133
+ try {
1134
+ const job = await this.getJobStatus(jobId);
1135
+ if (job?.status === "completed" || job?.status === "failed") {
1136
+ callback(job.result, job.error);
1137
+ this.jobCallbacks.delete(jobId);
1138
+ if (this.onResultReceived) {
1139
+ this.onResultReceived(jobId, job.result, job.error);
1140
+ }
1141
+ }
1142
+ } catch {
1143
+ }
1144
+ }
1145
+ if (this.jobCallbacks.size === 0 && this.resultPollingInterval) {
1146
+ clearInterval(this.resultPollingInterval);
1147
+ this.resultPollingInterval = void 0;
1148
+ }
1149
+ }, 2e3);
1150
+ }
1151
+ /**
1152
+ * Claim a job for execution on this edge node
1153
+ */
1154
+ async claimJob() {
1155
+ try {
1156
+ const result = await this.rainfall.executeTool("claim-job", {
1157
+ edgeNodeId: this.edgeNodeId,
1158
+ capabilities: this.buildCapabilitiesList()
1159
+ });
1160
+ return result.job;
1161
+ } catch {
1162
+ return null;
1163
+ }
1164
+ }
1165
+ /**
1166
+ * Submit job result after execution
1167
+ */
1168
+ async submitJobResult(jobId, result, error) {
1169
+ try {
1170
+ await this.rainfall.executeTool("submit-job-result", {
1171
+ jobId,
1172
+ edgeNodeId: this.edgeNodeId,
1173
+ result,
1174
+ error
1175
+ });
1176
+ } catch {
1177
+ }
1178
+ }
1179
+ /**
1180
+ * Get this edge node's ID
1181
+ */
1182
+ getEdgeNodeId() {
1183
+ return this.edgeNodeId;
1184
+ }
1185
+ /**
1186
+ * Build capabilities list from options
1187
+ */
1188
+ buildCapabilitiesList() {
1189
+ const caps = this.options.capabilities || {};
1190
+ const list = [];
1191
+ if (caps.localExec) list.push("local-exec");
1192
+ if (caps.fileWatch) list.push("file-watch");
1193
+ if (caps.passiveListen) list.push("passive-listen");
1194
+ if (caps.browser) list.push("browser");
1195
+ if (caps.custom) list.push(...caps.custom);
1196
+ return list;
1197
+ }
1198
+ };
1199
+
1200
+ // src/services/context.ts
1201
+ init_cjs_shims();
1202
+ var RainfallDaemonContext = class {
1203
+ rainfall;
1204
+ options;
1205
+ localMemories = /* @__PURE__ */ new Map();
1206
+ sessions = /* @__PURE__ */ new Map();
1207
+ executionHistory = [];
1208
+ currentSessionId;
1209
+ constructor(rainfall, options = {}) {
1210
+ this.rainfall = rainfall;
1211
+ this.options = {
1212
+ maxLocalMemories: 1e3,
1213
+ maxMessageHistory: 100,
1214
+ maxExecutionHistory: 500,
1215
+ sessionTtl: 24 * 60 * 60 * 1e3,
1216
+ // 24 hours
1217
+ ...options
1218
+ };
1219
+ }
1220
+ /**
1221
+ * Initialize the context - load recent memories from cloud
1222
+ */
1223
+ async initialize() {
1224
+ try {
1225
+ const recentMemories = await this.rainfall.memory.recall({
1226
+ query: "daemon:context",
1227
+ topK: this.options.maxLocalMemories
1228
+ });
1229
+ for (const memory of recentMemories) {
1230
+ this.localMemories.set(memory.id, {
1231
+ id: memory.id,
1232
+ content: memory.content,
1233
+ keywords: memory.keywords || [],
1234
+ timestamp: memory.timestamp,
1235
+ source: memory.source,
1236
+ metadata: memory.metadata
1237
+ });
1238
+ }
1239
+ console.log(`\u{1F9E0} Loaded ${this.localMemories.size} memories into context`);
1240
+ } catch (error) {
1241
+ console.warn("\u26A0\uFE0F Could not sync memories:", error instanceof Error ? error.message : error);
1242
+ }
1243
+ }
1244
+ /**
1245
+ * Create or get a session
1246
+ */
1247
+ getSession(sessionId) {
1248
+ if (sessionId && this.sessions.has(sessionId)) {
1249
+ const session = this.sessions.get(sessionId);
1250
+ session.lastActivity = (/* @__PURE__ */ new Date()).toISOString();
1251
+ return session;
1252
+ }
1253
+ const newSession = {
1254
+ id: sessionId || `session-${Date.now()}`,
1255
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1256
+ lastActivity: (/* @__PURE__ */ new Date()).toISOString(),
1257
+ variables: {},
1258
+ messageHistory: []
1259
+ };
1260
+ this.sessions.set(newSession.id, newSession);
1261
+ this.currentSessionId = newSession.id;
1262
+ return newSession;
1263
+ }
1264
+ /**
1265
+ * Get the current active session
1266
+ */
1267
+ getCurrentSession() {
1268
+ if (this.currentSessionId) {
1269
+ return this.sessions.get(this.currentSessionId);
1270
+ }
1271
+ return void 0;
1272
+ }
1273
+ /**
1274
+ * Set the current active session
1275
+ */
1276
+ setCurrentSession(sessionId) {
1277
+ if (this.sessions.has(sessionId)) {
1278
+ this.currentSessionId = sessionId;
1279
+ }
1280
+ }
1281
+ /**
1282
+ * Add a message to the current session history
1283
+ */
1284
+ addMessage(role, content) {
1285
+ const session = this.getCurrentSession();
1286
+ if (!session) return;
1287
+ session.messageHistory.push({
1288
+ role,
1289
+ content,
1290
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1291
+ });
1292
+ if (session.messageHistory.length > this.options.maxMessageHistory) {
1293
+ session.messageHistory = session.messageHistory.slice(-this.options.maxMessageHistory);
1294
+ }
1295
+ }
1296
+ /**
1297
+ * Store a memory (local + cloud sync)
1298
+ */
1299
+ async storeMemory(content, options = {}) {
1300
+ const id = `mem-${Date.now()}-${Math.random().toString(36).slice(2)}`;
1301
+ const entry = {
1302
+ id,
1303
+ content,
1304
+ keywords: options.keywords || [],
1305
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1306
+ source: options.source || "daemon",
1307
+ metadata: options.metadata
1308
+ };
1309
+ this.localMemories.set(id, entry);
1310
+ try {
1311
+ await this.rainfall.memory.create({
1312
+ content,
1313
+ keywords: [...options.keywords || [], "daemon:context"],
1314
+ metadata: {
1315
+ ...options.metadata,
1316
+ daemonMemoryId: id,
1317
+ source: options.source || "daemon"
1318
+ }
1319
+ });
1320
+ } catch (error) {
1321
+ console.warn("\u26A0\uFE0F Could not sync memory to cloud:", error instanceof Error ? error.message : error);
1322
+ }
1323
+ this.trimLocalMemories();
1324
+ return id;
1325
+ }
1326
+ /**
1327
+ * Recall memories by query
1328
+ */
1329
+ async recallMemories(query, topK = 5) {
1330
+ const localResults = Array.from(this.localMemories.values()).filter(
1331
+ (m) => m.content.toLowerCase().includes(query.toLowerCase()) || m.keywords.some((k) => k.toLowerCase().includes(query.toLowerCase()))
1332
+ ).slice(0, topK);
1333
+ try {
1334
+ const cloudResults = await this.rainfall.memory.recall({ query, topK });
1335
+ const seen = new Set(localResults.map((r) => r.id));
1336
+ for (const mem of cloudResults) {
1337
+ if (!seen.has(mem.id)) {
1338
+ localResults.push({
1339
+ id: mem.id,
1340
+ content: mem.content,
1341
+ keywords: mem.keywords || [],
1342
+ timestamp: mem.timestamp,
1343
+ source: mem.source,
1344
+ metadata: mem.metadata
1345
+ });
1346
+ }
1347
+ }
1348
+ } catch {
1349
+ }
1350
+ return localResults.slice(0, topK);
1351
+ }
1352
+ /**
1353
+ * Set a session variable
1354
+ */
1355
+ setVariable(key, value) {
1356
+ const session = this.getCurrentSession();
1357
+ if (session) {
1358
+ session.variables[key] = value;
1359
+ }
1360
+ }
1361
+ /**
1362
+ * Get a session variable
1363
+ */
1364
+ getVariable(key) {
1365
+ const session = this.getCurrentSession();
1366
+ return session?.variables[key];
1367
+ }
1368
+ /**
1369
+ * Record a tool execution
1370
+ */
1371
+ recordExecution(toolId, params, result, options = { duration: 0 }) {
1372
+ const record = {
1373
+ id: `exec-${Date.now()}-${Math.random().toString(36).slice(2)}`,
1374
+ toolId,
1375
+ params,
1376
+ result,
1377
+ error: options.error,
1378
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1379
+ duration: options.duration,
1380
+ edgeNodeId: options.edgeNodeId
1381
+ };
1382
+ this.executionHistory.push(record);
1383
+ if (this.executionHistory.length > this.options.maxExecutionHistory) {
1384
+ this.executionHistory = this.executionHistory.slice(-this.options.maxExecutionHistory);
1385
+ }
1386
+ }
1387
+ /**
1388
+ * Get recent execution history
1389
+ */
1390
+ getExecutionHistory(limit = 10) {
1391
+ return this.executionHistory.slice(-limit).reverse();
1392
+ }
1393
+ /**
1394
+ * Get execution statistics
1395
+ */
1396
+ getExecutionStats() {
1397
+ const stats = {
1398
+ total: this.executionHistory.length,
1399
+ successful: 0,
1400
+ failed: 0,
1401
+ averageDuration: 0,
1402
+ byTool: {}
1403
+ };
1404
+ let totalDuration = 0;
1405
+ for (const exec of this.executionHistory) {
1406
+ if (exec.error) {
1407
+ stats.failed++;
1408
+ } else {
1409
+ stats.successful++;
1410
+ }
1411
+ totalDuration += exec.duration;
1412
+ stats.byTool[exec.toolId] = (stats.byTool[exec.toolId] || 0) + 1;
1413
+ }
1414
+ stats.averageDuration = stats.total > 0 ? totalDuration / stats.total : 0;
1415
+ return stats;
1416
+ }
1417
+ /**
1418
+ * Clear old sessions based on TTL
1419
+ */
1420
+ cleanupSessions() {
1421
+ const now = Date.now();
1422
+ const ttl = this.options.sessionTtl;
1423
+ for (const [id, session] of this.sessions) {
1424
+ const lastActivity = new Date(session.lastActivity).getTime();
1425
+ if (now - lastActivity > ttl) {
1426
+ this.sessions.delete(id);
1427
+ if (this.currentSessionId === id) {
1428
+ this.currentSessionId = void 0;
1429
+ }
1430
+ }
1431
+ }
1432
+ }
1433
+ /**
1434
+ * Get context summary for debugging
1435
+ */
1436
+ getStatus() {
1437
+ return {
1438
+ memoriesCached: this.localMemories.size,
1439
+ activeSessions: this.sessions.size,
1440
+ currentSession: this.currentSessionId,
1441
+ executionHistorySize: this.executionHistory.length
1442
+ };
1443
+ }
1444
+ trimLocalMemories() {
1445
+ if (this.localMemories.size <= this.options.maxLocalMemories) return;
1446
+ const entries = Array.from(this.localMemories.entries()).sort((a, b) => new Date(a[1].timestamp).getTime() - new Date(b[1].timestamp).getTime());
1447
+ const toRemove = entries.slice(0, entries.length - this.options.maxLocalMemories);
1448
+ for (const [id] of toRemove) {
1449
+ this.localMemories.delete(id);
1450
+ }
1451
+ }
1452
+ };
1453
+
1454
+ // src/services/listeners.ts
1455
+ init_cjs_shims();
1456
+ var RainfallListenerRegistry = class {
1457
+ rainfall;
1458
+ context;
1459
+ executor;
1460
+ watchers = /* @__PURE__ */ new Map();
1461
+ cronIntervals = /* @__PURE__ */ new Map();
1462
+ eventHistory = [];
1463
+ maxEventHistory = 100;
1464
+ constructor(rainfall, context, executor) {
1465
+ this.rainfall = rainfall;
1466
+ this.context = context;
1467
+ this.executor = executor;
1468
+ }
1469
+ /**
1470
+ * Register a file watcher
1471
+ * Note: Actual file watching requires fs.watch or chokidar
1472
+ * This is the registry - actual watching is done by the daemon
1473
+ */
1474
+ async registerFileWatcher(config) {
1475
+ console.log(`\u{1F441}\uFE0F Registering file watcher: ${config.name} (${config.watchPath})`);
1476
+ const existing = Array.from(this.watchers.keys());
1477
+ if (existing.includes(config.id)) {
1478
+ await this.unregisterFileWatcher(config.id);
1479
+ }
1480
+ this.watchers.set(config.id, {
1481
+ stop: () => {
1482
+ console.log(`\u{1F441}\uFE0F Stopped file watcher: ${config.name}`);
1483
+ }
1484
+ });
1485
+ await this.context.storeMemory(`File watcher registered: ${config.name}`, {
1486
+ keywords: ["listener", "file-watcher", config.name],
1487
+ metadata: { config }
1488
+ });
1489
+ }
1490
+ /**
1491
+ * Unregister a file watcher
1492
+ */
1493
+ async unregisterFileWatcher(id) {
1494
+ const watcher = this.watchers.get(id);
1495
+ if (watcher) {
1496
+ watcher.stop();
1497
+ this.watchers.delete(id);
1498
+ }
1499
+ }
1500
+ /**
1501
+ * Register a cron trigger
1502
+ */
1503
+ async registerCronTrigger(config) {
1504
+ console.log(`\u23F0 Registering cron trigger: ${config.name} (${config.cron})`);
1505
+ if (this.cronIntervals.has(config.id)) {
1506
+ clearInterval(this.cronIntervals.get(config.id));
1507
+ this.cronIntervals.delete(config.id);
1508
+ }
1509
+ const interval = this.parseCronToMs(config.cron);
1510
+ if (interval) {
1511
+ const intervalId = setInterval(async () => {
1512
+ await this.handleCronTick(config);
1513
+ }, interval);
1514
+ this.cronIntervals.set(config.id, intervalId);
1515
+ }
1516
+ await this.context.storeMemory(`Cron trigger registered: ${config.name}`, {
1517
+ keywords: ["listener", "cron", config.name],
1518
+ metadata: { config }
1519
+ });
1520
+ }
1521
+ /**
1522
+ * Unregister a cron trigger
1523
+ */
1524
+ unregisterCronTrigger(id) {
1525
+ const interval = this.cronIntervals.get(id);
1526
+ if (interval) {
1527
+ clearInterval(interval);
1528
+ this.cronIntervals.delete(id);
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Handle a file event
1533
+ */
1534
+ async handleFileEvent(watcherId, eventType, filePath) {
1535
+ const event = {
1536
+ id: `evt-${Date.now()}`,
1537
+ type: "file",
1538
+ source: watcherId,
1539
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1540
+ data: { eventType, filePath }
1541
+ };
1542
+ this.recordEvent(event);
1543
+ console.log(`\u{1F4C1} File event: ${eventType} ${filePath}`);
1544
+ }
1545
+ /**
1546
+ * Handle a cron tick
1547
+ */
1548
+ async handleCronTick(config) {
1549
+ const event = {
1550
+ id: `evt-${Date.now()}`,
1551
+ type: "cron",
1552
+ source: config.id,
1553
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1554
+ data: { cron: config.cron }
1555
+ };
1556
+ this.recordEvent(event);
1557
+ console.log(`\u23F0 Cron tick: ${config.name}`);
1558
+ for (const step of config.workflow) {
1559
+ try {
1560
+ await this.executor.queueToolExecution(step.toolId, {
1561
+ ...step.params,
1562
+ _event: event
1563
+ });
1564
+ } catch (error) {
1565
+ console.error(`\u274C Workflow step failed: ${step.toolId}`, error);
1566
+ }
1567
+ }
1568
+ }
1569
+ /**
1570
+ * Trigger a manual event (for testing or programmatic triggers)
1571
+ */
1572
+ async triggerManual(name, data = {}) {
1573
+ const event = {
1574
+ id: `evt-${Date.now()}`,
1575
+ type: "manual",
1576
+ source: name,
1577
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1578
+ data
1579
+ };
1580
+ this.recordEvent(event);
1581
+ console.log(`\u{1F446} Manual trigger: ${name}`);
1582
+ await this.context.storeMemory(`Manual trigger fired: ${name}`, {
1583
+ keywords: ["trigger", "manual", name],
1584
+ metadata: { event }
1585
+ });
1586
+ }
1587
+ /**
1588
+ * Get recent events
1589
+ */
1590
+ getRecentEvents(limit = 10) {
1591
+ return this.eventHistory.slice(-limit).reverse();
1592
+ }
1593
+ /**
1594
+ * Get active listeners status
1595
+ */
1596
+ getStatus() {
1597
+ return {
1598
+ fileWatchers: this.watchers.size,
1599
+ cronTriggers: this.cronIntervals.size,
1600
+ recentEvents: this.eventHistory.length
1601
+ };
1602
+ }
1603
+ /**
1604
+ * Stop all listeners
1605
+ */
1606
+ async stopAll() {
1607
+ for (const [id] of this.watchers) {
1608
+ await this.unregisterFileWatcher(id);
1609
+ }
1610
+ for (const [id] of this.cronIntervals) {
1611
+ this.unregisterCronTrigger(id);
1612
+ }
1613
+ console.log("\u{1F6D1} All listeners stopped");
1614
+ }
1615
+ recordEvent(event) {
1616
+ this.eventHistory.push(event);
1617
+ if (this.eventHistory.length > this.maxEventHistory) {
1618
+ this.eventHistory = this.eventHistory.slice(-this.maxEventHistory);
1619
+ }
1620
+ }
1621
+ /**
1622
+ * Simple cron parser - converts basic cron expressions to milliseconds
1623
+ * Supports: @hourly, @daily, @weekly, and simple intervals like every N minutes
1624
+ */
1625
+ parseCronToMs(cron) {
1626
+ switch (cron) {
1627
+ case "@hourly":
1628
+ return 60 * 60 * 1e3;
1629
+ case "@daily":
1630
+ return 24 * 60 * 60 * 1e3;
1631
+ case "@weekly":
1632
+ return 7 * 24 * 60 * 60 * 1e3;
1633
+ case "@minutely":
1634
+ return 60 * 1e3;
1635
+ }
1636
+ const match = cron.match(/^\*\/(\d+)\s/);
1637
+ if (match) {
1638
+ const minutes = parseInt(match[1], 10);
1639
+ if (minutes > 0 && minutes <= 60) {
1640
+ return minutes * 60 * 1e3;
1641
+ }
1642
+ }
1643
+ console.warn(`\u26A0\uFE0F Unrecognized cron pattern "${cron}", using 1 minute interval`);
1644
+ return 60 * 1e3;
1645
+ }
1646
+ };
1647
+
1648
+ // src/daemon/index.ts
1649
+ var RainfallDaemon = class {
1650
+ wss;
1651
+ openaiApp;
1652
+ rainfall;
1653
+ port;
1654
+ openaiPort;
1655
+ rainfallConfig;
1656
+ tools = [];
1657
+ toolSchemas = /* @__PURE__ */ new Map();
1658
+ clients = /* @__PURE__ */ new Set();
1659
+ debug;
1660
+ // New services
1661
+ networkedExecutor;
1662
+ context;
1663
+ listeners;
1664
+ constructor(config = {}) {
1665
+ this.port = config.port || 8765;
1666
+ this.openaiPort = config.openaiPort || 8787;
1667
+ this.rainfallConfig = config.rainfallConfig;
1668
+ this.debug = config.debug || false;
1669
+ this.openaiApp = (0, import_express.default)();
1670
+ this.openaiApp.use(import_express.default.json());
1671
+ }
1672
+ async start() {
1673
+ this.log("\u{1F327}\uFE0F Rainfall Daemon starting...");
1674
+ await this.initializeRainfall();
1675
+ if (!this.rainfall) {
1676
+ throw new Error("Failed to initialize Rainfall SDK");
1677
+ }
1678
+ this.context = new RainfallDaemonContext(this.rainfall, {
1679
+ maxLocalMemories: 1e3,
1680
+ maxMessageHistory: 100,
1681
+ ...this.rainfallConfig
1682
+ });
1683
+ await this.context.initialize();
1684
+ this.networkedExecutor = new RainfallNetworkedExecutor(this.rainfall, {
1685
+ wsPort: this.port,
1686
+ httpPort: this.openaiPort,
1687
+ hostname: process.env.HOSTNAME || "local-daemon",
1688
+ capabilities: {
1689
+ localExec: true,
1690
+ fileWatch: true,
1691
+ passiveListen: true
1692
+ }
1693
+ });
1694
+ await this.networkedExecutor.registerEdgeNode();
1695
+ await this.networkedExecutor.subscribeToResults((jobId, result, error) => {
1696
+ this.log(`\u{1F4EC} Job ${jobId} ${error ? "failed" : "completed"}`, error || result);
1697
+ });
1698
+ this.listeners = new RainfallListenerRegistry(
1699
+ this.rainfall,
1700
+ this.context,
1701
+ this.networkedExecutor
1702
+ );
1703
+ await this.loadTools();
1704
+ await this.startWebSocketServer();
1705
+ await this.startOpenAIProxy();
1706
+ console.log(`\u{1F680} Rainfall daemon running`);
1707
+ console.log(` WebSocket (MCP): ws://localhost:${this.port}`);
1708
+ console.log(` OpenAI API: http://localhost:${this.openaiPort}/v1/chat/completions`);
1709
+ console.log(` Health Check: http://localhost:${this.openaiPort}/health`);
1710
+ console.log(` Edge Node ID: ${this.networkedExecutor.getEdgeNodeId() || "local"}`);
1711
+ console.log(` Tools loaded: ${this.tools.length}`);
1712
+ console.log(` Press Ctrl+C to stop`);
1713
+ process.on("SIGINT", () => this.stop());
1714
+ process.on("SIGTERM", () => this.stop());
1715
+ }
1716
+ async stop() {
1717
+ this.log("\u{1F6D1} Shutting down Rainfall daemon...");
1718
+ if (this.listeners) {
1719
+ await this.listeners.stopAll();
1720
+ }
1721
+ if (this.networkedExecutor) {
1722
+ await this.networkedExecutor.unregisterEdgeNode();
1723
+ }
1724
+ for (const client of this.clients) {
1725
+ client.close();
1726
+ }
1727
+ this.clients.clear();
1728
+ if (this.wss) {
1729
+ this.wss.close();
1730
+ this.wss = void 0;
1731
+ }
1732
+ console.log("\u{1F44B} Rainfall daemon stopped");
1733
+ }
1734
+ /**
1735
+ * Get the networked executor for distributed job management
1736
+ */
1737
+ getNetworkedExecutor() {
1738
+ return this.networkedExecutor;
1739
+ }
1740
+ /**
1741
+ * Get the context for memory/session management
1742
+ */
1743
+ getContext() {
1744
+ return this.context;
1745
+ }
1746
+ /**
1747
+ * Get the listener registry for passive triggers
1748
+ */
1749
+ getListenerRegistry() {
1750
+ return this.listeners;
1751
+ }
1752
+ async initializeRainfall() {
1753
+ if (this.rainfallConfig?.apiKey) {
1754
+ this.rainfall = new Rainfall(this.rainfallConfig);
1755
+ } else {
1756
+ const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1757
+ const config = loadConfig2();
1758
+ if (config.apiKey) {
1759
+ this.rainfall = new Rainfall({
1760
+ apiKey: config.apiKey,
1761
+ baseUrl: config.baseUrl
1762
+ });
1763
+ } else {
1764
+ throw new Error("No API key configured. Run: rainfall auth login <api-key>");
1765
+ }
1766
+ }
1767
+ }
1768
+ async loadTools() {
1769
+ if (!this.rainfall) return;
1770
+ try {
1771
+ this.tools = await this.rainfall.listTools();
1772
+ this.log(`\u{1F4E6} Loaded ${this.tools.length} tools`);
1773
+ } catch (error) {
1774
+ console.warn("\u26A0\uFE0F Failed to load tools:", error instanceof Error ? error.message : error);
1775
+ this.tools = [];
1776
+ }
1777
+ }
1778
+ async getToolSchema(toolId) {
1779
+ if (this.toolSchemas.has(toolId)) {
1780
+ return this.toolSchemas.get(toolId);
1781
+ }
1782
+ if (!this.rainfall) return null;
1783
+ try {
1784
+ const schema = await this.rainfall.getToolSchema(toolId);
1785
+ this.toolSchemas.set(toolId, schema);
1786
+ return schema;
1787
+ } catch {
1788
+ return null;
1789
+ }
1790
+ }
1791
+ async startWebSocketServer() {
1792
+ this.wss = new import_ws.WebSocketServer({ port: this.port });
1793
+ this.wss.on("connection", (ws) => {
1794
+ this.log("\u{1F7E2} MCP client connected");
1795
+ this.clients.add(ws);
1796
+ ws.on("message", async (data) => {
1797
+ try {
1798
+ const message = JSON.parse(data.toString());
1799
+ const response = await this.handleMCPMessage(message);
1800
+ ws.send(JSON.stringify(response));
1801
+ } catch (error) {
1802
+ const errorResponse = {
1803
+ jsonrpc: "2.0",
1804
+ id: void 0,
1805
+ error: {
1806
+ code: -32700,
1807
+ message: error instanceof Error ? error.message : "Parse error"
1808
+ }
1809
+ };
1810
+ ws.send(JSON.stringify(errorResponse));
1811
+ }
1812
+ });
1813
+ ws.on("close", () => {
1814
+ this.log("\u{1F534} MCP client disconnected");
1815
+ this.clients.delete(ws);
1816
+ });
1817
+ ws.on("error", (error) => {
1818
+ console.error("WebSocket error:", error);
1819
+ this.clients.delete(ws);
1820
+ });
1821
+ });
1822
+ }
1823
+ async handleMCPMessage(message) {
1824
+ const { id, method, params } = message;
1825
+ switch (method) {
1826
+ case "initialize":
1827
+ return {
1828
+ jsonrpc: "2.0",
1829
+ id,
1830
+ result: {
1831
+ protocolVersion: "2024-11-05",
1832
+ capabilities: {
1833
+ tools: { listChanged: true }
1834
+ },
1835
+ serverInfo: {
1836
+ name: "rainfall-daemon",
1837
+ version: "0.1.0"
1838
+ }
1839
+ }
1840
+ };
1841
+ case "tools/list":
1842
+ return {
1843
+ jsonrpc: "2.0",
1844
+ id,
1845
+ result: {
1846
+ tools: await this.getMCPTools()
1847
+ }
1848
+ };
1849
+ case "tools/call": {
1850
+ const toolName = params?.name;
1851
+ const toolParams = params?.arguments;
1852
+ try {
1853
+ const startTime = Date.now();
1854
+ const result = await this.executeTool(toolName, toolParams);
1855
+ const duration = Date.now() - startTime;
1856
+ if (this.context) {
1857
+ this.context.recordExecution(toolName, toolParams || {}, result, { duration });
1858
+ }
1859
+ return {
1860
+ jsonrpc: "2.0",
1861
+ id,
1862
+ result: {
1863
+ content: [
1864
+ {
1865
+ type: "text",
1866
+ text: typeof result === "string" ? result : JSON.stringify(result, null, 2)
1867
+ }
1868
+ ]
1869
+ }
1870
+ };
1871
+ } catch (error) {
1872
+ const errorMessage = error instanceof Error ? error.message : "Tool execution failed";
1873
+ if (this.context) {
1874
+ this.context.recordExecution(toolName, toolParams || {}, null, {
1875
+ error: errorMessage,
1876
+ duration: 0
1877
+ });
1878
+ }
1879
+ return {
1880
+ jsonrpc: "2.0",
1881
+ id,
1882
+ error: {
1883
+ code: -32603,
1884
+ message: errorMessage
1885
+ }
1886
+ };
1887
+ }
1888
+ }
1889
+ case "ping":
1890
+ return {
1891
+ jsonrpc: "2.0",
1892
+ id,
1893
+ result: {}
1894
+ };
1895
+ default:
1896
+ return {
1897
+ jsonrpc: "2.0",
1898
+ id,
1899
+ error: {
1900
+ code: -32601,
1901
+ message: `Method not found: ${method}`
1902
+ }
1903
+ };
1904
+ }
1905
+ }
1906
+ async getMCPTools() {
1907
+ const mcpTools = [];
1908
+ for (const tool of this.tools) {
1909
+ const schema = await this.getToolSchema(tool.id);
1910
+ if (schema) {
1911
+ const toolSchema = schema;
1912
+ mcpTools.push({
1913
+ name: tool.id,
1914
+ description: toolSchema.description || tool.description,
1915
+ inputSchema: toolSchema.parameters || { type: "object", properties: {} }
1916
+ });
1917
+ }
1918
+ }
1919
+ return mcpTools;
1920
+ }
1921
+ async executeTool(toolId, params) {
1922
+ if (!this.rainfall) {
1923
+ throw new Error("Rainfall SDK not initialized");
1924
+ }
1925
+ return this.rainfall.executeTool(toolId, params);
1926
+ }
1927
+ async startOpenAIProxy() {
1928
+ this.openaiApp.get("/v1/models", async (_req, res) => {
1929
+ try {
1930
+ if (this.rainfall) {
1931
+ const models = await this.rainfall.listModels();
1932
+ res.json({
1933
+ object: "list",
1934
+ data: models.map((m) => ({
1935
+ id: m.id,
1936
+ object: "model",
1937
+ created: Math.floor(Date.now() / 1e3),
1938
+ owned_by: "rainfall"
1939
+ }))
1940
+ });
1941
+ } else {
1942
+ res.json({
1943
+ object: "list",
1944
+ data: [
1945
+ { id: "llama-3.3-70b-versatile", object: "model", created: Date.now(), owned_by: "groq" },
1946
+ { id: "gpt-4o", object: "model", created: Date.now(), owned_by: "openai" },
1947
+ { id: "claude-3-5-sonnet", object: "model", created: Date.now(), owned_by: "anthropic" },
1948
+ { id: "gemini-2.0-flash-exp", object: "model", created: Date.now(), owned_by: "gemini" }
1949
+ ]
1950
+ });
1951
+ }
1952
+ } catch (error) {
1953
+ res.status(500).json({ error: "Failed to fetch models" });
1954
+ }
1955
+ });
1956
+ this.openaiApp.post("/v1/chat/completions", async (req, res) => {
1957
+ const body = req.body;
1958
+ if (!body.messages || !Array.isArray(body.messages)) {
1959
+ res.status(400).json({
1960
+ error: {
1961
+ message: "Missing required field: messages",
1962
+ type: "invalid_request_error"
1963
+ }
1964
+ });
1965
+ return;
1966
+ }
1967
+ if (!this.rainfall) {
1968
+ res.status(503).json({
1969
+ error: {
1970
+ message: "Rainfall SDK not initialized",
1971
+ type: "service_unavailable"
1972
+ }
1973
+ });
1974
+ return;
1975
+ }
1976
+ try {
1977
+ const me = await this.rainfall.getMe();
1978
+ const subscriberId = me.id;
1979
+ const localToolMap = await this.buildLocalToolMap();
1980
+ let allTools = [];
1981
+ if (body.tools && body.tools.length > 0) {
1982
+ allTools = body.tools;
1983
+ } else if (body.tool_choice) {
1984
+ const openaiTools = await this.getOpenAITools();
1985
+ allTools = openaiTools;
1986
+ }
1987
+ let messages = [...body.messages];
1988
+ const maxToolIterations = 10;
1989
+ let toolIterations = 0;
1990
+ while (toolIterations < maxToolIterations) {
1991
+ toolIterations++;
1992
+ const llmResponse = await this.callLLM({
1993
+ subscriberId,
1994
+ model: body.model,
1995
+ messages,
1996
+ tools: allTools.length > 0 ? allTools : void 0,
1997
+ tool_choice: body.tool_choice,
1998
+ temperature: body.temperature,
1999
+ max_tokens: body.max_tokens,
2000
+ stream: false,
2001
+ // Always non-streaming for tool loop
2002
+ tool_priority: body.tool_priority,
2003
+ enable_stacked: body.enable_stacked
2004
+ });
2005
+ const choice = llmResponse.choices?.[0];
2006
+ let toolCalls = choice?.message?.tool_calls || [];
2007
+ const content = choice?.message?.content || "";
2008
+ const reasoningContent = choice?.message?.reasoning_content || "";
2009
+ const fullContent = content + " " + reasoningContent;
2010
+ const xmlToolCalls = this.parseXMLToolCalls(fullContent);
2011
+ if (xmlToolCalls.length > 0) {
2012
+ this.log(`\u{1F4CB} Parsed ${xmlToolCalls.length} XML tool calls from content`);
2013
+ toolCalls = xmlToolCalls;
2014
+ }
2015
+ if (!toolCalls || toolCalls.length === 0) {
2016
+ if (body.stream) {
2017
+ await this.streamResponse(res, llmResponse);
2018
+ } else {
2019
+ res.json(llmResponse);
2020
+ }
2021
+ this.updateContext(body.messages, llmResponse);
2022
+ return;
2023
+ }
2024
+ messages.push({
2025
+ role: "assistant",
2026
+ content: choice?.message?.content || "",
2027
+ tool_calls: toolCalls
2028
+ });
2029
+ for (const toolCall of toolCalls) {
2030
+ const toolName = toolCall.function?.name;
2031
+ const toolArgsStr = toolCall.function?.arguments || "{}";
2032
+ if (!toolName) continue;
2033
+ this.log(`\u{1F527} Tool call: ${toolName}`);
2034
+ let toolResult;
2035
+ let toolError;
2036
+ try {
2037
+ const localTool = this.findLocalTool(toolName, localToolMap);
2038
+ if (localTool) {
2039
+ this.log(` \u2192 Executing locally`);
2040
+ const args = JSON.parse(toolArgsStr);
2041
+ toolResult = await this.executeLocalTool(localTool.id, args);
2042
+ } else {
2043
+ const shouldExecuteLocal = body.tool_priority === "local" || body.tool_priority === "stacked";
2044
+ if (shouldExecuteLocal) {
2045
+ try {
2046
+ const args = JSON.parse(toolArgsStr);
2047
+ toolResult = await this.rainfall.executeTool(toolName.replace(/_/g, "-"), args);
2048
+ } catch {
2049
+ toolResult = { _pending: true, tool: toolName, args: toolArgsStr };
2050
+ }
2051
+ } else {
2052
+ toolResult = { _pending: true, tool: toolName, args: toolArgsStr };
2053
+ }
2054
+ }
2055
+ } catch (error) {
2056
+ toolError = error instanceof Error ? error.message : String(error);
2057
+ this.log(` \u2192 Error: ${toolError}`);
2058
+ }
2059
+ messages.push({
2060
+ role: "tool",
2061
+ content: toolError ? JSON.stringify({ error: toolError }) : typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult),
2062
+ tool_call_id: toolCall.id
2063
+ });
2064
+ if (this.context) {
2065
+ this.context.recordExecution(
2066
+ toolName,
2067
+ JSON.parse(toolArgsStr || "{}"),
2068
+ toolResult,
2069
+ { error: toolError, duration: 0 }
2070
+ );
2071
+ }
2072
+ }
2073
+ }
2074
+ res.status(500).json({
2075
+ error: {
2076
+ message: "Maximum tool execution iterations reached",
2077
+ type: "tool_execution_error"
2078
+ }
2079
+ });
2080
+ } catch (error) {
2081
+ this.log("Chat completions error:", error);
2082
+ res.status(500).json({
2083
+ error: {
2084
+ message: error instanceof Error ? error.message : "Internal server error",
2085
+ type: "internal_error"
2086
+ }
2087
+ });
2088
+ }
2089
+ });
2090
+ this.openaiApp.get("/health", (_req, res) => {
2091
+ res.json({
2092
+ status: "ok",
2093
+ daemon: "rainfall",
2094
+ version: "0.1.0",
2095
+ tools_loaded: this.tools.length,
2096
+ edge_node_id: this.networkedExecutor?.getEdgeNodeId(),
2097
+ clients_connected: this.clients.size
2098
+ });
2099
+ });
2100
+ this.openaiApp.get("/status", (_req, res) => {
2101
+ res.json(this.getStatus());
2102
+ });
2103
+ this.openaiApp.post("/v1/queue", async (req, res) => {
2104
+ const { tool_id, params, execution_mode = "any" } = req.body;
2105
+ if (!tool_id) {
2106
+ res.status(400).json({ error: "Missing required field: tool_id" });
2107
+ return;
2108
+ }
2109
+ if (!this.networkedExecutor) {
2110
+ res.status(503).json({ error: "Networked executor not available" });
2111
+ return;
2112
+ }
2113
+ try {
2114
+ const jobId = await this.networkedExecutor.queueToolExecution(
2115
+ tool_id,
2116
+ params || {},
2117
+ { executionMode: execution_mode }
2118
+ );
2119
+ res.json({ job_id: jobId, status: "queued" });
2120
+ } catch (error) {
2121
+ res.status(500).json({
2122
+ error: error instanceof Error ? error.message : "Failed to queue job"
2123
+ });
2124
+ }
2125
+ });
2126
+ return new Promise((resolve) => {
2127
+ this.openaiApp.listen(this.openaiPort, () => {
2128
+ resolve();
2129
+ });
2130
+ });
2131
+ }
2132
+ /**
2133
+ * Build a map of local Rainfall tools for quick lookup
2134
+ * Maps OpenAI-style underscore names to Rainfall tool IDs
2135
+ */
2136
+ async buildLocalToolMap() {
2137
+ const map = /* @__PURE__ */ new Map();
2138
+ for (const tool of this.tools) {
2139
+ const openAiName = tool.id.replace(/-/g, "_");
2140
+ map.set(openAiName, {
2141
+ id: tool.id,
2142
+ name: openAiName,
2143
+ description: tool.description
2144
+ });
2145
+ map.set(tool.id, {
2146
+ id: tool.id,
2147
+ name: openAiName,
2148
+ description: tool.description
2149
+ });
2150
+ }
2151
+ return map;
2152
+ }
2153
+ /**
2154
+ * Find a local Rainfall tool by name (OpenAI underscore format or original)
2155
+ */
2156
+ findLocalTool(toolName, localToolMap) {
2157
+ if (localToolMap.has(toolName)) {
2158
+ return localToolMap.get(toolName);
2159
+ }
2160
+ const dashedName = toolName.replace(/_/g, "-");
2161
+ if (localToolMap.has(dashedName)) {
2162
+ return localToolMap.get(dashedName);
2163
+ }
2164
+ return void 0;
2165
+ }
2166
+ /**
2167
+ * Execute a local Rainfall tool
2168
+ */
2169
+ async executeLocalTool(toolId, args) {
2170
+ if (!this.rainfall) {
2171
+ throw new Error("Rainfall SDK not initialized");
2172
+ }
2173
+ const startTime = Date.now();
2174
+ try {
2175
+ const result = await this.rainfall.executeTool(toolId, args);
2176
+ const duration = Date.now() - startTime;
2177
+ this.log(` \u2713 Completed in ${duration}ms`);
2178
+ return result;
2179
+ } catch (error) {
2180
+ const duration = Date.now() - startTime;
2181
+ this.log(` \u2717 Failed after ${duration}ms`);
2182
+ throw error;
2183
+ }
2184
+ }
2185
+ /**
2186
+ * Parse XML-style tool calls from model output
2187
+ * Handles formats like: <function=name><parameter=key>value</parameter></function>
2188
+ */
2189
+ parseXMLToolCalls(content) {
2190
+ const toolCalls = [];
2191
+ const functionRegex = /<function=([^>]+)>([\s\S]*?)<\/function>/gi;
2192
+ let match;
2193
+ while ((match = functionRegex.exec(content)) !== null) {
2194
+ const functionName = match[1].trim();
2195
+ const paramsBlock = match[2];
2196
+ const params = {};
2197
+ const paramRegex = /<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi;
2198
+ let paramMatch;
2199
+ while ((paramMatch = paramRegex.exec(paramsBlock)) !== null) {
2200
+ const paramName = paramMatch[1].trim();
2201
+ const paramValue = paramMatch[2].trim();
2202
+ params[paramName] = paramValue;
2203
+ }
2204
+ toolCalls.push({
2205
+ id: `xml-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
2206
+ type: "function",
2207
+ function: {
2208
+ name: functionName,
2209
+ arguments: JSON.stringify(params)
2210
+ }
2211
+ });
2212
+ this.log(`\u{1F4CB} Parsed XML tool call: ${functionName}(${JSON.stringify(params)})`);
2213
+ }
2214
+ return toolCalls;
2215
+ }
2216
+ /**
2217
+ * Call the LLM via Rainfall backend, LM Studio, RunPod, or other providers
2218
+ *
2219
+ * Provider priority:
2220
+ * 1. Config file (llm.provider, llm.baseUrl)
2221
+ * 2. Environment variables (OPENAI_API_KEY, OLLAMA_HOST, etc.)
2222
+ * 3. Default to Rainfall (credits-based)
2223
+ */
2224
+ async callLLM(params) {
2225
+ if (!this.rainfall) {
2226
+ throw new Error("Rainfall SDK not initialized");
2227
+ }
2228
+ const { loadConfig: loadConfig2, getProviderBaseUrl: getProviderBaseUrl2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2229
+ const config = loadConfig2();
2230
+ const provider = config.llm?.provider || "rainfall";
2231
+ switch (provider) {
2232
+ case "local":
2233
+ case "ollama":
2234
+ return this.callLocalLLM(params, config);
2235
+ case "openai":
2236
+ case "anthropic":
2237
+ return this.callExternalLLM(params, config, provider);
2238
+ case "rainfall":
2239
+ default:
2240
+ return this.rainfall.chatCompletions({
2241
+ subscriber_id: params.subscriberId,
2242
+ model: params.model,
2243
+ messages: params.messages,
2244
+ stream: params.stream || false,
2245
+ temperature: params.temperature,
2246
+ max_tokens: params.max_tokens,
2247
+ tools: params.tools,
2248
+ tool_choice: params.tool_choice,
2249
+ tool_priority: params.tool_priority,
2250
+ enable_stacked: params.enable_stacked
2251
+ });
2252
+ }
2253
+ }
2254
+ /**
2255
+ * Call external LLM provider (OpenAI, Anthropic) via their OpenAI-compatible APIs
2256
+ */
2257
+ async callExternalLLM(params, config, provider) {
2258
+ const { getProviderBaseUrl: getProviderBaseUrl2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2259
+ const baseUrl = config.llm?.baseUrl || getProviderBaseUrl2({ llm: { provider } });
2260
+ const apiKey = config.llm?.apiKey;
2261
+ if (!apiKey) {
2262
+ throw new Error(`${provider} API key not configured. Set via: rainfall config set llm.apiKey <key>`);
2263
+ }
2264
+ const model = params.model || config.llm?.model || (provider === "anthropic" ? "claude-3-5-sonnet-20241022" : "gpt-4o");
2265
+ const url = `${baseUrl}/chat/completions`;
2266
+ const response = await fetch(url, {
2267
+ method: "POST",
2268
+ headers: {
2269
+ "Content-Type": "application/json",
2270
+ "Authorization": `Bearer ${apiKey}`
2271
+ },
2272
+ body: JSON.stringify({
2273
+ model,
2274
+ messages: params.messages,
2275
+ tools: params.tools,
2276
+ tool_choice: params.tool_choice,
2277
+ temperature: params.temperature,
2278
+ max_tokens: params.max_tokens,
2279
+ stream: false
2280
+ // Tool loop requires non-streaming
2281
+ })
2282
+ });
2283
+ if (!response.ok) {
2284
+ const error = await response.text();
2285
+ throw new Error(`${provider} API error: ${error}`);
2286
+ }
2287
+ return response.json();
2288
+ }
2289
+ /**
2290
+ * Call a local LLM (LM Studio, Ollama, etc.)
2291
+ */
2292
+ async callLocalLLM(params, config) {
2293
+ const baseUrl = config.llm?.baseUrl || "http://localhost:1234/v1";
2294
+ const apiKey = config.llm?.apiKey || "not-needed";
2295
+ const model = params.model || config.llm?.model || "local-model";
2296
+ const url = `${baseUrl}/chat/completions`;
2297
+ const response = await fetch(url, {
2298
+ method: "POST",
2299
+ headers: {
2300
+ "Content-Type": "application/json",
2301
+ "Authorization": `Bearer ${apiKey}`
2302
+ },
2303
+ body: JSON.stringify({
2304
+ model,
2305
+ messages: params.messages,
2306
+ tools: params.tools,
2307
+ tool_choice: params.tool_choice,
2308
+ temperature: params.temperature,
2309
+ max_tokens: params.max_tokens,
2310
+ stream: false
2311
+ // Tool loop requires non-streaming
2312
+ })
2313
+ });
2314
+ if (!response.ok) {
2315
+ const error = await response.text();
2316
+ throw new Error(`Local LLM error: ${error}`);
2317
+ }
2318
+ return response.json();
2319
+ }
2320
+ /**
2321
+ * Stream a response to the client (converts non-streaming to SSE format)
2322
+ */
2323
+ async streamResponse(res, response) {
2324
+ res.setHeader("Content-Type", "text/event-stream");
2325
+ res.setHeader("Cache-Control", "no-cache");
2326
+ res.setHeader("Connection", "keep-alive");
2327
+ const message = response.choices?.[0]?.message;
2328
+ const id = response.id || `chatcmpl-${Date.now()}`;
2329
+ const model = response.model || "unknown";
2330
+ const created = Math.floor(Date.now() / 1e3);
2331
+ res.write(`data: ${JSON.stringify({
2332
+ id,
2333
+ object: "chat.completion.chunk",
2334
+ created,
2335
+ model,
2336
+ choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }]
2337
+ })}
2338
+
2339
+ `);
2340
+ const content = message?.content || "";
2341
+ const chunkSize = 10;
2342
+ for (let i = 0; i < content.length; i += chunkSize) {
2343
+ const chunk = content.slice(i, i + chunkSize);
2344
+ res.write(`data: ${JSON.stringify({
2345
+ id,
2346
+ object: "chat.completion.chunk",
2347
+ created,
2348
+ model,
2349
+ choices: [{ index: 0, delta: { content: chunk }, finish_reason: null }]
2350
+ })}
2351
+
2352
+ `);
2353
+ }
2354
+ res.write(`data: ${JSON.stringify({
2355
+ id,
2356
+ object: "chat.completion.chunk",
2357
+ created,
2358
+ model,
2359
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }]
2360
+ })}
2361
+
2362
+ `);
2363
+ res.write("data: [DONE]\n\n");
2364
+ res.end();
2365
+ }
2366
+ /**
2367
+ * Update context with conversation history
2368
+ */
2369
+ updateContext(originalMessages, response) {
2370
+ if (!this.context) return;
2371
+ const lastUserMessage = originalMessages.filter((m) => m.role === "user").pop();
2372
+ if (lastUserMessage) {
2373
+ this.context.addMessage("user", lastUserMessage.content);
2374
+ }
2375
+ const assistantContent = response.choices?.[0]?.message?.content;
2376
+ if (assistantContent) {
2377
+ this.context.addMessage("assistant", assistantContent);
2378
+ }
2379
+ }
2380
+ async getOpenAITools() {
2381
+ const tools = [];
2382
+ for (const tool of this.tools.slice(0, 128)) {
2383
+ const schema = await this.getToolSchema(tool.id);
2384
+ if (schema) {
2385
+ const toolSchema = schema;
2386
+ let parameters = { type: "object", properties: {}, required: [] };
2387
+ if (toolSchema.parameters && typeof toolSchema.parameters === "object") {
2388
+ const rawParams = toolSchema.parameters;
2389
+ parameters = {
2390
+ type: rawParams.type || "object",
2391
+ properties: rawParams.properties || {},
2392
+ required: rawParams.required || []
2393
+ };
2394
+ }
2395
+ tools.push({
2396
+ type: "function",
2397
+ function: {
2398
+ name: tool.id.replace(/-/g, "_"),
2399
+ // OpenAI requires underscore names
2400
+ description: toolSchema.description || tool.description,
2401
+ parameters
2402
+ }
2403
+ });
2404
+ }
2405
+ }
2406
+ return tools;
2407
+ }
2408
+ buildResponseContent() {
2409
+ const edgeNodeId = this.networkedExecutor?.getEdgeNodeId();
2410
+ const toolCount = this.tools.length;
2411
+ return `Rainfall daemon online. Edge node: ${edgeNodeId || "local"}. ${toolCount} tools available. What would you like to execute locally or in the cloud?`;
2412
+ }
2413
+ getStatus() {
2414
+ return {
2415
+ running: !!this.wss,
2416
+ port: this.port,
2417
+ openaiPort: this.openaiPort,
2418
+ toolsLoaded: this.tools.length,
2419
+ clientsConnected: this.clients.size,
2420
+ edgeNodeId: this.networkedExecutor?.getEdgeNodeId(),
2421
+ context: this.context?.getStatus() || {
2422
+ memoriesCached: 0,
2423
+ activeSessions: 0,
2424
+ executionHistorySize: 0
2425
+ },
2426
+ listeners: this.listeners?.getStatus() || {
2427
+ fileWatchers: 0,
2428
+ cronTriggers: 0,
2429
+ recentEvents: 0
2430
+ }
2431
+ };
2432
+ }
2433
+ log(...args) {
2434
+ if (this.debug) {
2435
+ console.log(...args);
2436
+ }
2437
+ }
2438
+ };
2439
+ var daemonInstance = null;
2440
+ async function startDaemon(config = {}) {
2441
+ if (daemonInstance) {
2442
+ console.log("Daemon already running");
2443
+ return daemonInstance;
2444
+ }
2445
+ daemonInstance = new RainfallDaemon(config);
2446
+ await daemonInstance.start();
2447
+ return daemonInstance;
2448
+ }
2449
+ async function stopDaemon() {
2450
+ if (!daemonInstance) {
2451
+ console.log("Daemon not running");
2452
+ return;
2453
+ }
2454
+ await daemonInstance.stop();
2455
+ daemonInstance = null;
2456
+ }
2457
+ function getDaemonStatus() {
2458
+ if (!daemonInstance) {
2459
+ return null;
2460
+ }
2461
+ return daemonInstance.getStatus();
2462
+ }
2463
+ function getDaemonInstance() {
2464
+ return daemonInstance;
2465
+ }
2466
+ // Annotate the CommonJS export names for ESM import in node:
2467
+ 0 && (module.exports = {
2468
+ RainfallDaemon,
2469
+ getDaemonInstance,
2470
+ getDaemonStatus,
2471
+ startDaemon,
2472
+ stopDaemon
2473
+ });