@aigne/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/lib/cjs/assistant/generate-output.js +101 -0
  2. package/lib/cjs/assistant/select-agent.js +76 -0
  3. package/lib/cjs/assistant/type.js +11 -0
  4. package/lib/cjs/common/aid.js +42 -0
  5. package/lib/cjs/common/index.js +238 -0
  6. package/lib/cjs/common/resource-manager.js +199 -0
  7. package/lib/cjs/constants.js +9 -0
  8. package/lib/cjs/executor/agent.js +10 -0
  9. package/lib/cjs/executor/aigc.js +28 -0
  10. package/lib/cjs/executor/api.js +64 -0
  11. package/lib/cjs/executor/base.js +676 -0
  12. package/lib/cjs/executor/blocklet.js +25 -0
  13. package/lib/cjs/executor/call-agent.js +105 -0
  14. package/lib/cjs/executor/decision.js +478 -0
  15. package/lib/cjs/executor/image-blender.js +32 -0
  16. package/lib/cjs/executor/index.js +81 -0
  17. package/lib/cjs/executor/llm.js +379 -0
  18. package/lib/cjs/executor/logic.js +167 -0
  19. package/lib/cjs/index.js +17 -0
  20. package/lib/cjs/libs/blocklet/vc.js +92 -0
  21. package/lib/cjs/libs/openapi/request/index.js +24 -0
  22. package/lib/cjs/libs/openapi/request/util.js +146 -0
  23. package/lib/cjs/libs/openapi/types/index.js +17 -0
  24. package/lib/cjs/libs/openapi/util/call.js +15 -0
  25. package/lib/cjs/libs/openapi/util/check-schema.js +67 -0
  26. package/lib/cjs/libs/openapi/util/convert-schema.js +44 -0
  27. package/lib/cjs/libs/openapi/util/flatten-open-api.js +21 -0
  28. package/lib/cjs/libs/openapi/util/get-open-api-i18n-text.js +7 -0
  29. package/lib/cjs/logger.js +4 -0
  30. package/lib/cjs/runtime/resource-blocklet.js +5 -0
  31. package/lib/cjs/runtime/runtime.js +143 -0
  32. package/lib/cjs/types/assistant/index.js +31 -0
  33. package/lib/cjs/types/assistant/mustache/ReadableMustache.js +69 -0
  34. package/lib/cjs/types/assistant/mustache/directive.js +35 -0
  35. package/lib/cjs/types/assistant/mustache/mustache.js +688 -0
  36. package/lib/cjs/types/common/index.js +2 -0
  37. package/lib/cjs/types/index.js +20 -0
  38. package/lib/cjs/types/resource/index.js +47 -0
  39. package/lib/cjs/types/resource/project.js +35 -0
  40. package/lib/cjs/types/runtime/agent.js +2 -0
  41. package/lib/cjs/types/runtime/error.js +18 -0
  42. package/lib/cjs/types/runtime/index.js +37 -0
  43. package/lib/cjs/types/runtime/runtime-resource-blocklet-state.js +4 -0
  44. package/lib/cjs/types/runtime/schema.js +259 -0
  45. package/lib/cjs/utils/cron-job.js +48 -0
  46. package/lib/cjs/utils/extract-metadata-transform.js +58 -0
  47. package/lib/cjs/utils/extract-metadata-transform.test.js +61 -0
  48. package/lib/cjs/utils/fs.js +49 -0
  49. package/lib/cjs/utils/get-blocklet-agent.js +351 -0
  50. package/lib/cjs/utils/geti.js +37 -0
  51. package/lib/cjs/utils/is-non-nullable.js +20 -0
  52. package/lib/cjs/utils/render-message.js +23 -0
  53. package/lib/cjs/utils/resolve-secret-inputs.js +49 -0
  54. package/lib/cjs/utils/retry.js +19 -0
  55. package/lib/cjs/utils/task-id.js +7 -0
  56. package/lib/cjs/utils/tool-calls-transform.js +18 -0
  57. package/lib/esm/assistant/generate-output.js +91 -0
  58. package/lib/esm/assistant/select-agent.js +71 -0
  59. package/lib/esm/assistant/type.js +7 -0
  60. package/lib/esm/common/aid.js +38 -0
  61. package/lib/esm/common/index.js +232 -0
  62. package/lib/esm/common/resource-manager.js +192 -0
  63. package/lib/esm/constants.js +6 -0
  64. package/lib/esm/executor/agent.js +6 -0
  65. package/lib/esm/executor/aigc.js +24 -0
  66. package/lib/esm/executor/api.js +34 -0
  67. package/lib/esm/executor/base.js +668 -0
  68. package/lib/esm/executor/blocklet.js +21 -0
  69. package/lib/esm/executor/call-agent.js +98 -0
  70. package/lib/esm/executor/decision.js +471 -0
  71. package/lib/esm/executor/image-blender.js +25 -0
  72. package/lib/esm/executor/index.js +74 -0
  73. package/lib/esm/executor/llm.js +372 -0
  74. package/lib/esm/executor/logic.js +160 -0
  75. package/lib/esm/index.js +1 -0
  76. package/lib/esm/libs/blocklet/vc.js +85 -0
  77. package/lib/esm/libs/openapi/request/index.js +20 -0
  78. package/lib/esm/libs/openapi/request/util.js +136 -0
  79. package/lib/esm/libs/openapi/types/index.js +1 -0
  80. package/lib/esm/libs/openapi/util/call.js +8 -0
  81. package/lib/esm/libs/openapi/util/check-schema.js +62 -0
  82. package/lib/esm/libs/openapi/util/convert-schema.js +42 -0
  83. package/lib/esm/libs/openapi/util/flatten-open-api.js +19 -0
  84. package/lib/esm/libs/openapi/util/get-open-api-i18n-text.js +5 -0
  85. package/lib/esm/logger.js +2 -0
  86. package/lib/esm/runtime/resource-blocklet.js +2 -0
  87. package/lib/esm/runtime/runtime.js +136 -0
  88. package/lib/esm/types/assistant/index.js +9 -0
  89. package/lib/esm/types/assistant/mustache/ReadableMustache.js +63 -0
  90. package/lib/esm/types/assistant/mustache/directive.js +29 -0
  91. package/lib/esm/types/assistant/mustache/mustache.js +686 -0
  92. package/lib/esm/types/common/index.js +1 -0
  93. package/lib/esm/types/index.js +4 -0
  94. package/lib/esm/types/resource/index.js +26 -0
  95. package/lib/esm/types/resource/project.js +29 -0
  96. package/lib/esm/types/runtime/agent.js +1 -0
  97. package/lib/esm/types/runtime/error.js +14 -0
  98. package/lib/esm/types/runtime/index.js +20 -0
  99. package/lib/esm/types/runtime/runtime-resource-blocklet-state.js +1 -0
  100. package/lib/esm/types/runtime/schema.js +249 -0
  101. package/lib/esm/utils/cron-job.js +44 -0
  102. package/lib/esm/utils/extract-metadata-transform.js +54 -0
  103. package/lib/esm/utils/extract-metadata-transform.test.js +59 -0
  104. package/lib/esm/utils/fs.js +41 -0
  105. package/lib/esm/utils/get-blocklet-agent.js +344 -0
  106. package/lib/esm/utils/geti.js +30 -0
  107. package/lib/esm/utils/is-non-nullable.js +13 -0
  108. package/lib/esm/utils/render-message.js +20 -0
  109. package/lib/esm/utils/resolve-secret-inputs.js +46 -0
  110. package/lib/esm/utils/retry.js +16 -0
  111. package/lib/esm/utils/task-id.js +3 -0
  112. package/lib/esm/utils/tool-calls-transform.js +15 -0
  113. package/lib/types/assistant/generate-output.d.ts +29 -0
  114. package/lib/types/assistant/select-agent.d.ts +14 -0
  115. package/lib/types/assistant/type.d.ts +61 -0
  116. package/lib/types/common/aid.d.ts +18 -0
  117. package/lib/types/common/index.d.ts +7 -0
  118. package/lib/types/common/resource-manager.d.ts +88 -0
  119. package/lib/types/constants.d.ts +6 -0
  120. package/lib/types/executor/agent.d.ts +5 -0
  121. package/lib/types/executor/aigc.d.ts +9 -0
  122. package/lib/types/executor/api.d.ts +9 -0
  123. package/lib/types/executor/base.d.ts +209 -0
  124. package/lib/types/executor/blocklet.d.ts +9 -0
  125. package/lib/types/executor/call-agent.d.ts +12 -0
  126. package/lib/types/executor/decision.d.ts +20 -0
  127. package/lib/types/executor/image-blender.d.ts +9 -0
  128. package/lib/types/executor/index.d.ts +8 -0
  129. package/lib/types/executor/llm.d.ts +38 -0
  130. package/lib/types/executor/logic.d.ts +9 -0
  131. package/lib/types/index.d.ts +1 -0
  132. package/lib/types/libs/blocklet/vc.d.ts +17 -0
  133. package/lib/types/libs/openapi/request/index.d.ts +17 -0
  134. package/lib/types/libs/openapi/request/util.d.ts +40 -0
  135. package/lib/types/libs/openapi/types/index.d.ts +20 -0
  136. package/lib/types/libs/openapi/util/call.d.ts +2 -0
  137. package/lib/types/libs/openapi/util/check-schema.d.ts +3 -0
  138. package/lib/types/libs/openapi/util/convert-schema.d.ts +8 -0
  139. package/lib/types/libs/openapi/util/flatten-open-api.d.ts +3 -0
  140. package/lib/types/libs/openapi/util/get-open-api-i18n-text.d.ts +2 -0
  141. package/lib/types/logger.d.ts +2 -0
  142. package/lib/types/runtime/resource-blocklet.d.ts +2 -0
  143. package/lib/types/runtime/runtime.d.ts +20 -0
  144. package/lib/types/types/assistant/index.d.ts +405 -0
  145. package/lib/types/types/assistant/mustache/ReadableMustache.d.ts +2 -0
  146. package/lib/types/types/assistant/mustache/directive.d.ts +6 -0
  147. package/lib/types/types/assistant/mustache/mustache.d.ts +2 -0
  148. package/lib/types/types/common/index.d.ts +45 -0
  149. package/lib/types/types/index.d.ts +4 -0
  150. package/lib/types/types/resource/index.d.ts +17 -0
  151. package/lib/types/types/resource/project.d.ts +41 -0
  152. package/lib/types/types/runtime/agent.d.ts +33 -0
  153. package/lib/types/types/runtime/error.d.ts +10 -0
  154. package/lib/types/types/runtime/index.d.ts +116 -0
  155. package/lib/types/types/runtime/runtime-resource-blocklet-state.d.ts +5 -0
  156. package/lib/types/types/runtime/schema.d.ts +110 -0
  157. package/lib/types/utils/cron-job.d.ts +22 -0
  158. package/lib/types/utils/extract-metadata-transform.d.ts +16 -0
  159. package/lib/types/utils/extract-metadata-transform.test.d.ts +1 -0
  160. package/lib/types/utils/fs.d.ts +9 -0
  161. package/lib/types/utils/get-blocklet-agent.d.ts +219 -0
  162. package/lib/types/utils/geti.d.ts +1 -0
  163. package/lib/types/utils/is-non-nullable.d.ts +2 -0
  164. package/lib/types/utils/render-message.d.ts +6 -0
  165. package/lib/types/utils/resolve-secret-inputs.d.ts +11 -0
  166. package/lib/types/utils/retry.d.ts +1 -0
  167. package/lib/types/utils/task-id.d.ts +1 -0
  168. package/lib/types/utils/tool-calls-transform.d.ts +2 -0
  169. package/package.json +67 -0
  170. package/tsconfig.json +12 -0
