lua-cli 2.5.7 → 3.0.0-alpha.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 (124) hide show
  1. package/dist/api/agent.api.service.d.ts +45 -0
  2. package/dist/api/agent.api.service.js +54 -0
  3. package/dist/api/job.api.service.d.ts +210 -0
  4. package/dist/api/job.api.service.js +200 -0
  5. package/dist/api/lazy-instances.d.ts +24 -0
  6. package/dist/api/lazy-instances.js +48 -0
  7. package/dist/api/postprocessor.api.service.d.ts +98 -0
  8. package/dist/api/postprocessor.api.service.js +76 -0
  9. package/dist/api/preprocessor.api.service.d.ts +98 -0
  10. package/dist/api/preprocessor.api.service.js +76 -0
  11. package/dist/api/user.data.api.service.d.ts +28 -0
  12. package/dist/api/user.data.api.service.js +51 -0
  13. package/dist/api/webhook.api.service.d.ts +151 -0
  14. package/dist/api/webhook.api.service.js +134 -0
  15. package/dist/api-exports.d.ts +156 -41
  16. package/dist/api-exports.js +182 -21
  17. package/dist/cli/command-definitions.js +149 -7
  18. package/dist/commands/compile.js +124 -5
  19. package/dist/commands/completion.d.ts +11 -0
  20. package/dist/commands/completion.js +209 -0
  21. package/dist/commands/env.d.ts +3 -2
  22. package/dist/commands/env.js +42 -17
  23. package/dist/commands/features.d.ts +16 -0
  24. package/dist/commands/features.js +352 -0
  25. package/dist/commands/index.d.ts +7 -0
  26. package/dist/commands/index.js +7 -0
  27. package/dist/commands/init.js +53 -7
  28. package/dist/commands/jobs.d.ts +20 -0
  29. package/dist/commands/jobs.js +533 -0
  30. package/dist/commands/logs.js +2 -5
  31. package/dist/commands/persona.d.ts +3 -2
  32. package/dist/commands/persona.js +43 -18
  33. package/dist/commands/postprocessors.d.ts +8 -0
  34. package/dist/commands/postprocessors.js +431 -0
  35. package/dist/commands/preprocessors.d.ts +8 -0
  36. package/dist/commands/preprocessors.js +431 -0
  37. package/dist/commands/push.d.ts +9 -13
  38. package/dist/commands/push.js +937 -69
  39. package/dist/commands/skills.d.ts +16 -0
  40. package/dist/commands/skills.js +438 -0
  41. package/dist/commands/test.d.ts +9 -18
  42. package/dist/commands/test.js +558 -82
  43. package/dist/commands/webhooks.d.ts +18 -0
  44. package/dist/commands/webhooks.js +424 -0
  45. package/dist/common/data.entry.instance.d.ts +7 -0
  46. package/dist/common/data.entry.instance.js +15 -0
  47. package/dist/common/job.instance.d.ts +77 -0
  48. package/dist/common/job.instance.js +108 -0
  49. package/dist/common/order.instance.d.ts +6 -0
  50. package/dist/common/order.instance.js +14 -0
  51. package/dist/common/product.instance.d.ts +6 -0
  52. package/dist/common/product.instance.js +14 -0
  53. package/dist/common/user.instance.d.ts +15 -0
  54. package/dist/common/user.instance.js +38 -0
  55. package/dist/config/constants.d.ts +2 -2
  56. package/dist/config/constants.js +4 -4
  57. package/dist/index.js +14 -3
  58. package/dist/interfaces/agent.d.ts +33 -1
  59. package/dist/interfaces/chat.d.ts +22 -0
  60. package/dist/interfaces/index.d.ts +10 -0
  61. package/dist/interfaces/index.js +7 -0
  62. package/dist/interfaces/jobs.d.ts +172 -0
  63. package/dist/interfaces/jobs.js +5 -0
  64. package/dist/interfaces/message.d.ts +18 -0
  65. package/dist/interfaces/message.js +1 -0
  66. package/dist/interfaces/postprocessors.d.ts +35 -0
  67. package/dist/interfaces/postprocessors.js +4 -0
  68. package/dist/interfaces/preprocessors.d.ts +35 -0
  69. package/dist/interfaces/preprocessors.js +4 -0
  70. package/dist/interfaces/webhooks.d.ts +104 -0
  71. package/dist/interfaces/webhooks.js +5 -0
  72. package/dist/types/api-contracts.d.ts +14 -0
  73. package/dist/types/api-contracts.js +0 -7
  74. package/dist/types/compile.types.d.ts +49 -0
  75. package/dist/types/index.d.ts +1 -1
  76. package/dist/types/index.js +1 -1
  77. package/dist/types/skill.d.ts +502 -0
  78. package/dist/types/skill.js +477 -0
  79. package/dist/utils/agent-management.d.ts +25 -0
  80. package/dist/utils/agent-management.js +67 -0
  81. package/dist/utils/bundling.d.ts +31 -1
  82. package/dist/utils/bundling.js +653 -10
  83. package/dist/utils/compile.d.ts +63 -0
  84. package/dist/utils/compile.js +691 -36
  85. package/dist/utils/deployment.d.ts +2 -1
  86. package/dist/utils/deployment.js +16 -2
  87. package/dist/utils/init-agent.d.ts +3 -1
  88. package/dist/utils/init-agent.js +6 -4
  89. package/dist/utils/init-prompts.d.ts +2 -1
  90. package/dist/utils/init-prompts.js +14 -9
  91. package/dist/utils/job-management.d.ts +24 -0
  92. package/dist/utils/job-management.js +264 -0
  93. package/dist/utils/postprocessor-management.d.ts +9 -0
  94. package/dist/utils/postprocessor-management.js +118 -0
  95. package/dist/utils/preprocessor-management.d.ts +9 -0
  96. package/dist/utils/preprocessor-management.js +118 -0
  97. package/dist/utils/sandbox.d.ts +61 -1
  98. package/dist/utils/sandbox.js +283 -72
  99. package/dist/utils/tool-detection.d.ts +3 -2
  100. package/dist/utils/tool-detection.js +18 -4
  101. package/dist/utils/webhook-management.d.ts +24 -0
  102. package/dist/utils/webhook-management.js +256 -0
  103. package/dist/web/app.css +152 -736
  104. package/dist/web/app.js +45 -45
  105. package/package.json +2 -2
  106. package/template/AGENT_CONFIGURATION.md +251 -0
  107. package/template/COMPLEX_JOB_EXAMPLES.md +795 -0
  108. package/template/DYNAMIC_JOB_CREATION.md +371 -0
  109. package/template/README.md +30 -2
  110. package/template/WEBHOOKS_JOBS_QUICKSTART.md +318 -0
  111. package/template/WEBHOOK_JOB_EXAMPLES.md +817 -0
  112. package/template/package.json +1 -1
  113. package/template/src/index-agent-example.ts +201 -0
  114. package/template/src/index.ts +39 -0
  115. package/template/src/jobs/AbandonedBasketProcessorJob.ts +139 -0
  116. package/template/src/jobs/DailyCleanupJob.ts +100 -0
  117. package/template/src/jobs/DataMigrationJob.ts +133 -0
  118. package/template/src/jobs/HealthCheckJob.ts +87 -0
  119. package/template/src/postprocessors/ResponseFormatter.ts +151 -0
  120. package/template/src/preprocessors/MessageFilter.ts +91 -0
  121. package/template/src/tools/GameScoreTrackerTool.ts +356 -0
  122. package/template/src/tools/SmartBasketTool.ts +188 -0
  123. package/template/src/webhooks/PaymentWebhook.ts +113 -0
  124. package/template/src/webhooks/UserEventWebhook.ts +77 -0
