@flowfuse/nr-assistant 0.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.
- package/.eslintrc +32 -0
- package/.github/dependabot.yml +6 -0
- package/.github/workflows/project-automation.yml +10 -0
- package/.github/workflows/release-publish.yml +19 -0
- package/LICENSE +178 -0
- package/README.md +53 -0
- package/index.html +563 -0
- package/index.js +76 -0
- package/package.json +47 -0
package/.eslintrc
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"root": true,
|
|
3
|
+
"globals": {
|
|
4
|
+
"monaco": true,
|
|
5
|
+
"RED": true
|
|
6
|
+
},
|
|
7
|
+
"env": {
|
|
8
|
+
"browser": true,
|
|
9
|
+
"commonjs": true,
|
|
10
|
+
"es2021": true,
|
|
11
|
+
"mocha": true,
|
|
12
|
+
"jquery": true
|
|
13
|
+
},
|
|
14
|
+
"extends": [
|
|
15
|
+
"eslint:recommended",
|
|
16
|
+
"standard"
|
|
17
|
+
],
|
|
18
|
+
"plugins": [ "eslint-plugin-html", "no-only-tests" ],
|
|
19
|
+
"parserOptions": {
|
|
20
|
+
"ecmaVersion": 12
|
|
21
|
+
},
|
|
22
|
+
"rules": {
|
|
23
|
+
// Built-in rules
|
|
24
|
+
"indent": ["error", 4],
|
|
25
|
+
"object-shorthand": ["error"],
|
|
26
|
+
"no-console": ["error", { "allow": ["debug", "info", "warn", "error"] }],
|
|
27
|
+
|
|
28
|
+
// plugin:no-only-tests
|
|
29
|
+
"no-only-tests/no-only-tests": "error"
|
|
30
|
+
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: Release Published
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
tags:
|
|
5
|
+
- "v*.*.*"
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
publish:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
steps:
|
|
11
|
+
- uses: actions/checkout@v4
|
|
12
|
+
- uses: actions/setup-node@v4
|
|
13
|
+
with:
|
|
14
|
+
node-version: 16
|
|
15
|
+
- run: npm ci --omit=dev
|
|
16
|
+
- uses: JS-DevTools/npm-publish@v3
|
|
17
|
+
with:
|
|
18
|
+
token: ${{ secrets.NPM_PUBLISH_TOKEN }}
|
|
19
|
+
access: public
|
package/LICENSE
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Copyright (c) 2024-present FlowForge Inc, and other contributors, https://flowfuse.com/
|
|
2
|
+
|
|
3
|
+
Apache License
|
|
4
|
+
Version 2.0, January 2004
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
12
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
15
|
+
the copyright owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
18
|
+
other entities that control, are controlled by, or are under common
|
|
19
|
+
control with that entity. For the purposes of this definition,
|
|
20
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
21
|
+
direction or management of such entity, whether by contract or
|
|
22
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
23
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
26
|
+
exercising permissions granted by this License.
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
29
|
+
including but not limited to software source code, documentation
|
|
30
|
+
source, and configuration files.
|
|
31
|
+
|
|
32
|
+
"Object" form shall mean any form resulting from mechanical
|
|
33
|
+
transformation or translation of a Source form, including but
|
|
34
|
+
not limited to compiled object code, generated documentation,
|
|
35
|
+
and conversions to other media types.
|
|
36
|
+
|
|
37
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
38
|
+
Object form, made available under the License, as indicated by a
|
|
39
|
+
copyright notice that is included in or attached to the work
|
|
40
|
+
(an example is provided in the Appendix below).
|
|
41
|
+
|
|
42
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
43
|
+
form, that is based on (or derived from) the Work and for which the
|
|
44
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
45
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
46
|
+
of this License, Derivative Works shall not include works that remain
|
|
47
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
48
|
+
the Work and Derivative Works thereof.
|
|
49
|
+
|
|
50
|
+
"Contribution" shall mean any work of authorship, including
|
|
51
|
+
the original version of the Work and any modifications or additions
|
|
52
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
53
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
54
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
55
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
56
|
+
means any form of electronic, verbal, or written communication sent
|
|
57
|
+
to the Licensor or its representatives, including but not limited to
|
|
58
|
+
communication on electronic mailing lists, source code control systems,
|
|
59
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
60
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
61
|
+
excluding communication that is conspicuously marked or otherwise
|
|
62
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
65
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
66
|
+
subsequently incorporated within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a
|
|
85
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
86
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
87
|
+
or contributory patent infringement, then any patent licenses
|
|
88
|
+
granted to You under this License for that Work shall terminate
|
|
89
|
+
as of the date such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or
|
|
97
|
+
Derivative Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
109
|
+
distribution, then any Derivative Works that You distribute must
|
|
110
|
+
include a readable copy of the attribution notices contained
|
|
111
|
+
within such NOTICE file, excluding those notices that do not
|
|
112
|
+
pertain to any part of the Derivative Works, in at least one
|
|
113
|
+
of the following places: within a NOTICE text file distributed
|
|
114
|
+
as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or,
|
|
116
|
+
within a display generated by the Derivative Works, if and
|
|
117
|
+
wherever such third-party notices normally appear. The contents
|
|
118
|
+
of the NOTICE file are for informational purposes only and
|
|
119
|
+
do not modify the License. You may add Your own attribution
|
|
120
|
+
notices within Derivative Works that You distribute, alongside
|
|
121
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
122
|
+
that such additional attribution notices cannot be construed
|
|
123
|
+
as modifying the License.
|
|
124
|
+
|
|
125
|
+
You may add Your own copyright statement to Your modifications and
|
|
126
|
+
may provide additional or different license terms and conditions
|
|
127
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
128
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
129
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
130
|
+
the conditions stated in this License.
|
|
131
|
+
|
|
132
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
133
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
134
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
135
|
+
this License, without any additional terms or conditions.
|
|
136
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
137
|
+
the terms of any separate license agreement you may have executed
|
|
138
|
+
with Licensor regarding such Contributions.
|
|
139
|
+
|
|
140
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
141
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
142
|
+
except as required for reasonable and customary use in describing the
|
|
143
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
144
|
+
|
|
145
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
146
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
147
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
148
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
149
|
+
implied, including, without limitation, any warranties or conditions
|
|
150
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
151
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
152
|
+
appropriateness of using or redistributing the Work and assume any
|
|
153
|
+
risks associated with Your exercise of permissions under this License.
|
|
154
|
+
|
|
155
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
156
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
157
|
+
unless required by applicable law (such as deliberate and grossly
|
|
158
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
159
|
+
liable to You for damages, including any direct, indirect, special,
|
|
160
|
+
incidental, or consequential damages of any character arising as a
|
|
161
|
+
result of this License or out of the use or inability to use the
|
|
162
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
163
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
164
|
+
other commercial damages or losses), even if such Contributor
|
|
165
|
+
has been advised of the possibility of such damages.
|
|
166
|
+
|
|
167
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
168
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
169
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
170
|
+
or other liability obligations and/or rights consistent with this
|
|
171
|
+
License. However, in accepting such obligations, You may act only
|
|
172
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
173
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
174
|
+
defend, and hold each Contributor harmless for any liability
|
|
175
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
176
|
+
of your accepting any such warranty or additional liability.
|
|
177
|
+
|
|
178
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# FlowFuse Node-RED Assistant
|
|
2
|
+
|
|
3
|
+
A Node-RED plugin to assist FlowFuse users
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
## Installation
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @flowfuse/nr-assistant
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Development
|
|
13
|
+
|
|
14
|
+
Client-side portion of the plugin is in `index.js`. The server side code is in `index.js`
|
|
15
|
+
|
|
16
|
+
## About
|
|
17
|
+
|
|
18
|
+
This plugin is designed to assist users of the FlowFuse platform by providing tools to aid development of their Node-RED project.
|
|
19
|
+
|
|
20
|
+
The capabilities it adds to Node-RED can be found in Node-RED editor on the main toolbar and within the function node editor.
|
|
21
|
+
|
|
22
|
+
## NOTES:
|
|
23
|
+
* Requires the settings.js file to contain the following:
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"flowforge": {
|
|
27
|
+
"assistant": {
|
|
28
|
+
"enabled": true
|
|
29
|
+
"url": "https://", // URL of the AI service
|
|
30
|
+
"token": "", // API token for the AI service
|
|
31
|
+
"requestTimeout": 60000 // Timeout value for the AI service request
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
## Limitations
|
|
39
|
+
|
|
40
|
+
* Only function node generation is currently supported.
|
|
41
|
+
* Only a single function node can be generated at a time.
|
|
42
|
+
* The codelens feature is only supported for the on-message editor.
|
|
43
|
+
|
|
44
|
+
## Versioning
|
|
45
|
+
|
|
46
|
+
While in development, the version number of this package will remain at `0.x.y`.
|
|
47
|
+
`x` will be incremented for breaking changes, `y` for new features and patches.
|
|
48
|
+
|
|
49
|
+
Once plugin and API are stable, the version number will be updated to 1.0.0 and full SemVer rules will be applied.
|
|
50
|
+
|
|
51
|
+
## License
|
|
52
|
+
|
|
53
|
+
Apache-2.0
|
package/index.html
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
<script>
|
|
2
|
+
(function (RED, n) {
|
|
3
|
+
'use strict'
|
|
4
|
+
const AI_TIMEOUT = 90000 // default request timeout in milliseconds
|
|
5
|
+
const modulesAllowed = RED.settings.functionExternalModules !== false
|
|
6
|
+
const assistantOptions = {
|
|
7
|
+
enabled: false,
|
|
8
|
+
requestTimeout: AI_TIMEOUT
|
|
9
|
+
}
|
|
10
|
+
let assistantInitialised = false
|
|
11
|
+
debug('nr-assistant loading...')
|
|
12
|
+
RED.plugins.registerPlugin('flowfuse-nr-assistant', {
|
|
13
|
+
type: 'assistant',
|
|
14
|
+
name: 'Node-RED Assistant Plugin',
|
|
15
|
+
icon: 'font-awesome/fa-magic',
|
|
16
|
+
onadd: async function () {
|
|
17
|
+
RED.comms.subscribe('nr-assistant/#', (topic, msg) => {
|
|
18
|
+
debug('comms', topic, msg)
|
|
19
|
+
if (topic === 'nr-assistant/initialise') {
|
|
20
|
+
assistantOptions.enabled = !!msg?.enabled
|
|
21
|
+
assistantOptions.requestTimeout = msg?.requestTimeout || AI_TIMEOUT
|
|
22
|
+
initAssistant(msg)
|
|
23
|
+
}
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
function initAssistant () {
|
|
29
|
+
if (assistantInitialised) {
|
|
30
|
+
return
|
|
31
|
+
}
|
|
32
|
+
debug('nr-assistant initialising...')
|
|
33
|
+
if (!assistantOptions.enabled) {
|
|
34
|
+
console.warn('The FlowFuse Assistant is not enabled')
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!window.monaco) {
|
|
39
|
+
console.warn('Monaco editor not found. Unable to register code lens provider. Consider using the Monaco editor for a better experience.')
|
|
40
|
+
return
|
|
41
|
+
} else {
|
|
42
|
+
const commandId = 'nr-assistant-fn-inline'
|
|
43
|
+
monaco.languages.registerCodeLensProvider('javascript', {
|
|
44
|
+
provideCodeLenses: function (model, token) {
|
|
45
|
+
const thisEditor = getMonacoEditorForModel(model)
|
|
46
|
+
if (!thisEditor) {
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
const node = RED.view.selection()?.nodes?.[0]
|
|
50
|
+
|
|
51
|
+
// only support function nodes for now
|
|
52
|
+
if (!node || !node.type === 'function') {
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
// Only support the "on message" editor for now
|
|
56
|
+
// determine which editor is active and if it the "on message" editor
|
|
57
|
+
// if not, return nothing to prevent the code lens from showing
|
|
58
|
+
let isFuncTabEditor
|
|
59
|
+
let el = thisEditor.getDomNode()
|
|
60
|
+
while (el && el.tagName !== 'FORM') {
|
|
61
|
+
if (el.id === 'node-input-func-editor' || el.id === 'func-tab-body') {
|
|
62
|
+
isFuncTabEditor = true
|
|
63
|
+
break
|
|
64
|
+
}
|
|
65
|
+
el = el.parentNode
|
|
66
|
+
}
|
|
67
|
+
if (!isFuncTabEditor) {
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
lenses: [
|
|
73
|
+
{
|
|
74
|
+
range: {
|
|
75
|
+
startLineNumber: 1,
|
|
76
|
+
startColumn: 1,
|
|
77
|
+
endLineNumber: 2,
|
|
78
|
+
endColumn: 1
|
|
79
|
+
},
|
|
80
|
+
id: commandId
|
|
81
|
+
}
|
|
82
|
+
],
|
|
83
|
+
dispose: () => { }
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
resolveCodeLens: function (model, codeLens, token) {
|
|
87
|
+
if (codeLens.id !== commandId) {
|
|
88
|
+
return codeLens
|
|
89
|
+
}
|
|
90
|
+
codeLens.command = {
|
|
91
|
+
id: codeLens.id,
|
|
92
|
+
title: 'Ask the FlowFuse Assistant 🪄',
|
|
93
|
+
tooltip: 'Click to ask FlowFuse Assistant for help writing code',
|
|
94
|
+
arguments: [model, codeLens, token]
|
|
95
|
+
}
|
|
96
|
+
return codeLens
|
|
97
|
+
}
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
let previousPrompt = null
|
|
101
|
+
monaco.editor.registerCommand(commandId, function (accessor, model, codeLens, token) {
|
|
102
|
+
const node = RED.view.selection()?.nodes?.[0]
|
|
103
|
+
if (!node) {
|
|
104
|
+
console.warn('No node selected') // should not happen
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
if (!assistantOptions.enabled) {
|
|
108
|
+
RED.notify('The FlowFuse Assistant is not enabled', 'warning')
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
let xhr = null
|
|
112
|
+
const nodeId = node.id
|
|
113
|
+
const transactionId = `${nodeId}-${Date.now()}` // a unique id for this transaction
|
|
114
|
+
const thisEditor = getMonacoEditorForModel(model)
|
|
115
|
+
if (thisEditor) {
|
|
116
|
+
if (!document.body.contains(thisEditor.getDomNode())) {
|
|
117
|
+
console.warn('Editor is no longer in the DOM, cannot proceed.')
|
|
118
|
+
return
|
|
119
|
+
}
|
|
120
|
+
// walk up the tree to find the parent div with an id and include that in context
|
|
121
|
+
let parent = thisEditor.getDomNode().parentNode
|
|
122
|
+
while (parent?.tagName !== 'FORM') {
|
|
123
|
+
if (parent.id) {
|
|
124
|
+
break
|
|
125
|
+
}
|
|
126
|
+
parent = parent.parentNode
|
|
127
|
+
}
|
|
128
|
+
// const editorSection = parent?.id || '' // FUTURE: determine the code section users code lens was triggered in. Will be used to help the assistant understand the context of the code
|
|
129
|
+
const editorSection = 'on message' // hard coded for now since the code lens is only available in the "on message" editor in this first iteration
|
|
130
|
+
|
|
131
|
+
// FUTURE: for including selected text in the context for features like "fix my code", "refactor this", "what is this?" etc
|
|
132
|
+
// const userSelection = triggeredEditor.getSelection()
|
|
133
|
+
// const selectedText = model.getValueInRange(userSelection)
|
|
134
|
+
|
|
135
|
+
getUserInput({
|
|
136
|
+
defaultInput: previousPrompt,
|
|
137
|
+
title: 'FlowFuse Assistant : Function Code',
|
|
138
|
+
explanation: 'The FlowFuse Assistant can help you write code.',
|
|
139
|
+
description: 'Enter a short description of what you want the function to do.'
|
|
140
|
+
}).then((prompt) => {
|
|
141
|
+
if (prompt) {
|
|
142
|
+
previousPrompt = prompt
|
|
143
|
+
const data = {
|
|
144
|
+
prompt,
|
|
145
|
+
transactionId,
|
|
146
|
+
context: {
|
|
147
|
+
scope: 'inline', // inline denotes that the prompt is for a inline code (i.e. the monaco editor)
|
|
148
|
+
modulesAllowed,
|
|
149
|
+
codeSection: editorSection
|
|
150
|
+
// selection: selectedText // FUTURE: include the selected text in the context for features like "fix my code", "refactor this", "what is this?" etc
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const busyNotification = showBusyNotification('Busy processing your request. Please wait...', function () {
|
|
154
|
+
if (xhr) {
|
|
155
|
+
xhr.abort('abort')
|
|
156
|
+
xhr = null
|
|
157
|
+
}
|
|
158
|
+
})
|
|
159
|
+
xhr = $.ajax({
|
|
160
|
+
url: 'nr-assistant/function', // /function denotes this is a request for NODE JavaScript code
|
|
161
|
+
type: 'POST',
|
|
162
|
+
data,
|
|
163
|
+
success: function (reply, textStatus, jqXHR) {
|
|
164
|
+
const responseData = reply?.data?.data
|
|
165
|
+
if (responseData?.func?.length > 0) {
|
|
166
|
+
const currentSelection = thisEditor.getSelection()
|
|
167
|
+
// ensure the editor is still present in the DOM
|
|
168
|
+
if (!document.body.contains(thisEditor.getDomNode())) {
|
|
169
|
+
console.warn('Editor is no longer in the DOM')
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
busyNotification.close()
|
|
173
|
+
thisEditor.focus()
|
|
174
|
+
// insert the generated code at the current cursor position overwriting any selected text
|
|
175
|
+
thisEditor.executeEdits('', [
|
|
176
|
+
{
|
|
177
|
+
range: new monaco.Range(currentSelection.startLineNumber, currentSelection.startColumn, currentSelection.endLineNumber, currentSelection.endColumn),
|
|
178
|
+
text: responseData.func
|
|
179
|
+
}
|
|
180
|
+
])
|
|
181
|
+
// update the nodes output count the AI suggests a different number of outputs
|
|
182
|
+
if (typeof responseData?.outputs === 'number' && responseData.outputs >= 0) {
|
|
183
|
+
const outputsField = $('#node-input-outputs')
|
|
184
|
+
const currentOutputs = parseInt(outputsField.val())
|
|
185
|
+
if (!isNaN(currentOutputs) && typeof currentOutputs === 'number' && currentOutputs !== responseData.outputs) {
|
|
186
|
+
outputsField.val(responseData.outputs)
|
|
187
|
+
outputsField.trigger('change')
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// update libs - get the current list of libs then scan the response for any new ones
|
|
192
|
+
// if the lib is not already in the list, add it
|
|
193
|
+
if (modulesAllowed) {
|
|
194
|
+
if (Array.isArray(responseData?.node_modules) && responseData.node_modules.length > 0) {
|
|
195
|
+
const _libs = []
|
|
196
|
+
const libs = $('#node-input-libs-container').editableList('items')
|
|
197
|
+
libs.each(function (i) {
|
|
198
|
+
const item = $(this)
|
|
199
|
+
const v = item.find('.node-input-libs-var').val()
|
|
200
|
+
let n = item.find('.node-input-libs-val').typedInput('type')
|
|
201
|
+
if (n === '_custom_') {
|
|
202
|
+
n = item.find('.node-input-libs-val').val()
|
|
203
|
+
}
|
|
204
|
+
if ((!v || (v === '')) ||
|
|
205
|
+
(!n || (n === ''))) {
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
_libs.push({
|
|
209
|
+
var: v,
|
|
210
|
+
module: n
|
|
211
|
+
})
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
responseData.node_modules.forEach((lib) => {
|
|
215
|
+
const existing = _libs.find(l => l.module === lib.module)
|
|
216
|
+
if (!existing) {
|
|
217
|
+
$('#node-input-libs-container').editableList('addItem', { var: lib.var, module: lib.module })
|
|
218
|
+
}
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
} else {
|
|
223
|
+
processAIErrorResponse(jqXHR, textStatus, 'No response from server')
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
error: (jqXHR, textStatus, errorThrown) => {
|
|
227
|
+
busyNotification.close()
|
|
228
|
+
if (textStatus === 'abort' || errorThrown === 'abort' || jqXHR.statusText === 'abort') {
|
|
229
|
+
// user cancelled
|
|
230
|
+
return
|
|
231
|
+
}
|
|
232
|
+
processAIErrorResponse(jqXHR, textStatus, errorThrown)
|
|
233
|
+
}
|
|
234
|
+
})
|
|
235
|
+
}
|
|
236
|
+
})
|
|
237
|
+
} else {
|
|
238
|
+
console.warn('Could not find editor for model', model.uri.toString())
|
|
239
|
+
}
|
|
240
|
+
})
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// setup actions for function builder
|
|
244
|
+
const funcBuilderTitle = 'FlowFuse Function Node Assistant'
|
|
245
|
+
RED.actions.add('ff:nr-assistant-function-builder', showFunctionBuilderPrompt, { label: funcBuilderTitle })
|
|
246
|
+
|
|
247
|
+
// FUTURE: setup actions for flow builder
|
|
248
|
+
// const flowBuilderTitle = 'FlowFuse Flow Assistant'
|
|
249
|
+
// RED.actions.add('ff:nr-assistant-flow-builder', showFlowBuilderPrompt, { label: flowBuilderTitle })
|
|
250
|
+
|
|
251
|
+
// Add toolbar button
|
|
252
|
+
const toolbarMenuButton = $('<li><a id="red-ui-header-button-ff-ai" class="button fa fa-magic" href="#"></a></li>')
|
|
253
|
+
toolbarMenuButton.prependTo('.red-ui-header-toolbar')
|
|
254
|
+
toolbarMenuButton.on('click', function (e) {
|
|
255
|
+
RED.actions.invoke('ff:nr-assistant-function-builder')
|
|
256
|
+
})
|
|
257
|
+
RED.popover.tooltip(toolbarMenuButton, 'FlowFuse Assistant')
|
|
258
|
+
assistantInitialised = true
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function getUserInput ({ title, explanation, description, placeholder, defaultInput } = {
|
|
262
|
+
title: 'FlowFuse Assistant',
|
|
263
|
+
explanation: 'The FlowFuse Assistant can help you create things.',
|
|
264
|
+
description: 'Enter a short description explaining what you want it to do.',
|
|
265
|
+
placeholder: '',
|
|
266
|
+
defaultInput: ''
|
|
267
|
+
}) {
|
|
268
|
+
const bodyText = []
|
|
269
|
+
if (explanation) {
|
|
270
|
+
bodyText.push(`<p style="">${explanation}</p>`)
|
|
271
|
+
}
|
|
272
|
+
if (description) {
|
|
273
|
+
bodyText.push(`<p>${description}</p>`)
|
|
274
|
+
}
|
|
275
|
+
const body = bodyText.join('')
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
const dialog = $('<div id="ff-nr-ai-dialog-input" class="hide red-ui-editor"></div>')
|
|
278
|
+
const containerDiv = $('<div style="height: 100%;display: flex;flex-direction: column; height: calc(100% - 12px);">')
|
|
279
|
+
if (body) {
|
|
280
|
+
containerDiv.append('<div style="margin-bottom: 8px; margin-top: -10px">' + body + '</div>')
|
|
281
|
+
}
|
|
282
|
+
const form = $('<form id="ff-nr-ai-dialog-input-fields" style="flex-grow: 1; margin-bottom: 6px;"></form>')
|
|
283
|
+
const input = $('<textarea id="ff-nr-ai-dialog-input-editor" style="height:100%;width:100%; position:relative; resize: none;" maxlength="400" placeholder="' + (placeholder || '') + '">' + (defaultInput || '') + '</textarea>')
|
|
284
|
+
form.append(input)
|
|
285
|
+
containerDiv.append(form)
|
|
286
|
+
dialog.append(containerDiv)
|
|
287
|
+
const minHeight = 260 + (description ? 32 : 0) + (explanation ? 32 : 0)
|
|
288
|
+
const minWidth = 480
|
|
289
|
+
dialog.dialog({
|
|
290
|
+
autoOpen: true,
|
|
291
|
+
title: title || 'FlowFuse Assistant',
|
|
292
|
+
modal: true,
|
|
293
|
+
closeOnEscape: true,
|
|
294
|
+
height: minHeight,
|
|
295
|
+
width: minWidth,
|
|
296
|
+
minHeight,
|
|
297
|
+
minWidth,
|
|
298
|
+
resizable: true,
|
|
299
|
+
draggable: true,
|
|
300
|
+
open: function (event, ui) {
|
|
301
|
+
RED.keyboard.disable()
|
|
302
|
+
input.focus()
|
|
303
|
+
input.select()
|
|
304
|
+
},
|
|
305
|
+
close: function (event, ui) {
|
|
306
|
+
RED.keyboard.enable()
|
|
307
|
+
},
|
|
308
|
+
buttons: [
|
|
309
|
+
{
|
|
310
|
+
text: 'Ask the FlowFuse Assistant 🪄',
|
|
311
|
+
// class: 'primary',
|
|
312
|
+
click: function () {
|
|
313
|
+
const prompt = dialog.find('#ff-nr-ai-dialog-input-editor').val()
|
|
314
|
+
resolve(prompt)
|
|
315
|
+
$(this).dialog('close')
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
],
|
|
319
|
+
cancel: function (event, ui) {
|
|
320
|
+
resolve(null)
|
|
321
|
+
$(this).dialog('close')
|
|
322
|
+
}
|
|
323
|
+
})
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
let previousFunctionBuilderPrompt
|
|
328
|
+
function showFunctionBuilderPrompt (title) {
|
|
329
|
+
if (!assistantOptions.enabled) {
|
|
330
|
+
RED.notify('The FlowFuse Assistant is not enabled', 'warning')
|
|
331
|
+
return
|
|
332
|
+
}
|
|
333
|
+
getUserInput({
|
|
334
|
+
defaultInput: previousFunctionBuilderPrompt,
|
|
335
|
+
title: title || 'FlowFuse Assistant : Create A Function Node',
|
|
336
|
+
explanation: 'The FlowFuse Assistant can help you create a Function Node.',
|
|
337
|
+
description: 'Enter a short description of what you want it to do.'
|
|
338
|
+
}).then((prompt) => {
|
|
339
|
+
/** @type {JQueryXHR} */
|
|
340
|
+
let xhr = null
|
|
341
|
+
if (prompt) {
|
|
342
|
+
previousFunctionBuilderPrompt = prompt
|
|
343
|
+
const url = 'nr-assistant/function'
|
|
344
|
+
const transactionId = generateId(8) + '-' + Date.now() // a unique id for this transaction
|
|
345
|
+
const body = {
|
|
346
|
+
prompt,
|
|
347
|
+
transactionId,
|
|
348
|
+
context: {
|
|
349
|
+
scope: 'node', // "node" denotes that the prompt is for a generating a function node (as importable JSON flow code)
|
|
350
|
+
modulesAllowed
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
const busyNotification = showBusyNotification('Busy processing your request. Please wait...', function () {
|
|
354
|
+
if (xhr) {
|
|
355
|
+
xhr.abort('abort')
|
|
356
|
+
xhr = null
|
|
357
|
+
}
|
|
358
|
+
})
|
|
359
|
+
xhr = $.ajax({
|
|
360
|
+
url,
|
|
361
|
+
type: 'POST',
|
|
362
|
+
data: body,
|
|
363
|
+
timeout: assistantOptions.requestTimeout,
|
|
364
|
+
success: (reply, textStatus, jqXHR) => {
|
|
365
|
+
// console.log('showFunctionBuilderPrompt -> ajax -> success', reply)
|
|
366
|
+
busyNotification.close()
|
|
367
|
+
try {
|
|
368
|
+
const flowJson = typeof reply?.data?.flow === 'string' ? JSON.parse(reply.data.flow) : reply?.data?.flow
|
|
369
|
+
if (flowJson && Array.isArray(flowJson) && flowJson.length > 0) {
|
|
370
|
+
importFlow(flowJson)
|
|
371
|
+
} else {
|
|
372
|
+
processAIErrorResponse(jqXHR, textStatus, 'No response from server')
|
|
373
|
+
}
|
|
374
|
+
} catch (error) {
|
|
375
|
+
RED.notify('Sorry, something went wrong, please try again', 'error')
|
|
376
|
+
}
|
|
377
|
+
},
|
|
378
|
+
error: (jqXHR, textStatus, errorThrown) => {
|
|
379
|
+
// console.log('showFunctionBuilderPrompt -> ajax -> error', jqXHR, textStatus, errorThrown)
|
|
380
|
+
busyNotification.close()
|
|
381
|
+
if (textStatus === 'abort' || errorThrown === 'abort' || jqXHR.statusText === 'abort') {
|
|
382
|
+
// user cancelled
|
|
383
|
+
return
|
|
384
|
+
}
|
|
385
|
+
processAIErrorResponse(jqXHR, textStatus, errorThrown)
|
|
386
|
+
}
|
|
387
|
+
})
|
|
388
|
+
}
|
|
389
|
+
})
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
let previousFlowBuilderPrompt
|
|
393
|
+
// eslint-disable-next-line no-unused-vars
|
|
394
|
+
function showFlowBuilderPrompt (title) {
|
|
395
|
+
if (!assistantOptions.enabled) {
|
|
396
|
+
RED.notify('The FlowFuse Assistant is not enabled', 'warning')
|
|
397
|
+
return
|
|
398
|
+
}
|
|
399
|
+
getUserInput({
|
|
400
|
+
defaultInput: previousFlowBuilderPrompt,
|
|
401
|
+
title: title || 'FlowFuse Assistant : Flow Builder',
|
|
402
|
+
explanation: 'The FlowFuse Assistant can help you create a new flow.',
|
|
403
|
+
description: 'Enter a short description of what you want the flow to do.'
|
|
404
|
+
}).then((prompt) => {
|
|
405
|
+
/** @type {JQueryXHR} */
|
|
406
|
+
let xhr = null
|
|
407
|
+
if (prompt) {
|
|
408
|
+
previousFlowBuilderPrompt = prompt
|
|
409
|
+
const url = 'nr-assistant/flow'
|
|
410
|
+
const transactionId = generateId(8) + '-' + Date.now() // a unique id for this transaction
|
|
411
|
+
const body = {
|
|
412
|
+
prompt,
|
|
413
|
+
transactionId,
|
|
414
|
+
context: {
|
|
415
|
+
modulesAllowed
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
const busyNotification = showBusyNotification('Busy processing your request. Please wait...', function () {
|
|
419
|
+
if (xhr) {
|
|
420
|
+
xhr.abort('abort')
|
|
421
|
+
xhr = null
|
|
422
|
+
}
|
|
423
|
+
})
|
|
424
|
+
xhr = $.ajax({
|
|
425
|
+
url,
|
|
426
|
+
type: 'POST',
|
|
427
|
+
data: body,
|
|
428
|
+
timeout: assistantOptions.requestTimeout,
|
|
429
|
+
success: (reply, textStatus, jqXHR) => {
|
|
430
|
+
busyNotification.close()
|
|
431
|
+
try {
|
|
432
|
+
const flowJson = typeof reply?.data?.flow === 'string' ? JSON.parse(reply.data.flow) : reply?.data?.flow
|
|
433
|
+
if (flowJson && Array.isArray(flowJson) && flowJson.length > 0) {
|
|
434
|
+
importFlow(flowJson)
|
|
435
|
+
} else {
|
|
436
|
+
processAIErrorResponse(jqXHR, textStatus, 'No response from server')
|
|
437
|
+
}
|
|
438
|
+
} catch (error) {
|
|
439
|
+
RED.notify('Sorry, something went wrong, please try again', 'error')
|
|
440
|
+
}
|
|
441
|
+
},
|
|
442
|
+
error: (jqXHR, textStatus, errorThrown) => {
|
|
443
|
+
busyNotification.close()
|
|
444
|
+
if (textStatus === 'abort' || errorThrown === 'abort' || jqXHR.statusText === 'abort') {
|
|
445
|
+
// user cancelled
|
|
446
|
+
return
|
|
447
|
+
}
|
|
448
|
+
processAIErrorResponse(jqXHR, textStatus, errorThrown)
|
|
449
|
+
}
|
|
450
|
+
})
|
|
451
|
+
}
|
|
452
|
+
})
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Shows a busy notification with a cancel button
|
|
457
|
+
* @param {string} [message] - The message to display in the notification
|
|
458
|
+
* @param {function} [onCancel] - The function to call when the cancel button is clicked
|
|
459
|
+
* @param {object} [context] - The context object to pass to the onCancel callback function
|
|
460
|
+
* @returns {{close: () => {}}} - The notification object
|
|
461
|
+
*/
|
|
462
|
+
function showBusyNotification (message, onCancel, context, poop) {
|
|
463
|
+
message = message || 'Busy processing your request. Please wait...'
|
|
464
|
+
const busyMessage = $('<div>')
|
|
465
|
+
$('<span>').text(message).appendTo(busyMessage)
|
|
466
|
+
$('<i>').addClass('fa fa-spinner fa-spin fa-fw').appendTo(busyMessage)
|
|
467
|
+
// eslint-disable-next-line prefer-const
|
|
468
|
+
let notification
|
|
469
|
+
const buttons = [
|
|
470
|
+
{
|
|
471
|
+
text: 'cancel',
|
|
472
|
+
click: function () {
|
|
473
|
+
if (onCancel) {
|
|
474
|
+
const result = onCancel(context)
|
|
475
|
+
if (result === false) {
|
|
476
|
+
return
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
notification.close()
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
]
|
|
483
|
+
notification = showNotification(busyMessage, { type: 'success', timeout: 0, fixed: true, modal: true, buttons })
|
|
484
|
+
return notification
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Shows a busy notification with a cancel button
|
|
489
|
+
* @param {string} message - The message to display in the notification
|
|
490
|
+
* @param {object} [options] - The options to pass to the notification
|
|
491
|
+
* @param {'error'|'warning'|'success'|'compact'} [options.type] - The type of notification to display
|
|
492
|
+
* @param {Number} [options.timeout] - How long the notification should be shown for, in milliseconds. Default: 5000. This is ignored if the fixed property is set.
|
|
493
|
+
* @param {boolean} [options.fixed] - Do not hide the notification after a timeout. This also prevents the click-to-close default behaviour of the notification.
|
|
494
|
+
* @param {boolean} [options.modal] - Whether the notification should be modal
|
|
495
|
+
* @param {array} [options.buttons] - An array of buttons to display in the notification. Each button should be an object with a text property and a click property. The click property should be a function to call when the button is clicked. The function will be passed the context object.
|
|
496
|
+
* @returns {{close: () => {}}} - The notification object
|
|
497
|
+
*/
|
|
498
|
+
function showNotification (message, options) {
|
|
499
|
+
options = options || {}
|
|
500
|
+
options.type = options.type || 'success'
|
|
501
|
+
options.timeout = Object.prototype.hasOwnProperty.call(options, 'timeout') ? options.timeout : 5000
|
|
502
|
+
options.fixed = options.fixed || false
|
|
503
|
+
options.modal = options.modal || false
|
|
504
|
+
const pendingNotification = RED.notify(message, options)
|
|
505
|
+
return pendingNotification
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function importFlow (flow, addFlow) {
|
|
509
|
+
let newNodes = flow
|
|
510
|
+
try {
|
|
511
|
+
if (typeof flow === 'string') {
|
|
512
|
+
try {
|
|
513
|
+
flow = flow.trim()
|
|
514
|
+
if (flow.length === 0) {
|
|
515
|
+
return
|
|
516
|
+
}
|
|
517
|
+
newNodes = JSON.parse(flow)
|
|
518
|
+
} catch (err) {
|
|
519
|
+
const e = new Error(RED._('clipboard.invalidFlow', { message: err.message }))
|
|
520
|
+
e.code = 'NODE_RED'
|
|
521
|
+
throw e
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
const importOptions = { generateIds: true, addFlow }
|
|
525
|
+
RED.notify('Place your generated flow onto the workspace', 'compact')
|
|
526
|
+
RED.view.importNodes(newNodes, importOptions)
|
|
527
|
+
} catch (error) {
|
|
528
|
+
// console.log(error)
|
|
529
|
+
RED.notify('Sorry, something went wrong, please try again', 'error')
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function processAIErrorResponse (jqXHR, textStatus, errorThrown) {
|
|
534
|
+
console.warn('error', jqXHR, textStatus, errorThrown)
|
|
535
|
+
RED.notify('Sorry, something went wrong, please try again', 'error')
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function getMonacoEditorForModel (model) {
|
|
539
|
+
// Get the URI of the model, scan the editors for the model with the same URI
|
|
540
|
+
const modelUri = model.uri.toString()
|
|
541
|
+
const editors = monaco.editor.getEditors()
|
|
542
|
+
return editors.find(editor => editor && document.body.contains(editor.getDomNode()) && editor.getModel()?.uri?.toString() === modelUri)
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function generateId (length = 16) {
|
|
546
|
+
if (typeof length !== 'number' || length < 1) {
|
|
547
|
+
throw new Error('Invalid length')
|
|
548
|
+
}
|
|
549
|
+
const iterations = Math.ceil(length / 2)
|
|
550
|
+
const bytes = []
|
|
551
|
+
for (let i = 0; i < iterations; i++) {
|
|
552
|
+
bytes.push(Math.round(0xff * Math.random()).toString(16).padStart(2, '0'))
|
|
553
|
+
}
|
|
554
|
+
return bytes.join('').substring(0, length)
|
|
555
|
+
}
|
|
556
|
+
function debug () {
|
|
557
|
+
if (RED.nrAssistant?.DEBUG) {
|
|
558
|
+
// eslint-disable-next-line no-console
|
|
559
|
+
console.log('[nr-assistant]', ...arguments)
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}(RED, $))
|
|
563
|
+
</script>
|
package/index.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
module.exports = (RED) => {
|
|
2
|
+
const { default: got } = require('got')
|
|
3
|
+
RED.plugins.registerPlugin('flowfuse-nr-assistant', {
|
|
4
|
+
type: 'assistant',
|
|
5
|
+
name: 'Node-RED Assistant Plugin',
|
|
6
|
+
icon: 'font-awesome/fa-magic',
|
|
7
|
+
settings: {
|
|
8
|
+
'*': { exportable: true }
|
|
9
|
+
},
|
|
10
|
+
onadd: function () {
|
|
11
|
+
const assistantSettings = RED.settings.flowforge?.assistant || { enabled: false }
|
|
12
|
+
const clientSettings = {
|
|
13
|
+
enabled: assistantSettings.enabled !== false && !!assistantSettings.url,
|
|
14
|
+
requestTimeout: assistantSettings.requestTimeout || 60000
|
|
15
|
+
}
|
|
16
|
+
RED.comms.publish('nr-assistant/initialise', clientSettings, true /* retain */)
|
|
17
|
+
|
|
18
|
+
if (!assistantSettings || !assistantSettings.enabled) {
|
|
19
|
+
RED.log.info('FlowFuse Assistant Plugin is disabled')
|
|
20
|
+
return
|
|
21
|
+
}
|
|
22
|
+
if (!assistantSettings.url) {
|
|
23
|
+
RED.log.info('FlowFuse Assistant Plugin is missing url')
|
|
24
|
+
return
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
RED.log.info('FlowFuse Assistant Plugin loaded')
|
|
28
|
+
|
|
29
|
+
RED.httpAdmin.post('/nr-assistant/:method', RED.auth.needsPermission('write'), function (req, res) {
|
|
30
|
+
const method = req.params.method || 'fn'
|
|
31
|
+
// limit method to prevent path traversal
|
|
32
|
+
if (/[^a-zA-Z0-9-_]/.test(method)) {
|
|
33
|
+
res.status(400)
|
|
34
|
+
res.json({ status: 'error', message: 'Invalid method' })
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
const input = req.body
|
|
38
|
+
const prompt = input.prompt
|
|
39
|
+
if (!input.prompt) {
|
|
40
|
+
res.status(400)
|
|
41
|
+
res.json({ status: 'error', message: 'prompt is required' })
|
|
42
|
+
return
|
|
43
|
+
}
|
|
44
|
+
const body = {
|
|
45
|
+
prompt, // this is the prompt to the AI
|
|
46
|
+
promptHint: input.promptHint, // this is used to let the AI know what we are generating (`function node? Node JavaScript? flow?)
|
|
47
|
+
context: input.context, // this is used to provide additional context to the AI (e.g. the selected text of the function node)
|
|
48
|
+
transactionId: input.transactionId // used to correlate the request with the response
|
|
49
|
+
}
|
|
50
|
+
// join url & method (taking care of trailing slashes)
|
|
51
|
+
const url = `${assistantSettings.url.replace(/\/$/, '')}/${method.replace(/^\//, '')}`
|
|
52
|
+
got.post(url, {
|
|
53
|
+
headers: {
|
|
54
|
+
Accept: '*/*',
|
|
55
|
+
'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8,es;q=0.7',
|
|
56
|
+
Authorization: `Bearer ${assistantSettings.token}`,
|
|
57
|
+
'Content-Type': 'application/json'
|
|
58
|
+
},
|
|
59
|
+
json: body
|
|
60
|
+
}).then(response => {
|
|
61
|
+
const data = JSON.parse(response.body)
|
|
62
|
+
res.json({
|
|
63
|
+
status: 'ok',
|
|
64
|
+
data
|
|
65
|
+
})
|
|
66
|
+
}).catch((error) => {
|
|
67
|
+
const errorData = { status: 'error', message: 'Request to FlowFuse Assistant was unsuccessful', body: error.response?.body }
|
|
68
|
+
const errorCode = error.response?.statusCode || 500
|
|
69
|
+
res.status(errorCode).json({ status: 'error', message: errorData })
|
|
70
|
+
console.warn('nr-assistant error:', error)
|
|
71
|
+
RED.log.warn('FlowFuse Assistant request was unsuccessful')
|
|
72
|
+
})
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@flowfuse/nr-assistant",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "FlowFuse Node-RED assistant plugin",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "echo \"Error: no test specified\" && exit 0",
|
|
8
|
+
"lint": "eslint -c .eslintrc --ext js,html *.js *.html",
|
|
9
|
+
"lint:fix": "eslint -c .eslintrc --ext js,html *.js *.html --fix"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"node-red",
|
|
13
|
+
"nodered",
|
|
14
|
+
"flowfuse",
|
|
15
|
+
"plugin",
|
|
16
|
+
"ai",
|
|
17
|
+
"lowcode"
|
|
18
|
+
],
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/FlowFuse/nr-assistant.git"
|
|
22
|
+
},
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/FlowFuse/nr-assistant/issues"
|
|
25
|
+
},
|
|
26
|
+
"homepage": "https://github.com/FlowFuse/nr-assistant#readme",
|
|
27
|
+
"author": "FlowFuse Inc.",
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"node-red": {
|
|
30
|
+
"version": ">=2.2.0",
|
|
31
|
+
"plugins": {
|
|
32
|
+
"flowfuse-nr-assistant": "index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=16.x"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"got": "^11.8.6"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"eslint": "^8.48.0",
|
|
43
|
+
"eslint-config-standard": "^17.1.0",
|
|
44
|
+
"eslint-plugin-html": "7.1.0",
|
|
45
|
+
"eslint-plugin-no-only-tests": "^3.1.0"
|
|
46
|
+
}
|
|
47
|
+
}
|