snow-flow 1.1.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 (240) hide show
  1. package/.env.example +49 -0
  2. package/.mcp.json +106 -0
  3. package/.mcp.json.template +106 -0
  4. package/LICENSE +21 -0
  5. package/README.md +236 -0
  6. package/bin/snow-flow +4 -0
  7. package/bin/snow-flow.js +3 -0
  8. package/claude-flow +79 -0
  9. package/claude-flow.bat +18 -0
  10. package/claude-flow.config.json +20 -0
  11. package/claude-flow.ps1 +24 -0
  12. package/dist/agents/app-creator.agent.d.ts +55 -0
  13. package/dist/agents/app-creator.agent.d.ts.map +1 -0
  14. package/dist/agents/app-creator.agent.js +1292 -0
  15. package/dist/agents/app-creator.agent.js.map +1 -0
  16. package/dist/agents/base-snow-agent.d.ts +63 -0
  17. package/dist/agents/base-snow-agent.d.ts.map +1 -0
  18. package/dist/agents/base-snow-agent.js +296 -0
  19. package/dist/agents/base-snow-agent.js.map +1 -0
  20. package/dist/agents/script-generator.agent.d.ts +32 -0
  21. package/dist/agents/script-generator.agent.d.ts.map +1 -0
  22. package/dist/agents/script-generator.agent.js +772 -0
  23. package/dist/agents/script-generator.agent.js.map +1 -0
  24. package/dist/agents/ui-builder.agent.d.ts +50 -0
  25. package/dist/agents/ui-builder.agent.d.ts.map +1 -0
  26. package/dist/agents/ui-builder.agent.js +1539 -0
  27. package/dist/agents/ui-builder.agent.js.map +1 -0
  28. package/dist/agents/widget-builder.agent.d.ts +32 -0
  29. package/dist/agents/widget-builder.agent.d.ts.map +1 -0
  30. package/dist/agents/widget-builder.agent.js +439 -0
  31. package/dist/agents/widget-builder.agent.js.map +1 -0
  32. package/dist/agents/workflow-designer.agent.d.ts +31 -0
  33. package/dist/agents/workflow-designer.agent.d.ts.map +1 -0
  34. package/dist/agents/workflow-designer.agent.js +583 -0
  35. package/dist/agents/workflow-designer.agent.js.map +1 -0
  36. package/dist/api/error-handling.d.ts +214 -0
  37. package/dist/api/error-handling.d.ts.map +1 -0
  38. package/dist/api/error-handling.js +594 -0
  39. package/dist/api/error-handling.js.map +1 -0
  40. package/dist/api/flow-designer-api.d.ts +167 -0
  41. package/dist/api/flow-designer-api.d.ts.map +1 -0
  42. package/dist/api/flow-designer-api.js +555 -0
  43. package/dist/api/flow-designer-api.js.map +1 -0
  44. package/dist/api/natural-language-mapper.d.ts +126 -0
  45. package/dist/api/natural-language-mapper.d.ts.map +1 -0
  46. package/dist/api/natural-language-mapper.js +498 -0
  47. package/dist/api/natural-language-mapper.js.map +1 -0
  48. package/dist/api/performance-optimizer.d.ts +240 -0
  49. package/dist/api/performance-optimizer.d.ts.map +1 -0
  50. package/dist/api/performance-optimizer.js +701 -0
  51. package/dist/api/performance-optimizer.js.map +1 -0
  52. package/dist/api/transaction-manager.d.ts +189 -0
  53. package/dist/api/transaction-manager.d.ts.map +1 -0
  54. package/dist/api/transaction-manager.js +576 -0
  55. package/dist/api/transaction-manager.js.map +1 -0
  56. package/dist/cli/deploy-artifact.d.ts +7 -0
  57. package/dist/cli/deploy-artifact.d.ts.map +1 -0
  58. package/dist/cli/deploy-artifact.js +279 -0
  59. package/dist/cli/deploy-artifact.js.map +1 -0
  60. package/dist/cli.d.ts +6 -0
  61. package/dist/cli.d.ts.map +1 -0
  62. package/dist/cli.js +2057 -0
  63. package/dist/cli.js.map +1 -0
  64. package/dist/index.d.ts +10 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +35 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/managers/scope-manager.d.ts +75 -0
  69. package/dist/managers/scope-manager.d.ts.map +1 -0
  70. package/dist/managers/scope-manager.js +448 -0
  71. package/dist/managers/scope-manager.js.map +1 -0
  72. package/dist/mcp/mcp-wrapper.d.ts +8 -0
  73. package/dist/mcp/mcp-wrapper.d.ts.map +1 -0
  74. package/dist/mcp/mcp-wrapper.js +77 -0
  75. package/dist/mcp/mcp-wrapper.js.map +1 -0
  76. package/dist/mcp/servicenow-automation-mcp.d.ts +8 -0
  77. package/dist/mcp/servicenow-automation-mcp.d.ts.map +1 -0
  78. package/dist/mcp/servicenow-automation-mcp.js +683 -0
  79. package/dist/mcp/servicenow-automation-mcp.js.map +1 -0
  80. package/dist/mcp/servicenow-deployment-mcp.d.ts +7 -0
  81. package/dist/mcp/servicenow-deployment-mcp.d.ts.map +1 -0
  82. package/dist/mcp/servicenow-deployment-mcp.js +972 -0
  83. package/dist/mcp/servicenow-deployment-mcp.js.map +1 -0
  84. package/dist/mcp/servicenow-flow-composer-mcp.d.ts +7 -0
  85. package/dist/mcp/servicenow-flow-composer-mcp.d.ts.map +1 -0
  86. package/dist/mcp/servicenow-flow-composer-mcp.js +1121 -0
  87. package/dist/mcp/servicenow-flow-composer-mcp.js.map +1 -0
  88. package/dist/mcp/servicenow-graph-memory-mcp.d.ts +7 -0
  89. package/dist/mcp/servicenow-graph-memory-mcp.d.ts.map +1 -0
  90. package/dist/mcp/servicenow-graph-memory-mcp.js +703 -0
  91. package/dist/mcp/servicenow-graph-memory-mcp.js.map +1 -0
  92. package/dist/mcp/servicenow-integration-mcp.d.ts +8 -0
  93. package/dist/mcp/servicenow-integration-mcp.d.ts.map +1 -0
  94. package/dist/mcp/servicenow-integration-mcp.js +689 -0
  95. package/dist/mcp/servicenow-integration-mcp.js.map +1 -0
  96. package/dist/mcp/servicenow-intelligent-mcp.d.ts +7 -0
  97. package/dist/mcp/servicenow-intelligent-mcp.d.ts.map +1 -0
  98. package/dist/mcp/servicenow-intelligent-mcp.js +1138 -0
  99. package/dist/mcp/servicenow-intelligent-mcp.js.map +1 -0
  100. package/dist/mcp/servicenow-mcp-server.d.ts +37 -0
  101. package/dist/mcp/servicenow-mcp-server.d.ts.map +1 -0
  102. package/dist/mcp/servicenow-mcp-server.js +648 -0
  103. package/dist/mcp/servicenow-mcp-server.js.map +1 -0
  104. package/dist/mcp/servicenow-operations-mcp.d.ts +15 -0
  105. package/dist/mcp/servicenow-operations-mcp.d.ts.map +1 -0
  106. package/dist/mcp/servicenow-operations-mcp.js +1287 -0
  107. package/dist/mcp/servicenow-operations-mcp.js.map +1 -0
  108. package/dist/mcp/servicenow-platform-development-mcp.d.ts +8 -0
  109. package/dist/mcp/servicenow-platform-development-mcp.d.ts.map +1 -0
  110. package/dist/mcp/servicenow-platform-development-mcp.js +557 -0
  111. package/dist/mcp/servicenow-platform-development-mcp.js.map +1 -0
  112. package/dist/mcp/servicenow-progressive-indexer.d.ts +79 -0
  113. package/dist/mcp/servicenow-progressive-indexer.d.ts.map +1 -0
  114. package/dist/mcp/servicenow-progressive-indexer.js +320 -0
  115. package/dist/mcp/servicenow-progressive-indexer.js.map +1 -0
  116. package/dist/mcp/servicenow-reporting-analytics-mcp.d.ts +8 -0
  117. package/dist/mcp/servicenow-reporting-analytics-mcp.d.ts.map +1 -0
  118. package/dist/mcp/servicenow-reporting-analytics-mcp.js +888 -0
  119. package/dist/mcp/servicenow-reporting-analytics-mcp.js.map +1 -0
  120. package/dist/mcp/servicenow-security-compliance-mcp.d.ts +8 -0
  121. package/dist/mcp/servicenow-security-compliance-mcp.d.ts.map +1 -0
  122. package/dist/mcp/servicenow-security-compliance-mcp.js +812 -0
  123. package/dist/mcp/servicenow-security-compliance-mcp.js.map +1 -0
  124. package/dist/mcp/servicenow-update-set-mcp.d.ts +7 -0
  125. package/dist/mcp/servicenow-update-set-mcp.d.ts.map +1 -0
  126. package/dist/mcp/servicenow-update-set-mcp.js +599 -0
  127. package/dist/mcp/servicenow-update-set-mcp.js.map +1 -0
  128. package/dist/mcp/start-all-mcp-servers.d.ts +6 -0
  129. package/dist/mcp/start-all-mcp-servers.d.ts.map +1 -0
  130. package/dist/mcp/start-all-mcp-servers.js +65 -0
  131. package/dist/mcp/start-all-mcp-servers.js.map +1 -0
  132. package/dist/mcp/start-servicenow-mcp.d.ts +7 -0
  133. package/dist/mcp/start-servicenow-mcp.d.ts.map +1 -0
  134. package/dist/mcp/start-servicenow-mcp.js +64 -0
  135. package/dist/mcp/start-servicenow-mcp.js.map +1 -0
  136. package/dist/mcp/test-simple-mcp.d.ts +6 -0
  137. package/dist/mcp/test-simple-mcp.d.ts.map +1 -0
  138. package/dist/mcp/test-simple-mcp.js +64 -0
  139. package/dist/mcp/test-simple-mcp.js.map +1 -0
  140. package/dist/orchestrator/flow-composer.d.ts +269 -0
  141. package/dist/orchestrator/flow-composer.d.ts.map +1 -0
  142. package/dist/orchestrator/flow-composer.js +2221 -0
  143. package/dist/orchestrator/flow-composer.js.map +1 -0
  144. package/dist/orchestrator/flow-pattern-templates.d.ts +260 -0
  145. package/dist/orchestrator/flow-pattern-templates.d.ts.map +1 -0
  146. package/dist/orchestrator/flow-pattern-templates.js +906 -0
  147. package/dist/orchestrator/flow-pattern-templates.js.map +1 -0
  148. package/dist/orchestrator/flow-subflow-decision-engine.d.ts +202 -0
  149. package/dist/orchestrator/flow-subflow-decision-engine.d.ts.map +1 -0
  150. package/dist/orchestrator/flow-subflow-decision-engine.js +769 -0
  151. package/dist/orchestrator/flow-subflow-decision-engine.js.map +1 -0
  152. package/dist/orchestrator/flow-validation-engine.d.ts +145 -0
  153. package/dist/orchestrator/flow-validation-engine.d.ts.map +1 -0
  154. package/dist/orchestrator/flow-validation-engine.js +663 -0
  155. package/dist/orchestrator/flow-validation-engine.js.map +1 -0
  156. package/dist/orchestrator/snow-orchestrator.d.ts +49 -0
  157. package/dist/orchestrator/snow-orchestrator.d.ts.map +1 -0
  158. package/dist/orchestrator/snow-orchestrator.js +235 -0
  159. package/dist/orchestrator/snow-orchestrator.js.map +1 -0
  160. package/dist/orchestrator/subflow-creation-handler.d.ts +230 -0
  161. package/dist/orchestrator/subflow-creation-handler.d.ts.map +1 -0
  162. package/dist/orchestrator/subflow-creation-handler.js +791 -0
  163. package/dist/orchestrator/subflow-creation-handler.js.map +1 -0
  164. package/dist/strategies/global-scope-strategy.d.ts +123 -0
  165. package/dist/strategies/global-scope-strategy.d.ts.map +1 -0
  166. package/dist/strategies/global-scope-strategy.js +585 -0
  167. package/dist/strategies/global-scope-strategy.js.map +1 -0
  168. package/dist/types/index.d.ts +138 -0
  169. package/dist/types/index.d.ts.map +1 -0
  170. package/dist/types/index.js +4 -0
  171. package/dist/types/index.js.map +1 -0
  172. package/dist/types/servicenow.types.d.ts +260 -0
  173. package/dist/types/servicenow.types.d.ts.map +1 -0
  174. package/dist/types/servicenow.types.js +3 -0
  175. package/dist/types/servicenow.types.js.map +1 -0
  176. package/dist/types/snow-flow.types.d.ts +114 -0
  177. package/dist/types/snow-flow.types.d.ts.map +1 -0
  178. package/dist/types/snow-flow.types.js +3 -0
  179. package/dist/types/snow-flow.types.js.map +1 -0
  180. package/dist/utils/action-type-cache.d.ts +66 -0
  181. package/dist/utils/action-type-cache.d.ts.map +1 -0
  182. package/dist/utils/action-type-cache.js +237 -0
  183. package/dist/utils/action-type-cache.js.map +1 -0
  184. package/dist/utils/agent-detector.d.ts +35 -0
  185. package/dist/utils/agent-detector.d.ts.map +1 -0
  186. package/dist/utils/agent-detector.js +353 -0
  187. package/dist/utils/agent-detector.js.map +1 -0
  188. package/dist/utils/flow-api-discovery.d.ts +151 -0
  189. package/dist/utils/flow-api-discovery.d.ts.map +1 -0
  190. package/dist/utils/flow-api-discovery.js +440 -0
  191. package/dist/utils/flow-api-discovery.js.map +1 -0
  192. package/dist/utils/flow-xml-generator.d.ts +41 -0
  193. package/dist/utils/flow-xml-generator.d.ts.map +1 -0
  194. package/dist/utils/flow-xml-generator.js +258 -0
  195. package/dist/utils/flow-xml-generator.js.map +1 -0
  196. package/dist/utils/logger.d.ts +13 -0
  197. package/dist/utils/logger.d.ts.map +1 -0
  198. package/dist/utils/logger.js +51 -0
  199. package/dist/utils/logger.js.map +1 -0
  200. package/dist/utils/mcp-auth-middleware.d.ts +58 -0
  201. package/dist/utils/mcp-auth-middleware.d.ts.map +1 -0
  202. package/dist/utils/mcp-auth-middleware.js +227 -0
  203. package/dist/utils/mcp-auth-middleware.js.map +1 -0
  204. package/dist/utils/mcp-config-manager.d.ts +126 -0
  205. package/dist/utils/mcp-config-manager.d.ts.map +1 -0
  206. package/dist/utils/mcp-config-manager.js +209 -0
  207. package/dist/utils/mcp-config-manager.js.map +1 -0
  208. package/dist/utils/mcp-server-manager.d.ts +91 -0
  209. package/dist/utils/mcp-server-manager.d.ts.map +1 -0
  210. package/dist/utils/mcp-server-manager.js +338 -0
  211. package/dist/utils/mcp-server-manager.js.map +1 -0
  212. package/dist/utils/scope-utils.d.ts +72 -0
  213. package/dist/utils/scope-utils.d.ts.map +1 -0
  214. package/dist/utils/scope-utils.js +386 -0
  215. package/dist/utils/scope-utils.js.map +1 -0
  216. package/dist/utils/servicenow-client.d.ts +233 -0
  217. package/dist/utils/servicenow-client.d.ts.map +1 -0
  218. package/dist/utils/servicenow-client.js +1465 -0
  219. package/dist/utils/servicenow-client.js.map +1 -0
  220. package/dist/utils/snow-oauth-old.d.ts +65 -0
  221. package/dist/utils/snow-oauth-old.d.ts.map +1 -0
  222. package/dist/utils/snow-oauth-old.js +345 -0
  223. package/dist/utils/snow-oauth-old.js.map +1 -0
  224. package/dist/utils/snow-oauth.d.ts +85 -0
  225. package/dist/utils/snow-oauth.d.ts.map +1 -0
  226. package/dist/utils/snow-oauth.js +512 -0
  227. package/dist/utils/snow-oauth.js.map +1 -0
  228. package/dist/utils/template-engine.d.ts +76 -0
  229. package/dist/utils/template-engine.d.ts.map +1 -0
  230. package/dist/utils/template-engine.js +391 -0
  231. package/dist/utils/template-engine.js.map +1 -0
  232. package/dist/version.d.ts +35 -0
  233. package/dist/version.d.ts.map +1 -0
  234. package/dist/version.js +72 -0
  235. package/dist/version.js.map +1 -0
  236. package/mcp-wrapper.sh +12 -0
  237. package/package.json +77 -0
  238. package/reports/swarm-auto-centralized-1752649029776.json +13 -0
  239. package/scripts/postinstall.js +30 -0
  240. package/scripts/setup-mcp.js +89 -0