@@ -8,6 +8,27 @@ export interface ExecuteToolOptions extends SandboxOptions {
8
8
  toolCode: string;
9
9
  inputs: any;
10
10
  }
11
+ export interface ExecuteWebhookOptions extends SandboxOptions {
12
+ webhookCode: string;
13
+ query: any;
14
+ headers: any;
15
+ body: any;
16
+ }
17
+ export interface ExecuteJobOptions extends SandboxOptions {
18
+ jobCode: string;
19
+ jobData?: any;
20
+ }
21
+ export interface ExecutePreProcessorOptions extends SandboxOptions {
22
+ processorCode: string;
23
+ message: string;
24
+ channel: string;
25
+ }
26
+ export interface ExecutePostProcessorOptions extends SandboxOptions {
27
+ processorCode: string;
28
+ message: string;
29
+ response: string;
30
+ channel: string;
31
+ }
11
32
  /**
12
33
  * Loads environment variables from multiple sources in priority order:
13
34
  * 1. process.env (lowest priority)
@@ -16,13 +37,52 @@ export interface ExecuteToolOptions extends SandboxOptions {
16
37
  */
17
38
  export declare function loadEnvironmentVariables(): Record<string, string>;
18
39
  /**
19
- * Creates a VM sandbox context with all necessary globals and utilities
40
+ * Creates a VM sandbox context with all necessary globals and utilities.
41
+ *
42
+ * Available globals in the sandbox:
43
+ * - User: User data API
44
+ * - Products: Product catalog API
45
+ * - Data: Custom data collections API
46
+ * - Baskets: Shopping basket API
47
+ * - Orders: Order management API
48
+ * - Webhooks: Webhook management API (new)
49
+ * - Jobs: Job scheduling API (new)
50
+ * - env(): Environment variable access function
51
+ * - console, fetch, and other standard globals
20
52
  */
