lua-cli 2.5.8 → 3.0.0-alpha.10

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 (121) hide show
  1. package/dist/api/chat.api.service.d.ts +8 -0
  2. package/dist/api/chat.api.service.js +50 -0
  3. package/dist/api/job.api.service.d.ts +219 -0
  4. package/dist/api/job.api.service.js +216 -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 +158 -0
  8. package/dist/api/postprocessor.api.service.js +111 -0
  9. package/dist/api/preprocessor.api.service.d.ts +158 -0
  10. package/dist/api/preprocessor.api.service.js +111 -0
  11. package/dist/api/user.data.api.service.d.ts +13 -0
  12. package/dist/api/user.data.api.service.js +20 -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 +176 -41
  16. package/dist/api-exports.js +195 -21
  17. package/dist/cli/command-definitions.js +85 -8
  18. package/dist/commands/chat.js +73 -36
  19. package/dist/commands/compile.js +140 -7
  20. package/dist/commands/dev.js +23 -2
  21. package/dist/commands/index.d.ts +4 -0
  22. package/dist/commands/index.js +4 -0
  23. package/dist/commands/init.js +53 -7
  24. package/dist/commands/jobs.d.ts +20 -0
  25. package/dist/commands/jobs.js +533 -0
  26. package/dist/commands/logs.js +2 -5
  27. package/dist/commands/postprocessors.d.ts +8 -0
  28. package/dist/commands/postprocessors.js +431 -0
  29. package/dist/commands/preprocessors.d.ts +8 -0
  30. package/dist/commands/preprocessors.js +431 -0
  31. package/dist/commands/push.d.ts +3 -2
  32. package/dist/commands/push.js +1216 -7
  33. package/dist/commands/test.d.ts +9 -18
  34. package/dist/commands/test.js +574 -82
  35. package/dist/commands/webhooks.d.ts +18 -0
  36. package/dist/commands/webhooks.js +424 -0
  37. package/dist/common/job.instance.d.ts +80 -0
  38. package/dist/common/job.instance.js +116 -0
  39. package/dist/common/user.instance.d.ts +1 -0
  40. package/dist/common/user.instance.js +9 -0
  41. package/dist/config/constants.d.ts +4 -3
  42. package/dist/config/constants.js +10 -8
  43. package/dist/interfaces/agent.d.ts +2 -1
  44. package/dist/interfaces/chat.d.ts +52 -1
  45. package/dist/interfaces/index.d.ts +10 -0
  46. package/dist/interfaces/index.js +7 -0
  47. package/dist/interfaces/jobs.d.ts +193 -0
  48. package/dist/interfaces/jobs.js +5 -0
  49. package/dist/interfaces/postprocessors.d.ts +35 -0
  50. package/dist/interfaces/postprocessors.js +4 -0
  51. package/dist/interfaces/preprocessors.d.ts +35 -0
  52. package/dist/interfaces/preprocessors.js +4 -0
  53. package/dist/interfaces/webhooks.d.ts +104 -0
  54. package/dist/interfaces/webhooks.js +5 -0
  55. package/dist/services/auth.d.ts +8 -2
  56. package/dist/services/auth.js +35 -3
  57. package/dist/types/api-contracts.d.ts +5 -0
  58. package/dist/types/compile.types.d.ts +49 -0
  59. package/dist/types/index.d.ts +1 -1
  60. package/dist/types/index.js +1 -1
  61. package/dist/types/skill.d.ts +521 -0
  62. package/dist/types/skill.js +471 -0
  63. package/dist/utils/agent-management.d.ts +25 -0
  64. package/dist/utils/agent-management.js +67 -0
  65. package/dist/utils/bundling.d.ts +44 -5
  66. package/dist/utils/bundling.js +723 -23
  67. package/dist/utils/compile.d.ts +63 -0
  68. package/dist/utils/compile.js +712 -36
  69. package/dist/utils/deployment.d.ts +2 -1
  70. package/dist/utils/deployment.js +16 -2
  71. package/dist/utils/dev-api.d.ts +42 -2
  72. package/dist/utils/dev-api.js +177 -4
  73. package/dist/utils/dev-server.d.ts +1 -1
  74. package/dist/utils/dev-server.js +4 -4
  75. package/dist/utils/dynamic-job-bundler.d.ts +17 -0
  76. package/dist/utils/dynamic-job-bundler.js +143 -0
  77. package/dist/utils/init-agent.d.ts +3 -1
  78. package/dist/utils/init-agent.js +6 -4
  79. package/dist/utils/init-prompts.d.ts +2 -1
  80. package/dist/utils/init-prompts.js +14 -9
  81. package/dist/utils/job-management.d.ts +24 -0
  82. package/dist/utils/job-management.js +264 -0
  83. package/dist/utils/postprocessor-management.d.ts +9 -0
  84. package/dist/utils/postprocessor-management.js +118 -0
  85. package/dist/utils/pre-bundle-jobs.d.ts +26 -0
  86. package/dist/utils/pre-bundle-jobs.js +176 -0
  87. package/dist/utils/preprocessor-management.d.ts +9 -0
  88. package/dist/utils/preprocessor-management.js +118 -0
  89. package/dist/utils/sandbox-storage.d.ts +48 -0
  90. package/dist/utils/sandbox-storage.js +114 -0
  91. package/dist/utils/sandbox.d.ts +61 -1
  92. package/dist/utils/sandbox.js +299 -72
  93. package/dist/utils/tool-detection.d.ts +3 -2
  94. package/dist/utils/tool-detection.js +18 -4
  95. package/dist/utils/webhook-management.d.ts +24 -0
  96. package/dist/utils/webhook-management.js +256 -0
  97. package/package.json +1 -1
  98. package/template/README.md +30 -2
  99. package/template/env.example +5 -0
  100. package/template/lua.skill.yaml +47 -0
  101. package/template/package-lock.json +10505 -0
  102. package/template/package.json +2 -1
  103. package/template/src/index.ts +103 -2
  104. package/template/src/jobs/AbandonedBasketProcessorJob.ts +139 -0
  105. package/template/src/jobs/DailyCleanupJob.ts +100 -0
  106. package/template/src/jobs/DataMigrationJob.ts +133 -0
  107. package/template/src/jobs/HealthCheckJob.ts +87 -0
  108. package/template/src/tools/CreateInlineJob.ts +42 -0
  109. package/template/src/tools/GameScoreTrackerTool.ts +356 -0
  110. package/template/src/tools/SmartBasketTool.ts +188 -0
  111. package/template/src/webhooks/PaymentWebhook.ts +113 -0
  112. package/template/src/webhooks/UserEventWebhook.ts +77 -0
  113. package/API_REFERENCE.md +0 -1408
  114. package/CHANGELOG.md +0 -236
  115. package/CLI_REFERENCE.md +0 -908
  116. package/GETTING_STARTED.md +0 -1040
  117. package/INSTANCE_TYPES.md +0 -1158
  118. package/README.md +0 -865
  119. package/TEMPLATE_GUIDE.md +0 -1398
  120. package/USER_DATA_INSTANCE.md +0 -621
  121. package/template/TOOL_EXAMPLES.md +0 -655