@@ -0,0 +1,772 @@
1
+ "use strict";
2
+ /**
3
+ * Script Generator Agent for Business Rules and Script Includes
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ScriptGeneratorAgent = void 0;
7
+ const base_agent_js_1 = require("../core/base-agent.js");
8
+ class ScriptGeneratorAgent extends base_agent_js_1.BaseServiceNowAgent {
9
+ constructor(config) {
10
+ super('script-generator', servicenow_types_js_1.AgentType.SCRIPT_GENERATOR, [
11
+ 'generate_business_rule',
12
+ 'generate_script_include',
13
+ 'generate_client_script',
14
+ 'generate_ui_script',
15
+ 'optimize_script',
16
+ 'convert_script_type',
17
+ 'generate_test_script'
18
+ ], config);
19
+ }
20
+ async execute(task) {
21
+ this.logger.info(`Executing script generation task: ${task.description}`);
22
+ try {
23
+ switch (task.type) {
24
+ case 'generate_business_rule':
25
+ return await this.generateBusinessRule(task);
26
+ case 'generate_script_include':
27
+ return await this.generateScriptInclude(task);
28
+ case 'generate_client_script':
29
+ return await this.generateClientScript(task);
30
+ case 'generate_from_requirements':
31
+ return await this.generateFromRequirements(task);
32
+ case 'optimize_script':
33
+ return await this.optimizeScript(task);
34
+ default:
35
+ throw new Error(`Unknown task type: ${task.type}`);
36
+ }
37
+ }
38
+ catch (error) {
39
+ this.logger.error(`Script generation failed: ${error.message}`);
40
+ return {
41
+ taskId: task.id,
42
+ success: false,
43
+ error: error.message
44
+ };
45
+ }
46
+ }
47
+ async generateBusinessRule(task) {
48
+ const { name, table, when, conditions, logic, order } = task.payload;
49
+ const script = {
50
+ name,
51
+ type: 'business_rule',
52
+ table,
53
+ when: when || 'before',
54
+ conditions: conditions || '',
55
+ script: this.generateBusinessRuleScript(logic, when),
56
+ active: true
57
+ };
58
+ const metadata = {
59
+ order: order || 100,
60
+ advanced: true,
61
+ role_conditions: '',
62
+ filter_conditions: conditions
63
+ };
64
+ // Generate orchestration commands
65
+ const commands = [
66
+ this.generateCommand('Bash', 'create', {
67
+ command: `mkdir -p /Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/business_rules`,
68
+ description: 'Create business rules directory'
69
+ }, 'Create directory'),
70
+ this.generateCommand('Write', 'create', {
71
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/business_rules/${this.sanitizeName(name)}.js`,
72
+ content: script.script
73
+ }, `Create business rule script: ${name}`),
74
+ this.generateCommand('Write', 'create', {
75
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/business_rules/${this.sanitizeName(name)}.json`,
76
+ content: JSON.stringify({
77
+ ...script,
78
+ metadata
79
+ }, null, 2)
80
+ }, 'Create business rule metadata')
81
+ ];
82
+ // Store in memory for coordination
83
+ await this.storeInMemory(`scripts:business_rule:${this.sanitizeName(name)}`, script);
84
+ return {
85
+ taskId: task.id,
86
+ success: true,
87
+ output: script,
88
+ artifacts: [
89
+ this.createArtifact('business_rule', name, script, metadata)
90
+ ],
91
+ commands
92
+ };
93
+ }
94
+ async generateScriptInclude(task) {
95
+ const { name, apiName, description, methods, type } = task.payload;
96
+ const scriptInclude = {
97
+ name: name || apiName,
98
+ api_name: apiName || this.generateAPIName(name),
99
+ description: description || `Script Include: ${name}`,
100
+ script: this.generateScriptIncludeCode(apiName || name, methods, type),
101
+ active: true,
102
+ access: type === 'public' ? 'public' : 'package_private'
103
+ };
104
+ // Generate test script
105
+ const testScript = this.generateTestScript(scriptInclude.api_name, methods);
106
+ const commands = [
107
+ this.generateCommand('Bash', 'create', {
108
+ command: `mkdir -p /Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/script_includes/{src,test}`,
109
+ description: 'Create script include directories'
110
+ }, 'Create directories'),
111
+ this.generateCommand('Write', 'create', {
112
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/script_includes/src/${scriptInclude.api_name}.js`,
113
+ content: scriptInclude.script
114
+ }, `Create script include: ${scriptInclude.api_name}`),
115
+ this.generateCommand('Write', 'create', {
116
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/script_includes/test/${scriptInclude.api_name}.test.js`,
117
+ content: testScript
118
+ }, 'Create test script'),
119
+ this.generateCommand('Write', 'create', {
120
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/script_includes/${scriptInclude.api_name}.json`,
121
+ content: JSON.stringify(scriptInclude, null, 2)
122
+ }, 'Create script include metadata')
123
+ ];
124
+ await this.storeInMemory(`scripts:script_include:${scriptInclude.api_name}`, scriptInclude);
125
+ return {
126
+ taskId: task.id,
127
+ success: true,
128
+ output: {
129
+ scriptInclude,
130
+ testScript
131
+ },
132
+ artifacts: [
133
+ this.createArtifact('script_include', scriptInclude.api_name, scriptInclude),
134
+ this.createArtifact('test_script', `${scriptInclude.api_name}.test`, testScript)
135
+ ],
136
+ commands
137
+ };
138
+ }
139
+ async generateClientScript(task) {
140
+ const { name, table, type, fieldName, script: customScript } = task.payload;
141
+ const clientScript = {
142
+ name,
143
+ type: 'client_script',
144
+ table,
145
+ when: type || 'onLoad',
146
+ script: customScript || this.generateClientScriptCode(type || 'onLoad', fieldName),
147
+ active: true
148
+ };
149
+ const metadata = {
150
+ ui_type: 'Desktop',
151
+ isolate_script: true,
152
+ field: fieldName || ''
153
+ };
154
+ const commands = [
155
+ this.generateCommand('Bash', 'create', {
156
+ command: `mkdir -p /Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/client_scripts`,
157
+ description: 'Create client scripts directory'
158
+ }, 'Create directory'),
159
+ this.generateCommand('Write', 'create', {
160
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/client_scripts/${this.sanitizeName(name)}.js`,
161
+ content: clientScript.script
162
+ }, `Create client script: ${name}`),
163
+ this.generateCommand('Write', 'create', {
164
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/client_scripts/${this.sanitizeName(name)}.json`,
165
+ content: JSON.stringify({
166
+ ...clientScript,
167
+ metadata
168
+ }, null, 2)
169
+ }, 'Create client script metadata')
170
+ ];
171
+ await this.storeInMemory(`scripts:client_script:${this.sanitizeName(name)}`, clientScript);
172
+ return {
173
+ taskId: task.id,
174
+ success: true,
175
+ output: clientScript,
176
+ artifacts: [
177
+ this.createArtifact('client_script', name, clientScript, metadata)
178
+ ],
179
+ commands
180
+ };
181
+ }
182
+ async generateFromRequirements(task) {
183
+ const { requirements, scriptType, table } = task.payload;
184
+ // Analyze requirements to determine script structure
185
+ const analysis = this.analyzeScriptRequirements(requirements, scriptType);
186
+ // Generate appropriate script based on analysis
187
+ let generatedScript;
188
+ let scriptCategory;
189
+ switch (analysis.recommendedType) {
190
+ case 'business_rule':
191
+ generatedScript = {
192
+ name: analysis.suggestedName,
193
+ type: 'business_rule',
194
+ table: table || analysis.detectedTable,
195
+ when: analysis.when || 'before',
196
+ conditions: analysis.conditions,
197
+ script: this.generateSmartBusinessRule(analysis),
198
+ active: true
199
+ };
200
+ scriptCategory = 'business_rule';
201
+ break;
202
+ case 'script_include':
203
+ generatedScript = {
204
+ name: analysis.suggestedName,
205
+ api_name: this.generateAPIName(analysis.suggestedName),
206
+ script: this.generateSmartScriptInclude(analysis),
207
+ active: true,
208
+ access: 'package_private'
209
+ };
210
+ scriptCategory = 'script_include';
211
+ break;
212
+ case 'client_script':
213
+ generatedScript = {
214
+ name: analysis.suggestedName,
215
+ type: 'client_script',
216
+ table: table || analysis.detectedTable,
217
+ when: analysis.clientType || 'onChange',
218
+ script: this.generateSmartClientScript(analysis),
219
+ active: true
220
+ };
221
+ scriptCategory = 'client_script';
222
+ break;
223
+ default:
224
+ throw new Error(`Unable to determine script type from requirements`);
225
+ }
226
+ // Generate comprehensive documentation
227
+ const documentation = this.generateScriptDocumentation(generatedScript, analysis, requirements);
228
+ const commands = [
229
+ this.generateCommand('Bash', 'create', {
230
+ command: `mkdir -p /Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/${scriptCategory}s`,
231
+ description: `Create ${scriptCategory} directory`
232
+ }, 'Create directory'),
233
+ this.generateCommand('Write', 'create', {
234
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/${scriptCategory}s/${this.sanitizeName(generatedScript.name)}.js`,
235
+ content: generatedScript.script
236
+ }, `Create ${scriptCategory}: ${generatedScript.name}`),
237
+ this.generateCommand('Write', 'create', {
238
+ file_path: `/Users/nielsvanderwerf/Projects/servicenow_multiagent/output/scripts/${scriptCategory}s/${this.sanitizeName(generatedScript.name)}.md`,
239
+ content: documentation
240
+ }, 'Create documentation')
241
+ ];
242
+ return {
243
+ taskId: task.id,
244
+ success: true,
245
+ output: {
246
+ script: generatedScript,
247
+ analysis,
248
+ documentation
249
+ },
250
+ artifacts: [
251
+ this.createArtifact(scriptCategory, generatedScript.name, generatedScript),
252
+ this.createArtifact('documentation', `${generatedScript.name}.md`, documentation)
253
+ ],
254
+ commands
255
+ };
256
+ }
257
+ async optimizeScript(task) {
258
+ const { script, scriptType, optimizationGoals } = task.payload;
259
+ // Perform script analysis
260
+ const analysis = this.analyzeScriptPerformance(script);
261
+ // Apply optimizations
262
+ const optimizedScript = this.applyScriptOptimizations(script, analysis, optimizationGoals);
263
+ // Generate optimization report
264
+ const report = {
265
+ originalLength: script.length,
266
+ optimizedLength: optimizedScript.length,
267
+ improvements: analysis.improvements,
268
+ appliedOptimizations: analysis.optimizations,
269
+ performanceGains: analysis.estimatedGains
270
+ };
271
+ return {
272
+ taskId: task.id,
273
+ success: true,
274
+ output: {
275
+ originalScript: script,
276
+ optimizedScript,
277
+ report
278
+ },
279
+ artifacts: [
280
+ this.createArtifact('optimized_script', 'optimized.js', optimizedScript),
281
+ this.createArtifact('optimization_report', 'optimization-report.json', report)
282
+ ]
283
+ };
284
+ }
285
+ // Helper methods
286
+ generateBusinessRuleScript(logic, when) {
287
+ const template = `(function executeRule(current, previous /*null when async*/) {
288
+ // Business Rule: ${logic.description || 'Custom Business Logic'}
289
+
290
+ try {
291
+ ${this.generateBusinessLogic(logic, when)}
292
+ } catch (e) {
293
+ gs.error('Business rule error: ' + e.message, 'BusinessRule');
294
+ }
295
+
296
+ })(current, previous);`;
297
+ return template;
298
+ }
299
+ generateBusinessLogic(logic, when) {
300
+ let code = '';
301
+ // Add common patterns based on logic type
302
+ if (logic.type === 'validation') {
303
+ code = `// Validation logic
304
+ if (!current.${logic.field}) {
305
+ current.setAbortAction(true);
306
+ gs.addErrorMessage('${logic.errorMessage || 'Validation failed'}');
307
+ return;
308
+ }`;
309
+ }
310
+ else if (logic.type === 'calculation') {
311
+ code = `// Calculation logic
312
+ var result = ${logic.calculation || '0'};
313
+ current.${logic.targetField} = result;`;
314
+ }
315
+ else if (logic.type === 'notification') {
316
+ code = `// Notification logic
317
+ if (${logic.condition || 'true'}) {
318
+ gs.eventQueue('${logic.eventName || 'custom.notification'}', current, '${logic.param1 || ''}', '${logic.param2 || ''}');
319
+ }`;
320
+ }
321
+ else if (logic.type === 'integration') {
322
+ code = `// Integration logic
323
+ var request = new sn_ws.RESTMessageV2('${logic.integrationName || 'Custom_Integration'}', '${logic.method || 'get'}');
324
+ request.setStringParameter('id', current.sys_id);
325
+ var response = request.execute();
326
+ current.${logic.responseField || 'integration_response'} = response.getBody();`;
327
+ }
328
+ else {
329
+ // Custom logic
330
+ code = logic.customCode || '// Add custom business logic here';
331
+ }
332
+ return code;
333
+ }
334
+ generateScriptIncludeCode(className, methods, type) {
335
+ const isPrototype = type !== 'static';
336
+ const baseClass = type === 'ajax' ? 'AbstractAjaxProcessor' : '';
337
+ let code = `var ${className} = Class.create();`;
338
+ if (isPrototype) {
339
+ code = `${code}
340
+ ${className}.prototype = ${baseClass ? `Object.extendsObject(${baseClass}, ` : ''}{
341
+ initialize: function() {
342
+ ${baseClass ? 'this.logPrefix = "[' + className + '] ";' : '// Initialize instance variables'}
343
+ },
344
+
345
+ ${this.generateMethods(methods || [], className)}
346
+
347
+ type: '${className}'
348
+ }${baseClass ? ')' : ''};`;
349
+ }
350
+ else {
351
+ // Static script include
352
+ code = `var ${className} = {
353
+ ${this.generateStaticMethods(methods || [], className)}
354
+ };`;
355
+ }
356
+ return code;
357
+ }
358
+ generateMethods(methods, className) {
359
+ if (methods.length === 0) {
360
+ return `// Example method
361
+ exampleMethod: function(param) {
362
+ // Add method implementation
363
+ return 'Result';
364
+ }`;
365
+ }
366
+ return methods.map(method => {
367
+ return `${method.name}: function(${method.parameters?.join(', ') || ''}) {
368
+ ${method.description ? '// ' + method.description : ''}
369
+ ${method.body || '// Add implementation'}
370
+ }`;
371
+ }).join(',\n \n ');
372
+ }
373
+ generateStaticMethods(methods, className) {
374
+ if (methods.length === 0) {
375
+ return `// Example static method
376
+ exampleMethod: function(param) {
377
+ // Add method implementation
378
+ return 'Result';
379
+ }`;
380
+ }
381
+ return methods.map(method => {
382
+ return `${method.name}: function(${method.parameters?.join(', ') || ''}) {
383
+ ${method.description ? '// ' + method.description : ''}
384
+ ${method.body || '// Add implementation'}
385
+ }`;
386
+ }).join(',\n \n ');
387
+ }
388
+ generateClientScriptCode(type, fieldName) {
389
+ switch (type) {
390
+ case 'onLoad':
391
+ return `function onLoad() {
392
+ // Client script executed when form loads
393
+
394
+ // Hide/show fields based on conditions
395
+ g_form.setDisplay('field_name', false);
396
+
397
+ // Set default values
398
+ if (g_form.isNewRecord()) {
399
+ g_form.setValue('priority', '3');
400
+ }
401
+
402
+ // Add field messages
403
+ g_form.showFieldMsg('short_description', 'Please provide a detailed description', 'info');
404
+ }`;
405
+ case 'onChange':
406
+ return `function onChange(control, oldValue, newValue, isLoading, isTemplate) {
407
+ if (isLoading || newValue === '') {
408
+ return;
409
+ }
410
+
411
+ // Field: ${fieldName || 'field_name'}
412
+ // React to field changes
413
+
414
+ if (newValue != oldValue) {
415
+ // Perform client-side validation
416
+ if (!isValidValue(newValue)) {
417
+ g_form.setValue('${fieldName || 'field_name'}', oldValue);
418
+ alert('Invalid value entered');
419
+ return;
420
+ }
421
+
422
+ // Update related fields
423
+ updateRelatedFields(newValue);
424
+ }
425
+ }
426
+
427
+ function isValidValue(value) {
428
+ // Add validation logic
429
+ return true;
430
+ }
431
+
432
+ function updateRelatedFields(value) {
433
+ // Update other fields based on the new value
434
+ }`;
435
+ case 'onSubmit':
436
+ return `function onSubmit() {
437
+ // Validate form before submission
438
+
439
+ var isValid = true;
440
+ var errorMessage = [];
441
+
442
+ // Check required fields
443
+ if (g_form.getValue('short_description') == '') {
444
+ errorMessage.push('Short description is required');
445
+ isValid = false;
446
+ }
447
+
448
+ // Validate field formats
449
+ var email = g_form.getValue('email');
450
+ if (email && !isValidEmail(email)) {
451
+ errorMessage.push('Invalid email format');
452
+ isValid = false;
453
+ }
454
+
455
+ if (!isValid) {
456
+ g_form.addErrorMessage(errorMessage.join('\\n'));
457
+ return false;
458
+ }
459
+
460
+ return true;
461
+ }
462
+
463
+ function isValidEmail(email) {
464
+ var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
465
+ return re.test(email);
466
+ }`;
467
+ case 'onCellEdit':
468
+ return `function onCellEdit(sysIDs, table, oldValues, newValue, callback) {
469
+ // Handle list cell edits
470
+
471
+ // Validate the new value
472
+ if (!isValidCellValue(newValue)) {
473
+ alert('Invalid value');
474
+ callback(false);
475
+ return;
476
+ }
477
+
478
+ // Perform additional checks or updates
479
+ var ajax = new GlideAjax('CustomAjaxProcessor');
480
+ ajax.addParam('sysparm_name', 'validateBulkUpdate');
481
+ ajax.addParam('sysparm_ids', sysIDs.join(','));
482
+ ajax.addParam('sysparm_value', newValue);
483
+
484
+ ajax.getXMLAnswer(function(answer) {
485
+ if (answer === 'true') {
486
+ callback(true);
487
+ } else {
488
+ alert('Update not allowed');
489
+ callback(false);
490
+ }
491
+ });
492
+ }
493
+
494
+ function isValidCellValue(value) {
495
+ // Add validation logic
496
+ return true;
497
+ }`;
498
+ default:
499
+ return '// Custom client script\n// Add your implementation here';
500
+ }
501
+ }
502
+ generateTestScript(apiName, methods) {
503
+ return `// Test script for ${apiName}
504
+ // Run this in Scripts - Background to test the Script Include
505
+
506
+ gs.info('=== Testing ${apiName} ===');
507
+
508
+ try {
509
+ // Test instantiation
510
+ var instance = new ${apiName}();
511
+ gs.info('✓ Script Include instantiated successfully');
512
+
513
+ ${methods?.map(method => `
514
+ // Test ${method.name}
515
+ try {
516
+ var result = instance.${method.name}(${method.testParams?.join(', ') || ''});
517
+ gs.info('✓ ${method.name} executed successfully');
518
+ gs.info(' Result: ' + JSON.stringify(result));
519
+ } catch (e) {
520
+ gs.error('✗ ${method.name} failed: ' + e.message);
521
+ }`).join('\n') || '// Add test cases for your methods'}
522
+
523
+ gs.info('=== Test completed ===');
524
+ } catch (e) {
525
+ gs.error('Test failed: ' + e.message);
526
+ }`;
527
+ }
528
+ generateAPIName(name) {
529
+ // Convert name to proper API name format
530
+ return name
531
+ .split(/[\s-_]+/)
532
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
533
+ .join('');
534
+ }
535
+ analyzeScriptRequirements(requirements, preferredType) {
536
+ const analysis = {
537
+ recommendedType: preferredType,
538
+ suggestedName: '',
539
+ detectedTable: '',
540
+ when: '',
541
+ conditions: '',
542
+ clientType: '',
543
+ methods: [],
544
+ features: []
545
+ };
546
+ // Detect script type from requirements
547
+ const reqLower = requirements.toLowerCase();
548
+ if (!preferredType) {
549
+ if (reqLower.includes('when record') || reqLower.includes('before insert') ||
550
+ reqLower.includes('after update') || reqLower.includes('on insert')) {
551
+ analysis.recommendedType = 'business_rule';
552
+ }
553
+ else if (reqLower.includes('reusable') || reqLower.includes('utility') ||
554
+ reqLower.includes('ajax') || reqLower.includes('api')) {
555
+ analysis.recommendedType = 'script_include';
556
+ }
557
+ else if (reqLower.includes('form') || reqLower.includes('client') ||
558
+ reqLower.includes('ui') || reqLower.includes('user interface')) {
559
+ analysis.recommendedType = 'client_script';
560
+ }
561
+ }
562
+ // Extract table name
563
+ const tables = ['incident', 'change_request', 'problem', 'task', 'user', 'group'];
564
+ for (const table of tables) {
565
+ if (reqLower.includes(table)) {
566
+ analysis.detectedTable = table;
567
+ break;
568
+ }
569
+ }
570
+ // Detect timing for business rules
571
+ if (reqLower.includes('before'))
572
+ analysis.when = 'before';
573
+ else if (reqLower.includes('after'))
574
+ analysis.when = 'after';
575
+ else if (reqLower.includes('async'))
576
+ analysis.when = 'async';
577
+ // Detect client script type
578
+ if (reqLower.includes('load'))
579
+ analysis.clientType = 'onLoad';
580
+ else if (reqLower.includes('change'))
581
+ analysis.clientType = 'onChange';
582
+ else if (reqLower.includes('submit'))
583
+ analysis.clientType = 'onSubmit';
584
+ // Extract features
585
+ if (reqLower.includes('validate'))
586
+ analysis.features.push('validation');
587
+ if (reqLower.includes('calculate'))
588
+ analysis.features.push('calculation');
589
+ if (reqLower.includes('email') || reqLower.includes('notify'))
590
+ analysis.features.push('notification');
591
+ if (reqLower.includes('integrate') || reqLower.includes('api'))
592
+ analysis.features.push('integration');
593
+ // Generate suggested name
594
+ const words = requirements.split(/\s+/).slice(0, 5);
595
+ analysis.suggestedName = words.join(' ');
596
+ return analysis;
597
+ }
598
+ generateSmartBusinessRule(analysis) {
599
+ let script = '(function executeRule(current, previous /*null when async*/) {\n';
600
+ // Add features based on analysis
601
+ analysis.features.forEach((feature) => {
602
+ switch (feature) {
603
+ case 'validation':
604
+ script += `\n // Validation
605
+ if (!current.field_name) {
606
+ current.setAbortAction(true);
607
+ gs.addErrorMessage('Field is required');
608
+ return;
609
+ }\n`;
610
+ break;
611
+ case 'calculation':
612
+ script += `\n // Calculation
613
+ var calculated = calculateValue(current);
614
+ current.calculated_field = calculated;\n`;
615
+ break;
616
+ case 'notification':
617
+ script += `\n // Send notification
618
+ gs.eventQueue('custom.event', current, current.assigned_to, current.assignment_group);\n`;
619
+ break;
620
+ }
621
+ });
622
+ script += '\n})(current, previous);';
623
+ return script;
624
+ }
625
+ generateSmartScriptInclude(analysis) {
626
+ const className = this.generateAPIName(analysis.suggestedName);
627
+ let script = `var ${className} = Class.create();\n${className}.prototype = {\n`;
628
+ script += ' initialize: function() {\n },\n\n';
629
+ // Add methods based on features
630
+ analysis.features.forEach((feature) => {
631
+ switch (feature) {
632
+ case 'validation':
633
+ script += ` validate: function(record) {
634
+ // Validation logic
635
+ return true;
636
+ },\n\n`;
637
+ break;
638
+ case 'integration':
639
+ script += ` callExternalAPI: function(endpoint, payload) {
640
+ var request = new sn_ws.RESTMessageV2();
641
+ // API call implementation
642
+ return response;
643
+ },\n\n`;
644
+ break;
645
+ }
646
+ });
647
+ script += ` type: '${className}'\n};`;
648
+ return script;
649
+ }
650
+ generateSmartClientScript(analysis) {
651
+ const type = analysis.clientType || 'onChange';
652
+ switch (type) {
653
+ case 'onLoad':
654
+ return this.generateClientScriptCode('onLoad');
655
+ case 'onChange':
656
+ return this.generateClientScriptCode('onChange', 'field_name');
657
+ case 'onSubmit':
658
+ return this.generateClientScriptCode('onSubmit');
659
+ default:
660
+ return '// Custom client script';
661
+ }
662
+ }
663
+ generateScriptDocumentation(script, analysis, requirements) {
664
+ return `# ${script.name}
665
+
666
+ ## Overview
667
+ ${analysis.description || 'Script generated from requirements'}
668
+
669
+ ## Requirements
670
+ ${requirements}
671
+
672
+ ## Script Details
673
+ - **Type**: ${script.type}
674
+ - **Table**: ${script.table || 'N/A'}
675
+ - **When**: ${script.when || 'N/A'}
676
+ - **Active**: ${script.active}
677
+
678
+ ## Features
679
+ ${analysis.features.map((f) => `- ${f}`).join('\n')}
680
+
681
+ ## Implementation
682
+ \`\`\`javascript
683
+ ${script.script}
684
+ \`\`\`
685
+
686
+ ## Usage Notes
687
+ - This script was automatically generated based on the provided requirements
688
+ - Review and test thoroughly before deploying to production
689
+ - Consider adding error handling and logging as needed
690
+
691
+ ## Testing
692
+ ${script.type === 'script_include' ? 'See accompanying test script for testing procedures' : 'Test in a development instance first'}
693
+
694
+ Generated on: ${new Date().toISOString()}
695
+ Generated by: ServiceNow Multi-Agent Framework - Script Generator Agent
696
+ `;
697
+ }
698
+ analyzeScriptPerformance(script) {
699
+ const analysis = {
700
+ issues: [],
701
+ improvements: [],
702
+ optimizations: [],
703
+ estimatedGains: {}
704
+ };
705
+ // Check for common performance issues
706
+ if (script.includes('GlideRecord') && !script.includes('setLimit')) {
707
+ analysis.issues.push('Unbounded GlideRecord query detected');
708
+ analysis.improvements.push('Add setLimit() to GlideRecord queries');
709
+ }
710
+ if (script.includes('gr.next()') && script.includes('new GlideRecord')) {
711
+ const nestedQueries = (script.match(/new GlideRecord/g) || []).length;
712
+ if (nestedQueries > 1) {
713
+ analysis.issues.push('Nested GlideRecord queries detected');
714
+ analysis.improvements.push('Consider using GlideAggregate or joining queries');
715
+ }
716
+ }
717
+ if (script.includes('gs.info') || script.includes('gs.log')) {
718
+ analysis.issues.push('Excessive logging detected');
719
+ analysis.improvements.push('Remove or conditionalize debug logging');
720
+ }
721
+ // Suggest optimizations
722
+ if (script.includes('getValue()') && script.match(/getValue\(\)/g)?.length > 3) {
723
+ analysis.optimizations.push('Cache frequently accessed values');
724
+ }
725
+ return analysis;
726
+ }
727
+ applyScriptOptimizations(script, analysis, goals) {
728
+ let optimized = script;
729
+ // Apply optimizations based on goals
730
+ if (goals.includes('performance')) {
731
+ // Add setLimit to queries without it
732
+ optimized = optimized.replace(/gr\.query\(\);/g, 'gr.setLimit(1000);\n gr.query();');
733
+ // Cache getValue calls
734
+ optimized = optimized.replace(/current\.getValue\('(\w+)'\)/g, (match, field) => `cached_${field} || (cached_${field} = current.getValue('${field}'))`);
735
+ }
736
+ if (goals.includes('readability')) {
737
+ // Add proper indentation
738
+ optimized = this.formatScript(optimized);
739
+ }
740
+ if (goals.includes('maintainability')) {
741
+ // Extract magic numbers to constants
742
+ optimized = optimized.replace(/(\d{3,})/g, (match) => {
743
+ return `CONST_${match}`;
744
+ });
745
+ }
746
+ return optimized;
747
+ }
748
+ formatScript(script) {
749
+ // Simple formatting - in practice, use a proper formatter
750
+ let formatted = script;
751
+ let indent = 0;
752
+ formatted = formatted.split('\n').map(line => {
753
+ const trimmed = line.trim();
754
+ if (trimmed.endsWith('{')) {
755
+ const result = ' '.repeat(indent) + trimmed;
756
+ indent++;
757
+ return result;
758
+ }
759
+ else if (trimmed.startsWith('}')) {
760
+ indent = Math.max(0, indent - 1);
761
+ return ' '.repeat(indent) + trimmed;
762
+ }
763
+ return ' '.repeat(indent) + trimmed;
764
+ }).join('\n');
765
+ return formatted;
766
+ }
767
+ sanitizeName(name) {
768
+ return name.toLowerCase().replace(/[^a-z0-9]/g, '_');
769
+ }
770
+ }
771
+ exports.ScriptGeneratorAgent = ScriptGeneratorAgent;
772
+ //# sourceMappingURL=script-generator.agent.js.map