21
53
  export declare function createSandbox(options: SandboxOptions): any;
22
54
  /**
23
55
  * Executes a tool in a VM sandbox
24
56
  */
25
57
  export declare function executeTool(options: ExecuteToolOptions): Promise<any>;
58
+ /**
59
+ * Executes a webhook in a sandboxed environment.
60
+ *
61
+ * @param options - Webhook execution options including code and request data
62
+ * @returns Result from webhook execution
63
+ */
64
+ export declare function executeWebhook(options: ExecuteWebhookOptions): Promise<any>;
65
+ /**
66
+ * Executes a job in a sandboxed environment.
67
+ *
68
+ * @param options - Job execution options including code and job data
69
+ * @returns Result from job execution
70
+ */
71
+ export declare function executeJob(options: ExecuteJobOptions): Promise<any>;
72
+ /**
73
+ * Executes a preprocessor in a sandboxed environment.
74
+ *
75
+ * @param options - PreProcessor execution options
76
+ * @returns Processed message string
77
+ */
78
+ export declare function executePreProcessor(options: ExecutePreProcessorOptions): Promise<string>;
79
+ /**
80
+ * Executes a postprocessor in a sandboxed environment.
81
+ *
82
+ * @param options - PostProcessor execution options
83
+ * @returns Processed response string
84
+ */
85
+ export declare function executePostProcessor(options: ExecutePostProcessorOptions): Promise<string>;
26
86
  /**
27
87
  * Creates a custom console that broadcasts logs via WebSocket
28
88
  */
@@ -9,6 +9,10 @@ import ProductApiService from "../api/products.api.service.js";
9
9
  import BasketApiService from "../api/basket.api.service.js";
10
10
  import OrderApiService from "../api/order.api.service.js";
11
11
  import CustomDataApiService from "../api/custom.data.api.service.js";
12
+ import WebhookApi from "../api/webhook.api.service.js";
13
+ import JobApi from "../api/job.api.service.js";
14
+ import { BasketStatus } from "../interfaces/baskets.js";
15
+ import { OrderStatus } from "../interfaces/orders.js";
12
16
  /**
13
17
  * Loads environment variables from multiple sources in priority order:
14
18
  * 1. process.env (lowest priority)
@@ -54,7 +58,18 @@ export function loadEnvironmentVariables() {
54
58
  return envVars;
55
59
  }
56
60
  /**
57
- * Creates a VM sandbox context with all necessary globals and utilities
61
+ * Creates a VM sandbox context with all necessary globals and utilities.
62
+ *
63
+ * Available globals in the sandbox:
64
+ * - User: User data API
65
+ * - Products: Product catalog API
66
+ * - Data: Custom data collections API
67
+ * - Baskets: Shopping basket API
68
+ * - Orders: Order management API
69
+ * - Webhooks: Webhook management API (new)
70
+ * - Jobs: Job scheduling API (new)
71
+ * - env(): Environment variable access function
72
+ * - console, fetch, and other standard globals
58
73
  */