@@ -0,0 +1,71 @@
1
+ import { isChatCompletionChunk } from '@blocklet/ai-kit/api/types/chat';
2
+ import retry from '../utils/retry';
3
+ const selectAgentSystemPrompt = () => `\
4
+ ### Job Description
5
+ You are a text classification engine that analyzes text data and assigns categories based on user input or automatically determined categories.
6
+
7
+
8
+ ### Task
9
+ Your task is to assign one categories ONLY to the input text and only one category may be assigned returned in the output.
10
+ Additionally, you need to extract the key words from the text that are related to the classification.
11
+
12
+
13
+ ### Format
14
+ - "input_text" is in the variable text_field.
15
+ - "categories" are specified as a category list in the variable categories or left empty for automatic determination.
16
+ - "classification_instructions" may be included to improve the classification accuracy.
17
+
18
+
19
+ ### Constraint
20
+ - DO NOT include anything other than the JSON array in your response.
21
+ - The output results must be within the scope of categories, not content outside the scope
22
+ `;
23
+ async function generateSelectAgentName({ assistant, message, callAI, maxRetries = 0, categories, }) {
24
+ return retry(async () => {
25
+ const selectAgentIdResponseByPrompt = await callAI({
26
+ assistant,
27
+ input: {
28
+ messages: [
29
+ {
30
+ role: 'system',
31
+ content: `${selectAgentSystemPrompt()}`,
32
+ },
33
+ {
34
+ role: 'user',
35
+ content: '\n { "input_text": ["I recently had a great experience with your company. The service was prompt and the staff was very friendly."],\n "categories": [{,"category_name": "Customer Service"}, {"category_name": "Satisfaction"}, {"category_name": "Sales"}, {"category_name": "Product"}],\n "classification_instructions": []}\n',
36
+ },
37
+ {
38
+ role: 'assistant',
39
+ content: '{"category_name": "Customer Service"}',
40
+ },
41
+ {
42
+ role: 'user',
43
+ content: '\n {"input_text": ["bad service, slow to bring the food"],\n "categories": [{"category_name": "Food Quality"}, {"category_name": "Experience"}, {"category_name": "Price"}],\n "classification_instructions": []}\n',
44
+ },
45
+ {
46
+ role: 'assistant',
47
+ content: '{"category_name": "Experience"}',
48
+ },
49
+ {
50
+ role: 'user',
51
+ content: `\n {"input_text": [${message}],\n "categories": [${categories}],\n "classification_instructions": []}\n`,
52
+ },
53
+ ],
54
+ model: assistant?.model,
55
+ temperature: assistant?.temperature,
56
+ topP: assistant?.topP,
57
+ presencePenalty: assistant?.presencePenalty,
58
+ frequencyPenalty: assistant?.frequencyPenalty,
59
+ },
60
+ });
61
+ let text = '';
62
+ for await (const chunk of selectAgentIdResponseByPrompt) {
63
+ if (isChatCompletionChunk(chunk) && chunk.delta.content) {
64
+ text += chunk.delta.content;
65
+ }
66
+ }
67
+ const json = JSON.parse(text);
68
+ return json;
69
+ }, maxRetries);
70
+ }
71
+ export default generateSelectAgentName;
@@ -0,0 +1,7 @@
1
+ export class ToolCompletionDirective extends Error {
2
+ type;
3
+ constructor(message, type) {
4
+ super(message);
5
+ this.type = type;
6
+ }
7
+ }
@@ -0,0 +1,38 @@
1
+ import { Base64 } from 'js-base64';
2
+ export function parseIdentity(aid, options) {
3
+ let blockletDid;
4
+ let projectId;
5
+ let projectRef;
6
+ let agentId;
7
+ try {
8
+ const s = Base64.decode(aid).split('/');
9
+ if (s.length === 4) {
10
+ [blockletDid, projectId, projectRef, agentId] = s;
11
+ }
12
+ else if (s.length === 3) {
13
+ [projectId, projectRef, agentId] = s;
14
+ }
15
+ else if (s.length === 2) {
16
+ [projectId, agentId] = s;
17
+ }
18
+ }
19
+ catch (error) {
20
+ console.error('parse assistantId error', { error });
21
+ }
22
+ if (projectId && agentId)
23
+ return {
24
+ blockletDid: blockletDid || undefined,
25
+ projectId,
26
+ projectRef: projectRef || undefined,
27
+ agentId,
28
+ };
29
+ if (options?.rejectWhenError)
30
+ throw new Error(`Invalid assistant identity ${aid}`);
31
+ return undefined;
32
+ }
33
+ export function stringifyIdentity({ blockletDid, projectId, projectRef, agentId, }) {
34
+ if (typeof projectId !== 'string' || typeof agentId !== 'string') {
35
+ throw new Error('Invalid aid fragments');
36
+ }
37
+ return Base64.encodeURI([blockletDid || '', projectId, projectRef || '', agentId].join('/'));
38
+ }
@@ -0,0 +1,232 @@
1
+ export const defaultTextModel = 'gpt-4o-mini';
2
+ export const supportJsonSchemaModels = ['gpt-4o', 'gpt-4o-mini'];
3
+ export async function getSupportedModels() {
4
+ return [
5
+ {
6
+ brand: 'OpenAI',
7
+ model: 'gpt-4o',
8
+ name: 'GPT4o',
9
+ temperatureMin: 0,
10
+ temperatureMax: 2,
11
+ temperatureDefault: 1,
12
+ topPMin: 0,
13
+ topPMax: 1,
14
+ topPDefault: 1,
15
+ presencePenaltyMin: -2,
16
+ presencePenaltyMax: 2,
17
+ presencePenaltyDefault: 0,
18
+ frequencyPenaltyMin: -2,
19
+ frequencyPenaltyMax: 2,
20
+ frequencyPenaltyDefault: 0,
21
+ maxTokensMin: 1,
22
+ maxTokensMax: 128000,
23
+ maxTokensDefault: 128000,
24
+ },
25
+ {
26
+ brand: 'OpenAI',
27
+ model: 'gpt-4o-mini',
28
+ name: 'GPT4o mini',
29
+ temperatureMin: 0,
30
+ temperatureMax: 2,
31
+ temperatureDefault: 1,
32
+ topPMin: 0,
33
+ topPMax: 1,
34
+ topPDefault: 1,
35
+ presencePenaltyMin: -2,
36
+ presencePenaltyMax: 2,
37
+ presencePenaltyDefault: 0,
38
+ frequencyPenaltyMin: -2,
39
+ frequencyPenaltyMax: 2,
40
+ frequencyPenaltyDefault: 0,
41
+ maxTokensMin: 1,
42
+ maxTokensMax: 128000,
43
+ maxTokensDefault: 128000,
44
+ },
45
+ {
46
+ brand: 'OpenAI',
47
+ model: 'gpt-3.5-turbo',
48
+ name: 'GPT3.5 turbo',
49
+ temperatureMin: 0,
50
+ temperatureMax: 2,
51
+ temperatureDefault: 1,
52
+ topPMin: 0,
53
+ topPMax: 1,
54
+ topPDefault: 1,
55
+ presencePenaltyMin: -2,
56
+ presencePenaltyMax: 2,
57
+ presencePenaltyDefault: 0,
58
+ frequencyPenaltyMin: -2,
59
+ frequencyPenaltyMax: 2,
60
+ frequencyPenaltyDefault: 0,
61
+ maxTokensMin: 1,
62
+ maxTokensMax: 4096,
63
+ maxTokensDefault: 4096,
64
+ },
65
+ {
66
+ brand: 'OpenAI',
67
+ model: 'gpt-3.5-turbo-16k',
68
+ name: 'GPT3.5 turbo 16k',
69
+ temperatureMin: 0,
70
+ temperatureMax: 2,
71
+ temperatureDefault: 1,
72
+ topPMin: 0,
73
+ topPMax: 1,
74
+ topPDefault: 1,
75
+ presencePenaltyMin: -2,
76
+ presencePenaltyMax: 2,
77
+ presencePenaltyDefault: 0,
78
+ frequencyPenaltyMin: -2,
79
+ frequencyPenaltyMax: 2,
80
+ frequencyPenaltyDefault: 0,
81
+ maxTokensMin: 1,
82
+ maxTokensMax: 16385,
83
+ maxTokensDefault: 16385,
84
+ },
85
+ {
86
+ brand: 'OpenAI',
87
+ model: 'gpt-4',
88
+ name: 'GPT4',
89
+ temperatureMin: 0,
90
+ temperatureMax: 2,
91
+ temperatureDefault: 1,
92
+ topPMin: 0,
93
+ topPMax: 1,
94
+ topPDefault: 1,
95
+ presencePenaltyMin: -2,
96
+ presencePenaltyMax: 2,
97
+ presencePenaltyDefault: 0,
98
+ frequencyPenaltyMin: -2,
99
+ frequencyPenaltyMax: 2,
100
+ frequencyPenaltyDefault: 0,
101
+ maxTokensMin: 1,
102
+ maxTokensMax: 8192,
103
+ maxTokensDefault: 8192,
104
+ },
105
+ {
106
+ brand: 'OpenAI',
107
+ model: 'gpt-4-32k',
108
+ name: 'GPT4 32k',
109
+ temperatureMin: 0,
110
+ temperatureMax: 2,
111
+ temperatureDefault: 1,
112
+ topPMin: 0,
113
+ topPMax: 1,
114
+ topPDefault: 1,
115
+ presencePenaltyMin: -2,
116
+ presencePenaltyMax: 2,
117
+ presencePenaltyDefault: 0,
118
+ frequencyPenaltyMin: -2,
119
+ frequencyPenaltyMax: 2,
120
+ frequencyPenaltyDefault: 0,
121
+ maxTokensMin: 1,
122
+ maxTokensMax: 32768,
123
+ maxTokensDefault: 32768,
124
+ },
125
+ {
126
+ brand: 'Google',
127
+ model: 'gemini-pro',
128
+ name: 'Gemini Pro',
129
+ temperatureMin: 0,
130
+ temperatureMax: 2,
131
+ temperatureDefault: 1,
132
+ topPMin: 0.1,
133
+ topPMax: 1,
134
+ topPDefault: 1,
135
+ maxTokensMin: 1,
136
+ maxTokensMax: 2048,
137
+ maxTokensDefault: 2048,
138
+ },
139
+ {
140
+ brand: 'Mistral AI',
141
+ model: 'openRouter/mistralai/mistral-7b-instruct',
142
+ name: 'Mistral 7B Instruct',
143
+ temperatureMin: 0,
144
+ temperatureMax: 2,
145
+ temperatureDefault: 1,
146
+ topPMin: 0,
147
+ topPMax: 1,
148
+ topPDefault: 1,
149
+ maxTokensMin: 1,
150
+ maxTokensMax: 8192,
151
+ maxTokensDefault: 8192,
152
+ },
153
+ {
154
+ brand: 'Mistral AI',
155
+ model: 'openRouter/mistralai/mixtral-8x7b-instruct',
156
+ name: 'Mixtral 8x7B Instruct (beta)',
157
+ temperatureMin: 0,
158
+ temperatureMax: 2,
159
+ temperatureDefault: 1,
160
+ topPMin: 0,
161
+ topPMax: 1,
162
+ topPDefault: 1,
163
+ maxTokensMin: 1,
164
+ maxTokensMax: 32768,
165
+ maxTokensDefault: 32768,
166
+ },
167
+ {
168
+ brand: 'Hugging Face',
169
+ model: 'Hugging Face',
170
+ disabled: true,
171
+ },
172
+ {
173
+ brand: 'Azure OpenAI',
174
+ model: 'Azure OpenAI',
175
+ disabled: true,
176
+ },
177
+ {
178
+ brand: 'Replicate',
179
+ model: 'Replicate',
180
+ disabled: true,
181
+ },
182
+ {
183
+ brand: 'Vertex AI',
184
+ model: 'Vertex AI',
185
+ disabled: true,
186
+ },
187
+ ];
188
+ }
189
+ export const defaultImageModel = 'dall-e-2';
190
+ export async function getSupportedImagesModels() {
191
+ return [
192
+ {
193
+ brand: 'OpenAI',
194
+ model: 'dall-e-2',
195
+ nMin: 1,
196
+ nMax: 10,
197
+ nDefault: 1,
198
+ size: ['256x256', '512x512', '1024x1024'],
199
+ sizeDefault: '256x256',
200
+ },
201
+ {
202
+ brand: 'OpenAI',
203
+ model: 'dall-e-3',
204
+ nMin: 1,
205
+ nMax: 1,
206
+ nDefault: 1,
207
+ quality: ['standard', 'hd'],
208
+ qualityDefault: 'standard',
209
+ size: ['1024x1024', '1792x1024', '1024x1792'],
210
+ sizeDefault: '1024x1024',
211
+ style: ['vivid', 'natural'],
212
+ styleDefault: 'vivid',
213
+ },
214
+ ];
215
+ }
216
+ export function getServiceModePermissionMap(serviceMode) {
217
+ const permissionMap = {
218
+ single: {
219
+ ensureViewAllProjectsRoles: ['owner', 'admin', 'promptsEditor'],
220
+ ensurePromptsEditorRoles: ['owner', 'admin', 'promptsEditor'],
221
+ ensurePromptsAdminRoles: ['owner', 'admin', 'promptsEditor'],
222
+ },
223
+ multiple: {
224
+ ensureViewAllProjectsRoles: [],
225
+ // no need to check, everyone can do it, will check author permission in the backend
226
+ ensurePromptsEditorRoles: undefined,
227
+ ensurePromptsAdminRoles: ['owner', 'admin', 'promptsEditor'],
228
+ },
229
+ };
230
+ // try to fallback to 'single-tenant'
231
+ return permissionMap[serviceMode] || permissionMap.single;
232
+ }
@@ -0,0 +1,192 @@
1
+ import { readFile, readdir } from 'fs/promises';
2
+ import { dirname, join } from 'path';
3
+ import { getResources } from '@blocklet/sdk/lib/component';
4
+ import config from '@blocklet/sdk/lib/config';
5
+ import { exists } from 'fs-extra';
6
+ import { groupBy, throttle } from 'lodash';
7
+ import { parse } from 'yaml';
8
+ import { AIGNE_STUDIO_COMPONENT_DID } from '../constants';
9
+ import logger from '../logger';
10
+ import { ResourceTypes, validateResourceProject } from '../types';
11
+ import { isNonNullable, isPropsNonNullable } from '../utils/is-non-nullable';
12
+ const getResourceList = () => {
13
+ return ResourceTypes.flatMap((type) => getResources({ types: [{ did: AIGNE_STUDIO_COMPONENT_DID, type }], skipRunningCheck: true }).map((i) => ({
14
+ ...i,
15
+ type,
16
+ }))).filter(isPropsNonNullable('path'));
17
+ };
18
+ async function loadProjectsFromResourceBlockletDir({ did, path, }) {
19
+ if (!(await exists(path)))
20
+ return [];
21
+ const projectYamlPaths = (await readdir(path)).map((filename) => join(path, filename, `${filename}.yaml`));
22
+ return (await Promise.all(projectYamlPaths.map(async (filepath) => {
23
+ try {
24
+ const project = await validateResourceProject(parse((await readFile(filepath)).toString()));
25
+ return {
26
+ ...project,
27
+ blocklet: { did },
28
+ dir: dirname(filepath),
29
+ agentMap: Object.fromEntries(project.agents.map((i) => [i.id, i])),
30
+ };
31
+ }
32
+ catch (error) {
33
+ logger.error('parse aigne project resource file error', { error });
34
+ return null;
35
+ }
36
+ }))).filter(isNonNullable);
37
+ }
38
+ const loadResourceKnowledge = async () => {
39
+ const dirs = getResourceList().filter((i) => i.type === 'knowledge');
40
+ if (dirs.length === 0)
41
+ return [];
42
+ return (await Promise.all(dirs.map(async (item) => {
43
+ try {
44
+ if (!(await exists(item.path)))
45
+ return undefined;
46
+ const knowledgeIds = await readdir(item.path);
47
+ if (!knowledgeIds.length)
48
+ return undefined;
49
+ return await Promise.all(knowledgeIds.map(async (knowledgeId) => {
50
+ try {
51
+ const knowledgePath = join(item.path, knowledgeId);
52
+ const vectorsPath = join(knowledgePath, 'vectors');
53
+ const uploadPath = join(knowledgePath, 'uploads');
54
+ const sourcesPath = join(knowledgePath, 'sources');
55
+ const processedPath = join(knowledgePath, 'processed');
56
+ const logoPath = join(knowledgePath, 'logo.png');
57
+ const knowledgeJsonPath = join(knowledgePath, 'knowledge.yaml');
58
+ const knowledge = parse((await readFile(knowledgeJsonPath)).toString());
59
+ const documentsPath = join(knowledgePath, 'documents.yaml');
60
+ const documents = parse((await readFile(documentsPath)).toString());
61
+ const contentsPath = join(knowledgePath, 'contents.yaml');
62
+ const contents = (await exists(contentsPath)) ? parse((await readFile(contentsPath)).toString()) : [];
63
+ const segmentsPath = join(knowledgePath, 'segments.yaml');
64
+ const segments = (await exists(segmentsPath)) ? parse((await readFile(segmentsPath)).toString()) : [];
65
+ return {
66
+ title: item.title,
67
+ did: item.did,
68
+ knowledge: { projectId: knowledge.appId, ...knowledge },
69
+ documents,
70
+ segments,
71
+ contents,
72
+ blockletDid: item.did,
73
+ vectorsPath,
74
+ uploadPath, // old source
75
+ sourcesPath, // new source
76
+ processedPath,
77
+ logoPath,
78
+ };
79
+ }
80
+ catch (error) {
81
+ logger.error('read knowledge resource error', { error });
82
+ }
83
+ return undefined;
84
+ }));
85
+ }
86
+ catch (error) {
87
+ logger.error('read knowledge resource error', { error });
88
+ }
89
+ return undefined;
90
+ })))
91
+ .flat()
92
+ .filter(isNonNullable);
93
+ };
94
+ async function loadResources() {
95
+ const list = getResourceList().filter((i) => i.type !== 'knowledge');
96
+ const resources = groupBy(await Promise.all(list.map(async (item) => ({ ...item, projects: await loadProjectsFromResourceBlockletDir(item) }))), (i) => i.type);
97
+ const knowledgeList = await loadResourceKnowledge();
98
+ return {
99
+ knowledge: {
100
+ knowledgeList,
101
+ blockletMap: Object.fromEntries(Object.entries(groupBy(knowledgeList, (i) => i.blockletDid)).map(([blockletDid, kbs]) => [
102
+ blockletDid,
103
+ { knowledgeMap: Object.fromEntries(kbs.map((i) => [i.knowledge.id, i])) },
104
+ ])),
105
+ },
106
+ agents: Object.fromEntries(Object.entries(resources).map(([type, group]) => {
107
+ const blocklets = Object.entries(groupBy(group.flatMap((i) => i.projects), (i) => i.blocklet.did)).map(([blockletDid, projects]) => ({
108
+ did: blockletDid,
109
+ status: group[0].status,
110
+ projectMap: Object.fromEntries(projects.map((i) => [i.project.id, i])),
111
+ }));
112
+ return [
113
+ type,
114
+ {
115
+ projects: group.flatMap((i) => i.projects),
116
+ blockletMap: Object.fromEntries(blocklets.map((i) => [i.did, i])),
117
+ },
118
+ ];
119
+ })),
120
+ };
121
+ }
122
+ export class ResourceManager {
123
+ constructor({ wait = 5000, watch = true } = {}) {
124
+ if (watch) {
125
+ const reload = throttle(async () => {
126
+ logger.info('reload resource states');
127
+ await this.reload()
128
+ .then((resource) => {
129
+ logger.info('reload resource states success', {
130
+ projects: Object.values(resource.agents).reduce((res, i) => i.projects.length + res, 0),
131
+ knowledge: resource.knowledge.knowledgeList.length,
132
+ });
133
+ })
134
+ .catch((error) => {
135
+ logger.error('reload resource states error', { error });
136
+ });
137
+ }, wait, { leading: false, trailing: true });
138
+ config.events.on(config.Events.componentAdded, reload);
139
+ config.events.on(config.Events.componentRemoved, reload);
140
+ config.events.on(config.Events.componentStarted, reload);
141
+ config.events.on(config.Events.componentStopped, reload);
142
+ config.events.on(config.Events.componentUpdated, reload);
143
+ }
144
+ }
145
+ promise;
146
+ get resources() {
147
+ if (!this.promise) {
148
+ this.promise = loadResources();
149
+ }
150
+ return this.promise;
151
+ }
152
+ async reload() {
153
+ this.promise = loadResources();
154
+ return this.resources;
155
+ }
156
+ async getProjects({ blockletDid, type }) {
157
+ const resources = await this.resources;
158
+ const list = resources.agents[type]?.projects ?? [];
159
+ if (blockletDid) {
160
+ return list.filter((i) => i.blocklet.did === blockletDid);
161
+ }
162
+ return list;
163
+ }
164
+ async getProject({ blockletDid, projectId, type, }) {
165
+ const resources = await this.resources;
166
+ for (const t of type ? [type].flat() : ResourceTypes) {
167
+ const p = resources.agents[t]?.blockletMap[blockletDid]?.projectMap[projectId];
168
+ if (p)
169
+ return p;
170
+ }
171
+ return undefined;
172
+ }
173
+ async getAgent({ blockletDid, projectId, agentId, type = ResourceTypes, }) {
174
+ const resources = await this.resources;
175
+ for (const t of [type].flat()) {
176
+ const blocklet = resources.agents[t]?.blockletMap[blockletDid];
177
+ const project = blocklet?.projectMap[projectId];
178
+ const agent = project?.agentMap[agentId];
179
+ if (agent)
180
+ return { agent, project: project.project, blocklet: { did: blockletDid } };
181
+ }
182
+ return undefined;
183
+ }
184
+ async getKnowledgeList() {
185
+ const resources = await this.resources;
186
+ return resources.knowledge.knowledgeList;
187
+ }
188
+ async getKnowledge({ blockletDid, knowledgeId }) {
189
+ const resources = await this.resources;
190
+ return resources.knowledge.blockletMap[blockletDid]?.knowledgeMap[knowledgeId];
191
+ }
192
+ }
@@ -0,0 +1,6 @@
1
+ export const AIGNE_RUNTIME_COMPONENT_DID = 'z2qaBP9SahqU2L2YA3ip7NecwKACMByTFuiJ2';
2
+ export const AIGNE_COMPONENTS_COMPONENT_DID = 'z2qa6fvjmjew4pWJyTsKaWFuNoMUMyXDh5A1D';
3
+ export const AIGNE_RUNTIME_CUSTOM_COMPONENT_ID = 'grc9q1cveub6pnl8';
4
+ export const AIGNE_STUDIO_COMPONENT_DID = 'z8iZpog7mcgcgBZzTiXJCWESvmnRrQmnd3XBB';
5
+ export const NFT_BLENDER_COMPONENT_DID = 'z8ia1ieY5KhEC4LMRETzS5nUwD7PvAND8qkfX';
6
+ export const AIGNE_ISSUE_VC_PREFIX = 'AIGNE';
@@ -0,0 +1,6 @@
1
+ import { AgentExecutorBase } from './base';
2
+ export class AgentExecutor extends AgentExecutorBase {
3
+ async process() {
4
+ // ignore
5
+ }
6
+ }
@@ -0,0 +1,24 @@
1
+ import { AgentExecutorBase } from './base';
2
+ export class AIGCAgentExecutor extends AgentExecutorBase {
3
+ async process() {
4
+ const { agent } = this;
5
+ if (!agent.prompt?.length)
6
+ throw new Error('Prompt cannot be empty');
7
+ const prompt = await this.renderMessage(agent.prompt
8
+ .split('\n')
9
+ .filter((i) => !i.startsWith('//'))
10
+ .join('\n'));
11
+ const { data } = await this.context.callAIImage({
12
+ assistant: agent,
13
+ input: {
14
+ prompt,
15
+ n: agent.n,
16
+ model: agent.model,
17
+ quality: agent.quality,
18
+ size: agent.size,
19
+ style: agent.style,
20
+ },
21
+ });
22
+ return { $images: data };
23
+ }
24
+ }
@@ -0,0 +1,34 @@
1
+ import axios, { isAxiosError } from 'axios';
2
+ import Cookie from 'js-cookie';
3
+ import { pick } from 'lodash';
4
+ import { AgentExecutorBase } from './base';
5
+ export class APIAgentExecutor extends AgentExecutorBase {
6
+ async process({ inputs }) {
7
+ const { agent } = this;
8
+ if (!agent.requestUrl)
9
+ throw new Error(`Assistant ${agent.id}'s url is empty`);
10
+ const args = Object.fromEntries(await Promise.all((agent.parameters ?? [])
11
+ .filter((i) => !!i.key && !i.hidden)
12
+ .map(async (i) => [i.key, inputs?.[i.key] || i.defaultValue])));
13
+ const method = agent.requestMethod || 'GET';
14
+ const isGet = method === 'get';
15
+ try {
16
+ const response = await axios({
17
+ url: agent.requestUrl,
18
+ method,
19
+ params: isGet ? args : undefined,
20
+ data: isGet ? undefined : args,
21
+ headers: {
22
+ 'x-csrf-token': Cookie.get('x-csrf-token'),
23
+ },
24
+ });
25
+ return response.data;
26
+ }
27
+ catch (e) {
28
+ if (isAxiosError(e)) {
29
+ Object.assign(e, pick(e.response, 'status', 'statusText', 'data'));
30
+ }
31
+ throw e;
32
+ }
33
+ }
34
+ }