@@ -21,5 +21,6 @@ export declare function createDeploymentData(tools: ToolInfo[], distDir: string)
21
21
  * @param tools - Array of detected tools
22
22
  * @param luaDir - Legacy .lua directory for output
23
23
  * @param indexFile - The TypeScript source file for the index
24
+ * @param agentData - Optional resolved agent data from LuaAgent (for new approach)
24
25
  */
25
- export declare function createLegacyDeploymentData(tools: ToolInfo[], luaDir: string, indexFile: TypeScriptSourceFile): Promise<void>;
26
+ export declare function createLegacyDeploymentData(tools: ToolInfo[], luaDir: string, indexFile: TypeScriptSourceFile, agentData?: any): Promise<void>;
@@ -52,10 +52,24 @@ function readPackageJson() {
52
52
  * @param tools - Array of detected tools
53
53
  * @param luaDir - Legacy .lua directory for output
54
54
  * @param indexFile - The TypeScript source file for the index
55
+ * @param agentData - Optional resolved agent data from LuaAgent (for new approach)
55
56
  */
56
- export async function createLegacyDeploymentData(tools, luaDir, indexFile) {
57
+ export async function createLegacyDeploymentData(tools, luaDir, indexFile, agentData) {
57
58
  const config = readSkillConfig();
58
- const skillsMetadata = extractSkillsMetadata(indexFile);
59
+ let skillsMetadata;
60
+ // Check if we have agent data (from LuaAgent approach)
61
+ if (agentData && agentData.skills && agentData.skills.length > 0) {
62
+ // Use skills from LuaAgent
63
+ // Map 'tools' to 'constructorTools' for compatibility with buildSkillsArray
64
+ skillsMetadata = agentData.skills.map((skill) => ({
65
+ ...skill,
66
+ constructorTools: skill.tools || []
67
+ }));
68
+ }
69
+ else {
70
+ // Fall back to legacy approach - extract from index file
71
+ skillsMetadata = extractSkillsMetadata(indexFile);
72
+ }
59
73
  // Map tools to their parent skills
60
74
  const skillToTools = mapToolsToSkills(indexFile);
61
75
  // Build skills array with their associated tools
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { DevVersionResponse, UpdateDevVersionResponse, SandboxIdsMap } from '../interfaces/dev.js';
6
6
  /**
7
- * Sends a chat message to the API with skill override for sandbox testing.
7
+ * Sends a chat message to the API with skill and processor overrides for sandbox testing.
8
8
  *
9
9
  * @param apiKey - User's API key
10
10
  * @param agentId - Agent ID
@@ -13,9 +13,10 @@ import { DevVersionResponse, UpdateDevVersionResponse, SandboxIdsMap } from '../
13
13
  * @param message - Message to send
14
14
  * @param persona - Optional persona override
15
15
  * @param deployData - Deploy data containing all skills
16
+ * @param config - Optional config for processor overrides
16
17
  * @returns The chat response text or null if failed
17
18
  */
18
- export declare function sendChatMessage(apiKey: string, agentId: string, skillId: string, sandboxId: string, message: string, persona: string | undefined, deployData: any): Promise<string | null>;
19
+ export declare function sendChatMessage(apiKey: string, agentId: string, skillId: string, sandboxId: string, message: string, persona: string | undefined, deployData: any, config?: any): Promise<string | null>;
19
20
  /**
20
21
  * Updates an existing sandbox version.
21
22
  *
@@ -59,3 +60,42 @@ export declare function pushSingleSkillToSandbox(apiKey: string, agentId: string
59
60
  * @returns Map of skill names to their sandbox IDs
60
61
  */
61
62
  export declare function pushSkillsToSandbox(apiKey: string, agentId: string, deployData: any, isInitial?: boolean): Promise<SandboxIdsMap>;
63
+ /**
64
+ * Pushes a single preprocessor to the sandbox.
65
+ * Attempts to update existing sandbox version, creates new one if update fails.
66
+ *
67
+ * @param apiKey - User's API key
68
+ * @param agentId - Agent ID
69
+ * @param preprocessorId - PreProcessor ID
70
+ * @param preprocessorData - PreProcessor data to push
71
+ * @param isInitial - Whether this is the initial push (affects logging)
72
+ * @returns True if successful, false otherwise
73
+ */
74
+ export declare function pushSinglePreProcessorToSandbox(apiKey: string, agentId: string, preprocessorId: string, preprocessorData: any, isInitial?: boolean): Promise<boolean>;
75
+ /**
76
+ * Pushes a single postprocessor to the sandbox.
77
+ * Attempts to update existing sandbox version, creates new one if update fails.
78
+ *
79
+ * @param apiKey - User's API key
80
+ * @param agentId - Agent ID
81
+ * @param postprocessorId - PostProcessor ID
82
+ * @param postprocessorData - PostProcessor data to push
83
+ * @param isInitial - Whether this is the initial push (affects logging)
84
+ * @returns True if successful, false otherwise
85
+ */
86
+ export declare function pushSinglePostProcessorToSandbox(apiKey: string, agentId: string, postprocessorId: string, postprocessorData: any, isInitial?: boolean): Promise<boolean>;
87
+ /**
88
+ * Pushes preprocessors and postprocessors to sandbox.
89
+ *
90
+ * @param apiKey - User's API key
91
+ * @param agentId - Agent ID
92
+ * @param config - Configuration with preprocessors and postprocessors
93
+ * @param bundledPreProcessors - Bundled preprocessor data from compilation
94
+ * @param bundledPostProcessors - Bundled postprocessor data from compilation
95
+ * @param isInitial - Whether this is the initial push
96
+ * @returns Object with counts of pushed processors
97
+ */
98
+ export declare function pushProcessorsToSandbox(apiKey: string, agentId: string, config: any, bundledPreProcessors: any[], bundledPostProcessors: any[], isInitial?: boolean): Promise<{
99
+ preprocessors: number;
100
+ postprocessors: number;
101
+ }>;
@@ -4,12 +4,14 @@
4
4
  */
5
5
  import ChatApi from '../api/chat.api.service.js';
6
6
  import SkillApi from '../api/skills.api.service.js';
7
+ import PreProcessorApi from '../api/preprocessor.api.service.js';
8
+ import PostProcessorApi from '../api/postprocessor.api.service.js';
7
9
  import { BASE_URLS } from '../config/constants.js';
8
10
  import { writeProgress, writeSuccess } from './cli.js';
9
11
  import { loadEnvironmentVariables } from './sandbox.js';
10
- import { getSandboxSkillId, setSandboxSkillId, getAllSandboxSkillIds } from './sandbox-storage.js';
12
+ import { getSandboxSkillId, setSandboxSkillId, getAllSandboxSkillIds, getSandboxPreProcessorId, setSandboxPreProcessorId, getSandboxPostProcessorId, setSandboxPostProcessorId } from './sandbox-storage.js';
11
13
  /**
12
- * Sends a chat message to the API with skill override for sandbox testing.
14
+ * Sends a chat message to the API with skill and processor overrides for sandbox testing.
13
15
  *
14
16
  * @param apiKey - User's API key
15
17
  * @param agentId - Agent ID
@@ -18,9 +20,10 @@ import { getSandboxSkillId, setSandboxSkillId, getAllSandboxSkillIds } from './s
18
20
  * @param message - Message to send
19
21
  * @param persona - Optional persona override
20
22
  * @param deployData - Deploy data containing all skills
23
+ * @param config - Optional config for processor overrides
21
24
  * @returns The chat response text or null if failed
22
25
  */
23
- export async function sendChatMessage(apiKey, agentId, skillId, sandboxId, message, persona, deployData) {
26
+ export async function sendChatMessage(apiKey, agentId, skillId, sandboxId, message, persona, deployData, config) {
24
27
  try {
25
28
  // Get all sandbox skill IDs for skill override
26
29
  const allSkillOverrides = await getAllSandboxSkillIds(deployData);
@@ -31,6 +34,10 @@ export async function sendChatMessage(apiKey, agentId, skillId, sandboxId, messa
31
34
  sandboxId: sandboxId
32
35
  }
33
36
  ];
37
+ // Get sandbox processor overrides if config provided
38
+ const { getAllSandboxPreProcessorIds, getAllSandboxPostProcessorIds } = await import('./sandbox-storage.js');
39
+ const preprocessorOverride = config ? await getAllSandboxPreProcessorIds(config) : [];
40
+ const postprocessorOverride = config ? await getAllSandboxPostProcessorIds(config) : [];
34
41
  const chatRequest = {
35
42
  messages: [
36
43
  {
@@ -39,7 +46,9 @@ export async function sendChatMessage(apiKey, agentId, skillId, sandboxId, messa
39
46
  }
40
47
  ],
41
48
  navigate: true,
42
- skillOverride: skillOverride
49
+ skillOverride: skillOverride,
50
+ preprocessorOverride: preprocessorOverride,
51
+ postprocessorOverride: postprocessorOverride
43
52
  };
44
53
  // Add persona override if provided
45
54
  if (persona) {
@@ -260,3 +269,167 @@ export async function pushSkillsToSandbox(apiKey, agentId, deployData, isInitial
260
269
  }
261
270
  return sandboxIds;
262
271
  }
272
+ /**
273
+ * Pushes a single preprocessor to the sandbox.
274
+ * Attempts to update existing sandbox version, creates new one if update fails.
275
+ *
276
+ * @param apiKey - User's API key
277
+ * @param agentId - Agent ID
278
+ * @param preprocessorId - PreProcessor ID
279
+ * @param preprocessorData - PreProcessor data to push
280
+ * @param isInitial - Whether this is the initial push (affects logging)
281
+ * @returns True if successful, false otherwise
282
+ */
283
+ export async function pushSinglePreProcessorToSandbox(apiKey, agentId, preprocessorId, preprocessorData, isInitial = false) {
284
+ const preprocessorName = preprocessorData.name || 'Unknown PreProcessor';
285
+ const sandboxPreProcessorId = await getSandboxPreProcessorId(preprocessorName);
286
+ // Ensure version has -sandbox postfix
287
+ const baseVersion = preprocessorData.version || '1.0.0';
288
+ const sandboxVersion = baseVersion.endsWith('-sandbox') ? baseVersion : `${baseVersion}-sandbox`;
289
+ const payload = {
290
+ name: preprocessorName,
291
+ version: sandboxVersion,
292
+ description: preprocessorData.description,
293
+ context: preprocessorData.context,
294
+ code: preprocessorData.code,
295
+ executeFunction: preprocessorData.executeFunction,
296
+ async: Boolean(preprocessorData.async ?? false)
297
+ };
298
+ if (sandboxPreProcessorId) {
299
+ // Try to update existing sandbox version
300
+ if (!isInitial) {
301
+ writeProgress(`🔄 Updating existing preprocessor sandbox version...`);
302
+ }
303
+ const api = new PreProcessorApi(BASE_URLS.API, apiKey, agentId);
304
+ const updateResult = await api.updateDevPreProcessor(preprocessorId, sandboxPreProcessorId, payload);
305
+ if (updateResult.success && updateResult.data) {
306
+ return true;
307
+ }
308
+ else {
309
+ if (!isInitial) {
310
+ writeProgress("⚠️ Failed to update preprocessor sandbox, creating new one...");
311
+ }
312
+ }
313
+ }
314
+ // Create new sandbox version
315
+ if (!isInitial) {
316
+ writeProgress(`🔄 Creating new preprocessor sandbox version...`);
317
+ }
318
+ const api = new PreProcessorApi(BASE_URLS.API, apiKey, agentId);
319
+ const result = await api.pushDevPreProcessor(preprocessorId, payload);
320
+ if (result.success && result.data) {
321
+ // Store the new sandbox preprocessor ID
322
+ await setSandboxPreProcessorId(result.data.versionId, preprocessorName);
323
+ return true;
324
+ }
325
+ else if (result.error) {
326
+ console.error(`❌ PreProcessor sandbox push failed: ${result.error.message}`);
327
+ return false;
328
+ }
329
+ return false;
330
+ }
331
+ /**
332
+ * Pushes a single postprocessor to the sandbox.
333
+ * Attempts to update existing sandbox version, creates new one if update fails.
334
+ *
335
+ * @param apiKey - User's API key
336
+ * @param agentId - Agent ID
337
+ * @param postprocessorId - PostProcessor ID
338
+ * @param postprocessorData - PostProcessor data to push
339
+ * @param isInitial - Whether this is the initial push (affects logging)
340
+ * @returns True if successful, false otherwise
341
+ */
342
+ export async function pushSinglePostProcessorToSandbox(apiKey, agentId, postprocessorId, postprocessorData, isInitial = false) {
343
+ const postprocessorName = postprocessorData.name || 'Unknown PostProcessor';
344
+ const sandboxPostProcessorId = await getSandboxPostProcessorId(postprocessorName);
345
+ // Ensure version has -sandbox postfix
346
+ const baseVersion = postprocessorData.version || '1.0.0';
347
+ const sandboxVersion = baseVersion.endsWith('-sandbox') ? baseVersion : `${baseVersion}-sandbox`;
348
+ const payload = {
349
+ name: postprocessorName,
350
+ version: sandboxVersion,
351
+ description: postprocessorData.description,
352
+ context: postprocessorData.context,
353
+ code: postprocessorData.code,
354
+ executeFunction: postprocessorData.executeFunction,
355
+ async: Boolean(postprocessorData.async ?? false)
356
+ };
357
+ if (sandboxPostProcessorId) {
358
+ // Try to update existing sandbox version
359
+ if (!isInitial) {
360
+ writeProgress(`🔄 Updating existing postprocessor sandbox version...`);
361
+ }
362
+ const api = new PostProcessorApi(BASE_URLS.API, apiKey, agentId);
363
+ const updateResult = await api.updateDevPostProcessor(postprocessorId, sandboxPostProcessorId, payload);
364
+ if (updateResult.success && updateResult.data) {
365
+ return true;
366
+ }
367
+ else {
368
+ if (!isInitial) {
369
+ writeProgress("⚠️ Failed to update postprocessor sandbox, creating new one...");
370
+ }
371
+ }
372
+ }
373
+ // Create new sandbox version
374
+ if (!isInitial) {
375
+ writeProgress(`🔄 Creating new postprocessor sandbox version...`);
376
+ }
377
+ const api = new PostProcessorApi(BASE_URLS.API, apiKey, agentId);
378
+ const result = await api.pushDevPostProcessor(postprocessorId, payload);
379
+ if (result.success && result.data) {
380
+ // Store the new sandbox postprocessor ID
381
+ await setSandboxPostProcessorId(result.data.versionId, postprocessorName);
382
+ return true;
383
+ }
384
+ else if (result.error) {
385
+ console.error(`❌ PostProcessor sandbox push failed: ${result.error.message}`);
386
+ return false;
387
+ }
388
+ return false;
389
+ }
390
+ /**
391
+ * Pushes preprocessors and postprocessors to sandbox.
392
+ *
393
+ * @param apiKey - User's API key
394
+ * @param agentId - Agent ID
395
+ * @param config - Configuration with preprocessors and postprocessors
396
+ * @param bundledPreProcessors - Bundled preprocessor data from compilation
397
+ * @param bundledPostProcessors - Bundled postprocessor data from compilation
398
+ * @param isInitial - Whether this is the initial push
399
+ * @returns Object with counts of pushed processors
400
+ */
401
+ export async function pushProcessorsToSandbox(apiKey, agentId, config, bundledPreProcessors, bundledPostProcessors, isInitial = false) {
402
+ let preprocessorCount = 0;
403
+ let postprocessorCount = 0;
404
+ // Push preprocessors
405
+ const configPreProcessors = config.preprocessors || [];
406
+ for (const preprocessor of configPreProcessors) {
407
+ const bundled = bundledPreProcessors.find(p => p.name === preprocessor.name);
408
+ if (bundled && bundled.code && preprocessor.preprocessorId) {
409
+ try {
410
+ const success = await pushSinglePreProcessorToSandbox(apiKey, agentId, preprocessor.preprocessorId, bundled, isInitial);
411
+ if (success)
412
+ preprocessorCount++;
413
+ }
414
+ catch (error) {
415
+ console.error(`❌ Failed to push preprocessor ${preprocessor.name}:`, error);
416
+ }
417
+ }
418
+ }
419
+ // Push postprocessors
420
+ const configPostProcessors = config.postprocessors || [];
421
+ for (const postprocessor of configPostProcessors) {
422
+ const bundled = bundledPostProcessors.find(p => p.name === postprocessor.name);
423
+ if (bundled && bundled.code && postprocessor.postprocessorId) {
424
+ try {
425
+ const success = await pushSinglePostProcessorToSandbox(apiKey, agentId, postprocessor.postprocessorId, bundled, isInitial);
426
+ if (success)
427
+ postprocessorCount++;
428
+ }
429
+ catch (error) {
430
+ console.error(`❌ Failed to push postprocessor ${postprocessor.name}:`, error);
431
+ }
432
+ }
433
+ }
434
+ return { preprocessors: preprocessorCount, postprocessors: postprocessorCount };
435
+ }
@@ -21,4 +21,4 @@ export interface DevServer {
21
21
  * @param port - Port to run server on
22
22
  * @returns Server instance with WebSocket and broadcast function
23
23
  */
24
- export declare function createChatServer(apiKey: string, agentId: string, skillId: string, sandboxId: string, port: number): DevServer;
24
+ export declare function createChatServer(apiKey: string, agentId: string, skillId: string, sandboxId: string, port: number, config?: any): DevServer;
@@ -42,7 +42,7 @@ function readDeployJson() {
42
42
  * @param port - Port to run server on
43
43
  * @returns Server instance with WebSocket and broadcast function
44
44
  */
45
- export function createChatServer(apiKey, agentId, skillId, sandboxId, port) {
45
+ export function createChatServer(apiKey, agentId, skillId, sandboxId, port, config) {
46
46
  const deployData = readDeployJson();
47
47
  const server = createServer((req, res) => {
48
48
  // Enable CORS
@@ -56,7 +56,7 @@ export function createChatServer(apiKey, agentId, skillId, sandboxId, port) {
56
56
  }
57
57
  // Route handlers
58
58
  if (req.method === 'POST' && req.url === '/chat') {
59
- handleChatEndpoint(req, res, apiKey, agentId, skillId, sandboxId, deployData);
59
+ handleChatEndpoint(req, res, apiKey, agentId, skillId, sandboxId, deployData, config);
60
60
  return;
61
61
  }
62
62
  if (req.method === 'GET' && req.url === '/persona') {
@@ -173,7 +173,7 @@ export function createChatServer(apiKey, agentId, skillId, sandboxId, port) {
173
173
  /**
174
174
  * Handles POST /chat - Send chat messages
175
175
  */
176
- function handleChatEndpoint(req, res, apiKey, agentId, skillId, sandboxId, deployData) {
176
+ function handleChatEndpoint(req, res, apiKey, agentId, skillId, sandboxId, deployData, config) {
177
177
  let body = '';
178
178
  req.on('data', (chunk) => {
179
179
  body += chunk.toString();
@@ -181,7 +181,7 @@ function handleChatEndpoint(req, res, apiKey, agentId, skillId, sandboxId, deplo
181
181
  req.on('end', async () => {
182
182
  try {
183
183
  const { message, persona } = JSON.parse(body);
184
- const response = await sendChatMessage(apiKey, agentId, skillId, sandboxId, message, persona, deployData);
184
+ const response = await sendChatMessage(apiKey, agentId, skillId, sandboxId, message, persona, deployData, config);
185
185
  res.writeHead(HTTP_STATUS.OK, { 'Content-Type': 'application/json' });
186
186
  res.end(JSON.stringify({
187
187
  success: response !== null,
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Dynamic Job Bundler
3
+ * Handles detection and bundling of Jobs.create() calls within execute functions
4
+ */
5
+ /**
6
+ * Detects if code contains Jobs.create() calls
7
+ */
8
+ export declare function containsJobsCreate(code: string): boolean;
9
+ /**
10
+ * Extracts Jobs.create() execute functions and bundles them with dependencies.
11
+ * Finds execute functions in the code and creates standalone bundles.
12
+ */
13
+ export declare function bundleNestedJobs(code: string, parentName: string, distDir: string): Promise<string>;
14
+ /**
15
+ * Cleans up temporary bundling directory
16
+ */
17
+ export declare function cleanupTempDir(distDir: string): void;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Dynamic Job Bundler
3
+ * Handles detection and bundling of Jobs.create() calls within execute functions
4
+ */
5
+ import { build } from 'esbuild';
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { compressCode } from './compile.js';
9
+ import { sandboxGlobalsPlugin } from './bundling.js';
10
+ /**
11
+ * Detects if code contains Jobs.create() calls
12
+ */
13
+ export function containsJobsCreate(code) {
14
+ const found = /Jobs\.create\s*\(/i.test(code);
15
+ if (found) {
16
+ console.log('[DynamicJobs] ✅ Detected Jobs.create() in code');
17
+ }
18
+ return found;
19
+ }
20
+ /**
21
+ * Extracts Jobs.create() execute functions and bundles them with dependencies.
22
+ * Finds execute functions in the code and creates standalone bundles.
23
+ */
24
+ export async function bundleNestedJobs(code, parentName, distDir) {
25
+ if (!containsJobsCreate(code)) {
26
+ return code;
27
+ }
28
+ console.log(`[DynamicJobs] ⚠️ Jobs.create() with external dependencies not yet fully supported`);
29
+ console.log(`[DynamicJobs] 💡 Recommendation: Use fetch() or lua-cli APIs in job execute functions`);
30
+ console.log(`[DynamicJobs] 📋 Full bundling support planned for v3.1.0`);
31
+ // Return original code as-is
32
+ // The job will have access to lua-cli globals but external packages won't be bundled
33
+ return code;
34
+ }
35
+ /**
36
+ * Helper to extract job execute function from code
37
+ */
38
+ function extractJobExecuteFromCode(code) {
39
+ // This extracts the execute function body
40
+ // For now, return a placeholder that indicates the limitation
41
+ return `
42
+ // Note: This job execute function runs with limited context
43
+ // Use fetch() for external APIs or lua-cli globals (User, Data, Products)
44
+ console.log('Job execute running with user:', user);
45
+ return { executed: true };
46
+ `;
47
+ }
48
+ /**
49
+ * Bundles a job's execute function independently
50
+ */
51
+ async function bundleJobExecuteFunction(executeFunction, jobName, distDir) {
52
+ const tempDir = path.join(distDir, '.temp');
53
+ if (!fs.existsSync(tempDir)) {
54
+ fs.mkdirSync(tempDir, { recursive: true });
55
+ }
56
+ const tempFile = path.join(tempDir, `${jobName}.js`);
57
+ const tempOutput = path.join(tempDir, `${jobName}-bundled.js`);
58
+ try {
59
+ // Extract imports that the execute function might need
60
+ // Common ones: Stripe, axios, etc.
61
+ const moduleCode = `
62
+ // Job execute function for ${jobName}
63
+ // Import dependencies that might be used
64
+ import Stripe from 'stripe';
65
+ import { env, User, Data, Products, Baskets, Orders } from 'lua-cli';
66
+
67
+ // The execute function with all dependencies available
68
+ const executeFunc = ${executeFunction};
69
+
70
+ // Export as default for esbuild to bundle
71
+ export default executeFunc;
72
+ `;
73
+ fs.writeFileSync(tempFile, moduleCode);
74
+ // Bundle with esbuild - bundle ALL dependencies (including Stripe, axios, etc.)
75
+ await build({
76
+ entryPoints: [tempFile],
77
+ bundle: true,
78
+ platform: 'node',
79
+ target: 'node16',
80
+ format: 'cjs',
81
+ minify: true,
82
+ outfile: tempOutput,
83
+ external: [], // Bundle everything except lua-cli APIs (handled by plugin)
84
+ plugins: [sandboxGlobalsPlugin], // This handles lua-cli globals
85
+ // Important: Don't externalize packages like stripe, axios, etc.
86
+ // They need to be included in the bundle
87
+ });
88
+ // Read bundled code (includes all dependencies like Stripe, axios, etc.)
89
+ let bundledCode = fs.readFileSync(tempOutput, 'utf8');
90
+ // Log bundle size for debugging
91
+ console.log(`[DynamicJobs] Bundled size for ${jobName}: ${(bundledCode.length / 1024).toFixed(2)}KB`);
92
+ // Wrap for VM execution - the bundled code includes ALL dependencies
93
+ const wrappedCode = `(async (job) => {
94
+
95
+ ${bundledCode}
96
+
97
+ // Get the execute function from exports
98
+ const executeFunction = module.exports || module.exports.default;
99
+
100
+ // Execute with job
101
+ return await executeFunction(job);
102
+ })`;
103
+ // Compress the wrapped code
104
+ const compressed = compressCode(wrappedCode);
105
+ // Clean up temp files
106
+ try {
107
+ fs.unlinkSync(tempFile);
108
+ fs.unlinkSync(tempOutput);
109
+ }
110
+ catch (cleanupError) {
111
+ // Ignore cleanup errors
112
+ }
113
+ return compressed;
114
+ }
115
+ catch (error) {
116
+ console.warn(`Warning: Could not bundle job execute function ${jobName}:`, error);
117
+ // Clean up on error
118
+ try {
119
+ if (fs.existsSync(tempFile))
120
+ fs.unlinkSync(tempFile);
121
+ if (fs.existsSync(tempOutput))
122
+ fs.unlinkSync(tempOutput);
123
+ }
124
+ catch (cleanupError) {
125
+ // Ignore cleanup errors
126
+ }
127
+ return '';
128
+ }
129
+ }
130
+ /**
131
+ * Cleans up temporary bundling directory
132
+ */
133
+ export function cleanupTempDir(distDir) {
134
+ const tempDir = path.join(distDir, '.temp');
135
+ if (fs.existsSync(tempDir)) {
136
+ try {
137
+ fs.rmSync(tempDir, { recursive: true, force: true });
138
+ }
139
+ catch (error) {
140
+ // Ignore cleanup errors
141
+ }
142
+ }
143
+ }
@@ -28,10 +28,12 @@ export declare function selectBaseAgentType(agentTypes: AgentType[]): AgentType;
28
28
  * @param businessConfig - Business configuration
29
29
  * @param metadata - Agent metadata
30
30
  * @param features - Feature configuration
31
+ * @param existingOrgId - Optional existing organization ID to use
32
+ * @param newOrgName - Optional new organization name (if not using existing)
31
33
  * @returns Agent creation result with agent and org details
32
34
  * @throws Error if agent creation fails
33
35
  */
34
- export declare function createNewAgent(apiKey: string, agentType: AgentType, businessConfig: BusinessConfig, metadata: Record<string, any>, features: Record<string, boolean>): Promise<AgentCreationResult>;
36
+ export declare function createNewAgent(apiKey: string, agentType: AgentType, businessConfig: BusinessConfig, metadata: Record<string, any>, features: Record<string, boolean>, existingOrgId?: string, newOrgName?: string): Promise<AgentCreationResult>;
35
37
  /**
36
38
  * Fetches detailed agent information for an existing agent.
37
39
  * Used when selecting an existing agent during init.
@@ -50,10 +50,12 @@ export function selectBaseAgentType(agentTypes) {
50
50
  * @param businessConfig - Business configuration
51
51
  * @param metadata - Agent metadata
52
52
  * @param features - Feature configuration
53
+ * @param existingOrgId - Optional existing organization ID to use
54
+ * @param newOrgName - Optional new organization name (if not using existing)
53
55
  * @returns Agent creation result with agent and org details
54
56
  * @throws Error if agent creation fails
55
57
  */
56
- export async function createNewAgent(apiKey, agentType, businessConfig, metadata, features) {
58
+ export async function createNewAgent(apiKey, agentType, businessConfig, metadata, features, existingOrgId, newOrgName) {
57
59
  writeProgress("🔄 Creating agent...");
58
60
  const agentData = {
59
61
  id: `agent_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
@@ -67,9 +69,9 @@ export async function createNewAgent(apiKey, agentType, businessConfig, metadata
67
69
  },
68
70
  features,
69
71
  channels: [],
70
- org: {
71
- registeredName: businessConfig.businessName
72
- }
72
+ org: existingOrgId
73
+ ? { id: existingOrgId } // Use existing org
74
+ : { registeredName: newOrgName || businessConfig.businessName } // Create new org
73
75
  };
74
76
  const agentApi = new AgentApi(BASE_URLS.API, apiKey);
75
77
  const createAgentResult = await agentApi.createAgent(agentData);
@@ -42,6 +42,7 @@ export declare function promptFeatureConfiguration(agentType: AgentType): Promis
42
42
  * Prompts for business and agent configuration.
43
43
  * Collects business name, agent name, type, personality, and traits.
44
44
  *
45
+ * @param skipBusinessName - If true, skips business name prompt (for existing orgs)
45
46
  * @returns Complete business configuration
46
47
  */
47
- export declare function promptBusinessConfiguration(): Promise<BusinessConfig>;
48
+ export declare function promptBusinessConfiguration(skipBusinessName?: boolean): Promise<BusinessConfig>;
@@ -115,17 +115,22 @@ export async function promptFeatureConfiguration(agentType) {
115
115
  * Prompts for business and agent configuration.
116
116
  * Collects business name, agent name, type, personality, and traits.
117
117
  *
118
+ * @param skipBusinessName - If true, skips business name prompt (for existing orgs)
118
119
  * @returns Complete business configuration
119
120
  */
120
- export async function promptBusinessConfiguration() {
121
- const { businessName } = await inquirer.prompt([
122
- {
123
- type: "input",
124
- name: "businessName",
125
- message: "Enter business name:",
126
- default: DEFAULT_BUSINESS_NAME
127
- }
128
- ]);
121
+ export async function promptBusinessConfiguration(skipBusinessName = false) {
122
+ let businessName = DEFAULT_BUSINESS_NAME;
123
+ if (!skipBusinessName) {
124
+ const result = await inquirer.prompt([
125
+ {
126
+ type: "input",
127
+ name: "businessName",
128
+ message: "Enter business name:",
129
+ default: DEFAULT_BUSINESS_NAME
130
+ }
131
+ ]);
132
+ businessName = result.businessName;
133
+ }
129
134
  const { agentName } = await inquirer.prompt([
130
135
  {
131
136
  type: "input",
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Job Management Utilities
3
+ * Handles job creation via API and YAML configuration management
4
+ */
5
+ import { SkillConfig } from '../types/compile.types.js';
6
+ /**
7
+ * Ensures all detected jobs exist in the YAML config with valid job IDs.
8
+ * If a job doesn't exist or has no ID, creates it via the API.
9
+ *
10
+ * @param jobsArray - Array of jobs detected from source code
11
+ * @param config - The skill configuration from lua.skill.yaml
12
+ * @returns Updated jobs array with valid job IDs
13
+ */
14
+ export declare function ensureJobsExistInYaml(jobsArray: any[], config: SkillConfig): Promise<any[]>;
15
+ /**
16
+ * Syncs the server jobs with the YAML configuration.
17
+ * Performs a two-way sync:
18
+ * 1. Deletes/deactivates jobs 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 syncServerJobsWithYaml(config: SkillConfig): Promise<string[]>;