59
74
  export function createSandbox(options) {
60
75
  const { apiKey, agentId, customConsole, broadcastLog } = options;
@@ -62,73 +77,6 @@ export function createSandbox(options) {
62
77
  const envVars = loadEnvironmentVariables();
63
78
  // Create a CommonJS context for execution
64
79
  const require = createRequire(process.cwd() + '/package.json');
65
- // const updateUserData = async (data: any) => {
66
- // return await UserDataApi.updateUserData(apiKey, agentId, data);
67
- // };
68
- // const getUserData = async () => {
69
- // return await UserDataApi.getUserData(apiKey, agentId);
70
- // };
71
- // const linkUserData = async (data: any) => {
72
- // return await UserDataApi.createUserData(apiKey, agentId, data);
73
- // };
74
- // const createProduct = async (data: any) => {
75
- // return await ProductApi.createProduct(apiKey, agentId, data);
76
- // };
77
- // const getProducts = async (page: number = 1, limit: number = 10) => {
78
- // return await ProductApi.getProducts(apiKey, agentId, page, limit);
79
- // };
80
- // const updateProduct = async (data: any, productId: string) => {
81
- // return await ProductApi.updateProduct(apiKey, agentId, { ...data, id: productId });
82
- // };
83
- // const deleteProduct = async (productId: string) => {
84
- // return await ProductApi.deleteProduct(apiKey, agentId, productId);
85
- // };
86
- // const createBasket = async (data: any) => {
87
- // return await ProductApi.createBasket(apiKey, agentId, data);
88
- // };
89
- // const getBaskets = async (status?: BasketStatus) => {
90
- // return await ProductApi.getUserBaskets(apiKey, agentId, status);
91
- // };
92
- // const addItemToBasket = async (basketId: string, data: any) => {
93
- // return await ProductApi.addItemToBasket(apiKey, agentId, basketId, data);
94
- // };
95
- // const removeItemFromBasket = async (basketId: string, itemId: string) => {
96
- // return await ProductApi.removeItemFromBasket(apiKey, agentId, basketId, itemId);
97
- // };
98
- // const clearBasket = async (basketId: string) => {
99
- // return await ProductApi.clearBasket(apiKey, agentId, basketId);
100
- // };
101
- // const updateBasketStatus = async (basketId: string, status: BasketStatus) => {
102
- // return await ProductApi.updateBasketStatus(apiKey, agentId, basketId, status);
103
- // };
104
- // const createOrder = async (data: any) => {
105
- // return await ProductApi.createOrder(apiKey, agentId, data);
106
- // };
107
- // const updateOrderStatus = async (orderId: string, status: OrderStatus) => {
108
- // return await ProductApi.updateOrderStatus(apiKey, agentId, orderId, status);
109
- // };
110
- // const getUserOrders = async (userId: string) => {
111
- // return await ProductApi.getUserOrders(apiKey, agentId, userId);
112
- // };
113
- // // Custom Data API functions
114
- // const createCustomData = async (collectionName: string, data: any) => {
115
- // return await CustomDataApi.createCustomData(apiKey, agentId, collectionName, data);
116
- // };
117
- // const getCustomData = async (collectionName: string, filter?: any, page: number = 1, limit: number = 10) => {
118
- // return await CustomDataApi.getCustomData(apiKey, agentId, collectionName, filter, page, limit);
119
- // };
120
- // const getCustomDataEntry = async (collectionName: string, entryId: string) => {
121
- // return await CustomDataApi.getCustomDataEntry(apiKey, agentId, collectionName, entryId);
122
- // };
123
- // const updateCustomData = async (collectionName: string, entryId: string, data: any) => {
124
- // return await CustomDataApi.updateCustomData(apiKey, agentId, collectionName, entryId, data);
125
- // };
126
- // const searchCustomData = async (collectionName: string, searchText: string, limit: number = 10, scoreThreshold: number = 0.6) => {
127
- // return await CustomDataApi.searchCustomData(apiKey, agentId, collectionName, searchText, limit, scoreThreshold);
128
- // };
129
- // const deleteCustomData = async (collectionName: string, entryId: string) => {
130
- // return await CustomDataApi.deleteCustomData(apiKey, agentId, collectionName, entryId);
131
- // };
132
80
  // Create console object (use custom console if provided, otherwise default)
133
81
  const consoleObj = customConsole || console;
134
82
  // Create API service instances
@@ -137,6 +85,8 @@ export function createSandbox(options) {
137
85
  const dataService = new CustomDataApiService(BASE_URLS.API, apiKey, agentId);
138
86
  const basketsService = new BasketApiService(BASE_URLS.API, apiKey, agentId);
139
87
  const orderService = new OrderApiService(BASE_URLS.API, apiKey, agentId);
88
+ const webhookService = new WebhookApi(BASE_URLS.API, apiKey, agentId);
89
+ const jobService = new JobApi(BASE_URLS.API, apiKey, agentId);
140
90
  // Override User service methods if needed
141
91
  // Example: Override the update method
142
92
  // const originalUpdate = userService.update.bind(userService);
@@ -232,9 +182,6 @@ export function createSandbox(options) {
232
182
  setInterval,
233
183
  clearTimeout,
234
184
  clearInterval,
235
- process: {
236
- env: envVars
237
- },
238
185
  global: globalThis,
239
186
  __dirname: process.cwd(),
240
187
  __filename: path.join(process.cwd(), 'index.ts'),
@@ -275,8 +222,52 @@ export function createSandbox(options) {
275
222
  Data: dataService,
276
223
  Baskets: basketsService,
277
224
  Orders: orderService,
225
+ // Jobs API
226
+ Jobs: {
227
+ create: async (config) => {
228
+ // Convert execute function to string
229
+ const executeString = typeof config.execute === 'function'
230
+ ? config.execute.toString()
231
+ : config.execute;
232
+ // Create job
233
+ return await jobService.createJobInstance({
234
+ name: config.name,
235
+ description: config.description,
236
+ context: config.description || '',
237
+ schedule: config.schedule,
238
+ timeout: config.timeout,
239
+ retry: config.retry
240
+ });
241
+ },
242
+ get: async (jobId) => jobService.getJob(jobId)
243
+ },
278
244
  // Environment variables function
279
- env: (key) => envVars[key]
245
+ env: (key) => envVars[key],
246
+ // Enums for status values
247
+ BasketStatus: BasketStatus,
248
+ OrderStatus: OrderStatus,
249
+ // AI Generation API
250
+ AI: {
251
+ generate: async (context, messages, targetAgentId) => {
252
+ const ChatApi = (await import('../api/chat.api.service.js')).default;
253
+ const chatService = new ChatApi(BASE_URLS.API, apiKey);
254
+ // Use provided agentId or default to current agent
255
+ const useAgentId = targetAgentId || 'luaAgent';
256
+ const result = await chatService.sendMessage(useAgentId, {
257
+ messages,
258
+ navigate: false,
259
+ skillOverride: [],
260
+ runtimeContext: context
261
+ });
262
+ if (!result.success) {
263
+ throw new Error(result.error?.message || 'AI generation failed');
264
+ }
265
+ return result.data?.text || '';
266
+ }
267
+ },
268
+ process: {
269
+ env: envVars
270
+ }
280
271
  };
281
272
  return sandbox;
282
273
  }
@@ -324,6 +315,226 @@ try{
324
315
  const executeFunction = context.module.exports;
325
316
  return await executeFunction(inputs);
326
317
  }
318
+ /**
319
+ * Executes a webhook in a sandboxed environment.
320
+ *
321
+ * @param options - Webhook execution options including code and request data
322
+ * @returns Result from webhook execution
323
+ */
324
+ export async function executeWebhook(options) {
325
+ const { webhookCode, query, headers, body } = options;
326
+ // Create sandbox
327
+ const sandbox = createSandbox(options);
328
+ // Create the CommonJS wrapper code
329
+ const commonJsWrapper = `
330
+ const executeFunction = ${webhookCode};
331
+
332
+ // Export the function for testing
333
+ module.exports = async (input) => {
334
+ try{
335
+ return await executeFunction(input);
336
+ }catch(e){
337
+ console.error(e);
338
+ return { status: 'error', error: e.message };
339
+ }
340
+ };
341
+ `;
342
+ // Execute the code in the sandbox
343
+ const context = vm.createContext(sandbox);
344
+ // Add polyfills
345
+ vm.runInContext(`
346
+ if (typeof global !== 'undefined') {
347
+ global.AbortController = AbortController;
348
+ global.FormData = FormData;
349
+ global.TextEncoder = TextEncoder;
350
+ global.TextDecoder = TextDecoder;
351
+ global.crypto = crypto;
352
+ global.fetch = fetch;
353
+ global.Headers = Headers;
354
+ global.Request = Request;
355
+ global.Response = Response;
356
+ global.URL = URL;
357
+ global.URLSearchParams = URLSearchParams;
358
+ }
359
+ `, context);
360
+ vm.runInContext(commonJsWrapper, context);
361
+ // Get the exported function and execute with webhook input structure
362
+ const executeFunction = context.module.exports;
363
+ return await executeFunction({ query, headers, body });
364
+ }
365
+ /**
366
+ * Executes a job in a sandboxed environment.
367
+ *
368
+ * @param options - Job execution options including code and job data
369
+ * @returns Result from job execution
370
+ */
371
+ export async function executeJob(options) {
372
+ const { jobCode, jobData, apiKey, agentId } = options;
373
+ // Create sandbox
374
+ const sandbox = createSandbox(options);
375
+ // Create the CommonJS wrapper code that creates JobInstance from jobData
376
+ const commonJsWrapper = `
377
+ const executeFunction = ${jobCode};
378
+
379
+ // Export the function for testing
380
+ module.exports = async (jobData) => {
381
+ try{
382
+ // Create job instance from jobData if provided
383
+ let jobInstance = undefined;
384
+ if (jobData) {
385
+ jobInstance = {
386
+ id: jobData.id || jobData.jobId,
387
+ jobId: jobData.jobId || jobData.id,
388
+ name: jobData.name,
389
+ schedule: jobData.schedule,
390
+ metadata: jobData.metadata || {},
391
+ data: jobData,
392
+ updateMetadata: async (newMetadata) => {
393
+ jobInstance.metadata = { ...jobInstance.metadata, ...newMetadata };
394
+ console.log('✅ Metadata updated:', jobInstance.metadata);
395
+ },
396
+ delete: async () => {
397
+ console.log('🗑️ Job.delete() called for:', jobInstance.jobId);
398
+ // Note: In production, this would call Jobs.deactivate(jobId)
399
+ },
400
+ toJSON: () => jobData
401
+ };
402
+ }
403
+
404
+ return await executeFunction(jobInstance);
405
+ }catch(e){
406
+ console.error(e);
407
+ return { status: 'error', error: e.message };
408
+ }
409
+ };
410
+ `;
411
+ // Execute the code in the sandbox
412
+ const context = vm.createContext(sandbox);
413
+ // Add polyfills
414
+ vm.runInContext(`
415
+ if (typeof global !== 'undefined') {
416
+ global.AbortController = AbortController;
417
+ global.FormData = FormData;
418
+ global.TextEncoder = TextEncoder;
419
+ global.TextDecoder = TextDecoder;
420
+ global.crypto = crypto;
421
+ global.fetch = fetch;
422
+ global.Headers = Headers;
423
+ global.Request = Request;
424
+ global.Response = Response;
425
+ global.URL = URL;
426
+ global.URLSearchParams = URLSearchParams;
427
+ }
428
+ `, context);
429
+ vm.runInContext(commonJsWrapper, context);
430
+ // Get the exported function and execute with jobData
431
+ const executeFunction = context.module.exports;
432
+ return await executeFunction(jobData);
433
+ }
434
+ /**
435
+ * Executes a preprocessor in a sandboxed environment.
436
+ *
437
+ * @param options - PreProcessor execution options
438
+ * @returns Processed message string
439
+ */
440
+ export async function executePreProcessor(options) {
441
+ const { processorCode, message, channel, apiKey, agentId } = options;
442
+ // Create sandbox
443
+ const sandbox = createSandbox(options);
444
+ // Get user instance first (outside VM)
445
+ const UserDataApi = (await import('../api/user.data.api.service.js')).default;
446
+ const userService = new UserDataApi(BASE_URLS.API, apiKey, agentId);
447
+ const userInstance = await userService.get();
448
+ // Create the CommonJS wrapper code
449
+ const commonJsWrapper = `
450
+ const executeFunction = ${processorCode};
451
+
452
+ // Export the function for testing
453
+ module.exports = async (input) => {
454
+ try{
455
+ // userInstance is passed as parameter
456
+ return await executeFunction(input.user, input.message, input.channel);
457
+ }catch(e){
458
+ console.error(e);
459
+ return { status: 'error', error: e.message };
460
+ }
461
+ };
462
+ `;
463
+ // Execute the code in the sandbox
464
+ const context = vm.createContext(sandbox);
465
+ // Add polyfills
466
+ vm.runInContext(`
467
+ if (typeof global !== 'undefined') {
468
+ global.AbortController = AbortController;
469
+ global.FormData = FormData;
470
+ global.TextEncoder = TextEncoder;
471
+ global.TextDecoder = TextDecoder;
472
+ global.crypto = crypto;
473
+ global.fetch = fetch;
474
+ global.Headers = Headers;
475
+ global.Request = Request;
476
+ global.Response = Response;
477
+ global.URL = URL;
478
+ global.URLSearchParams = URLSearchParams;
479
+ }
480
+ `, context);
481
+ vm.runInContext(commonJsWrapper, context);
482
+ // Get the exported function and execute with user instance
483
+ const executeFunction = context.module.exports;
484
+ return await executeFunction({ user: userInstance, message, channel });
485
+ }
486
+ /**
487
+ * Executes a postprocessor in a sandboxed environment.
488
+ *
489
+ * @param options - PostProcessor execution options
490
+ * @returns Processed response string
491
+ */
492
+ export async function executePostProcessor(options) {
493
+ const { processorCode, message, response, channel, apiKey, agentId } = options;
494
+ // Create sandbox
495
+ const sandbox = createSandbox(options);
496
+ // Get user instance first (outside VM)
497
+ const UserDataApi = (await import('../api/user.data.api.service.js')).default;
498
+ const userService = new UserDataApi(BASE_URLS.API, apiKey, agentId);
499
+ const userInstance = await userService.get();
500
+ // Create the CommonJS wrapper code
501
+ const commonJsWrapper = `
502
+ const executeFunction = ${processorCode};
503
+
504
+ // Export the function for testing
505
+ module.exports = async (input) => {
506
+ try{
507
+ // userInstance is passed as parameter
508
+ return await executeFunction(input.user, input.message, input.response, input.channel);
509
+ }catch(e){
510
+ console.error(e);
511
+ return { status: 'error', error: e.message };
512
+ }
513
+ };
514
+ `;
515
+ // Execute the code in the sandbox
516
+ const context = vm.createContext(sandbox);
517
+ // Add polyfills
518
+ vm.runInContext(`
519
+ if (typeof global !== 'undefined') {
520
+ global.AbortController = AbortController;
521
+ global.FormData = FormData;
522
+ global.TextEncoder = TextEncoder;
523
+ global.TextDecoder = TextDecoder;
524
+ global.crypto = crypto;
525
+ global.fetch = fetch;
526
+ global.Headers = Headers;
527
+ global.Request = Request;
528
+ global.Response = Response;
529
+ global.URL = URL;
530
+ global.URLSearchParams = URLSearchParams;
531
+ }
532
+ `, context);
533
+ vm.runInContext(commonJsWrapper, context);
534
+ // Get the exported function and execute with user instance
535
+ const executeFunction = context.module.exports;
536
+ return await executeFunction({ user: userInstance, message, response, channel });
537
+ }
327
538
  /**
328
539
  * Creates a custom console that broadcasts logs via WebSocket
329
540
  */
@@ -6,13 +6,14 @@ import { Project } from "ts-morph";
6
6
  import { ToolInfo } from '../interfaces/compile.js';
7
7
  import { TypeScriptSourceFile } from '../types/compile.types.js';
8
8
  /**
9
- * Detects all tools in the project by analyzing the index file.
9
+ * Detects all tools in the project by analyzing the index file and skill files.
10
10
  * Searches for tools in two places:
11
11
  * 1. LuaSkill constructor's tools array
12
12
  * 2. skill.addTools() or skill.addTool() method calls
13
13
  *
14
14
  * @param indexFile - The main index TypeScript source file
15
15
  * @param project - The ts-morph Project instance
16
+ * @param skillFilePaths - Optional array of skill file paths to scan for tools (for LuaAgent)
16
17
  * @returns Promise resolving to array of detected tool information
17
18
  */
18
- export declare function detectTools(indexFile: TypeScriptSourceFile, project: Project): Promise<ToolInfo[]>;
19
+ export declare function detectTools(indexFile: TypeScriptSourceFile, project: Project, skillFilePaths?: string[]): Promise<ToolInfo[]>;
@@ -5,21 +5,35 @@
5
5
  import { Node } from "ts-morph";
6
6
  import { extractToolFromNewExpressionSync, } from './compile.js';
7
7
  /**
8
- * Detects all tools in the project by analyzing the index file.
8
+ * Detects all tools in the project by analyzing the index file and skill files.
9
9
  * Searches for tools in two places:
10
10
  * 1. LuaSkill constructor's tools array
11
11
  * 2. skill.addTools() or skill.addTool() method calls
12
12
  *
13
13
  * @param indexFile - The main index TypeScript source file
14
14
  * @param project - The ts-morph Project instance
15
+ * @param skillFilePaths - Optional array of skill file paths to scan for tools (for LuaAgent)
15
16
  * @returns Promise resolving to array of detected tool information
16
17
  */
17
- export async function detectTools(indexFile, project) {
18
+ export async function detectTools(indexFile, project, skillFilePaths) {
18
19
  const tools = [];
19
- // Search strategy 1: Find tools in LuaSkill constructor's tools array
20
+ // Search strategy 1: Find tools in LuaSkill constructor's tools array in index file
20
21
  detectToolsFromConstructor(indexFile, project, tools);
21
- // Search strategy 2: Find tools from skill.addTools() or skill.addTool() method calls
22
+ // Search strategy 2: Find tools from skill.addTools() or skill.addTool() method calls in index file
22
23
  detectToolsFromMethodCalls(indexFile, project, tools);
24
+ // Search strategy 3: If skill files are provided (from LuaAgent), scan those too
25
+ if (skillFilePaths && skillFilePaths.length > 0) {
26
+ for (const skillFilePath of skillFilePaths) {
27
+ try {
28
+ const skillFile = project.addSourceFileAtPath(skillFilePath);
29
+ detectToolsFromConstructor(skillFile, project, tools);
30
+ detectToolsFromMethodCalls(skillFile, project, tools);
31
+ }
32
+ catch (error) {
33
+ console.warn(`Warning: Could not scan skill file ${skillFilePath} for tools:`, error);
34
+ }
35
+ }
36
+ }
23
37
  return tools;
24
38
  }
25
39
  /**
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Webhook Management Utilities
3
+ * Handles webhook creation via API and YAML configuration management
4
+ */
5
+ import { SkillConfig } from '../types/compile.types.js';
6
+ /**
7
+ * Ensures all detected webhooks exist in the YAML config with valid webhook IDs.
8
+ * If a webhook doesn't exist or has no ID, creates it via the API.
9
+ *
10
+ * @param webhooksArray - Array of webhooks detected from source code
11
+ * @param config - The skill configuration from lua.skill.yaml
12
+ * @returns Updated webhooks array with valid webhook IDs
13
+ */
14
+ export declare function ensureWebhooksExistInYaml(webhooksArray: any[], config: SkillConfig): Promise<any[]>;
15
+ /**
16
+ * Syncs the server webhooks with the YAML configuration.
17
+ * Performs a two-way sync:
18
+ * 1. Deletes/deactivates webhooks from server that aren't in YAML
19
+ * 2. Updates YAML with active version numbers from server
20
+ *
21
+ * @param config - The skill configuration from lua.skill.yaml
22
+ * @returns Array of messages about sync operations
23
+ */
24
+ export declare function syncServerWebhooksWithYaml(config: SkillConfig): Promise<string[]>;