@aigne/core 0.0.2 → 0.0.4

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 (168) hide show
  1. package/lib/cjs/index.js +1 -1
  2. package/lib/cjs/types/index.js +2 -4
  3. package/lib/esm/index.js +1 -1
  4. package/lib/esm/types/index.js +2 -4
  5. package/lib/types/index.d.ts +1 -1
  6. package/lib/types/types/agent.d.ts +5 -0
  7. package/lib/types/types/index.d.ts +2 -4
  8. package/lib/types/types/runnable.d.ts +20 -0
  9. package/package.json +6 -7
  10. package/lib/cjs/assistant/generate-output.js +0 -101
  11. package/lib/cjs/assistant/select-agent.js +0 -76
  12. package/lib/cjs/assistant/type.js +0 -11
  13. package/lib/cjs/common/aid.js +0 -42
  14. package/lib/cjs/common/index.js +0 -238
  15. package/lib/cjs/common/resource-manager.js +0 -199
  16. package/lib/cjs/constants.js +0 -9
  17. package/lib/cjs/executor/agent.js +0 -10
  18. package/lib/cjs/executor/aigc.js +0 -28
  19. package/lib/cjs/executor/api.js +0 -64
  20. package/lib/cjs/executor/base.js +0 -676
  21. package/lib/cjs/executor/blocklet.js +0 -25
  22. package/lib/cjs/executor/call-agent.js +0 -105
  23. package/lib/cjs/executor/decision.js +0 -478
  24. package/lib/cjs/executor/image-blender.js +0 -32
  25. package/lib/cjs/executor/index.js +0 -81
  26. package/lib/cjs/executor/llm.js +0 -379
  27. package/lib/cjs/executor/logic.js +0 -167
  28. package/lib/cjs/libs/blocklet/vc.js +0 -92
  29. package/lib/cjs/libs/openapi/request/index.js +0 -24
  30. package/lib/cjs/libs/openapi/request/util.js +0 -146
  31. package/lib/cjs/libs/openapi/types/index.js +0 -17
  32. package/lib/cjs/libs/openapi/util/call.js +0 -15
  33. package/lib/cjs/libs/openapi/util/check-schema.js +0 -67
  34. package/lib/cjs/libs/openapi/util/convert-schema.js +0 -44
  35. package/lib/cjs/libs/openapi/util/flatten-open-api.js +0 -21
  36. package/lib/cjs/libs/openapi/util/get-open-api-i18n-text.js +0 -7
  37. package/lib/cjs/runtime/resource-blocklet.js +0 -5
  38. package/lib/cjs/runtime/runtime.js +0 -143
  39. package/lib/cjs/types/assistant/index.js +0 -31
  40. package/lib/cjs/types/assistant/mustache/ReadableMustache.js +0 -69
  41. package/lib/cjs/types/assistant/mustache/directive.js +0 -35
  42. package/lib/cjs/types/assistant/mustache/mustache.js +0 -688
  43. package/lib/cjs/types/resource/index.js +0 -47
  44. package/lib/cjs/types/resource/project.js +0 -35
  45. package/lib/cjs/types/runtime/error.js +0 -18
  46. package/lib/cjs/types/runtime/index.js +0 -37
  47. package/lib/cjs/types/runtime/runtime-resource-blocklet-state.js +0 -4
  48. package/lib/cjs/types/runtime/schema.js +0 -259
  49. package/lib/cjs/utils/cron-job.js +0 -48
  50. package/lib/cjs/utils/extract-metadata-transform.js +0 -58
  51. package/lib/cjs/utils/extract-metadata-transform.test.js +0 -61
  52. package/lib/cjs/utils/fs.js +0 -49
  53. package/lib/cjs/utils/get-blocklet-agent.js +0 -351
  54. package/lib/cjs/utils/geti.js +0 -37
  55. package/lib/cjs/utils/is-non-nullable.js +0 -20
  56. package/lib/cjs/utils/render-message.js +0 -23
  57. package/lib/cjs/utils/resolve-secret-inputs.js +0 -49
  58. package/lib/cjs/utils/retry.js +0 -19
  59. package/lib/cjs/utils/task-id.js +0 -7
  60. package/lib/cjs/utils/tool-calls-transform.js +0 -18
  61. package/lib/esm/assistant/generate-output.js +0 -91
  62. package/lib/esm/assistant/select-agent.js +0 -71
  63. package/lib/esm/assistant/type.js +0 -7
  64. package/lib/esm/common/aid.js +0 -38
  65. package/lib/esm/common/index.js +0 -232
  66. package/lib/esm/common/resource-manager.js +0 -192
  67. package/lib/esm/constants.js +0 -6
  68. package/lib/esm/executor/agent.js +0 -6
  69. package/lib/esm/executor/aigc.js +0 -24
  70. package/lib/esm/executor/api.js +0 -34
  71. package/lib/esm/executor/base.js +0 -668
  72. package/lib/esm/executor/blocklet.js +0 -21
  73. package/lib/esm/executor/call-agent.js +0 -98
  74. package/lib/esm/executor/decision.js +0 -471
  75. package/lib/esm/executor/image-blender.js +0 -25
  76. package/lib/esm/executor/index.js +0 -74
  77. package/lib/esm/executor/llm.js +0 -372
  78. package/lib/esm/executor/logic.js +0 -160
  79. package/lib/esm/libs/blocklet/vc.js +0 -85
  80. package/lib/esm/libs/openapi/request/index.js +0 -20
  81. package/lib/esm/libs/openapi/request/util.js +0 -136
  82. package/lib/esm/libs/openapi/types/index.js +0 -1
  83. package/lib/esm/libs/openapi/util/call.js +0 -8
  84. package/lib/esm/libs/openapi/util/check-schema.js +0 -62
  85. package/lib/esm/libs/openapi/util/convert-schema.js +0 -42
  86. package/lib/esm/libs/openapi/util/flatten-open-api.js +0 -19
  87. package/lib/esm/libs/openapi/util/get-open-api-i18n-text.js +0 -5
  88. package/lib/esm/runtime/resource-blocklet.js +0 -2
  89. package/lib/esm/runtime/runtime.js +0 -136
  90. package/lib/esm/types/assistant/index.js +0 -9
  91. package/lib/esm/types/assistant/mustache/ReadableMustache.js +0 -63
  92. package/lib/esm/types/assistant/mustache/directive.js +0 -29
  93. package/lib/esm/types/assistant/mustache/mustache.js +0 -686
  94. package/lib/esm/types/resource/index.js +0 -26
  95. package/lib/esm/types/resource/project.js +0 -29
  96. package/lib/esm/types/runtime/error.js +0 -14
  97. package/lib/esm/types/runtime/index.js +0 -20
  98. package/lib/esm/types/runtime/runtime-resource-blocklet-state.js +0 -1
  99. package/lib/esm/types/runtime/schema.js +0 -249
  100. package/lib/esm/utils/cron-job.js +0 -44
  101. package/lib/esm/utils/extract-metadata-transform.js +0 -54
  102. package/lib/esm/utils/extract-metadata-transform.test.js +0 -59
  103. package/lib/esm/utils/fs.js +0 -41
  104. package/lib/esm/utils/get-blocklet-agent.js +0 -344
  105. package/lib/esm/utils/geti.js +0 -30
  106. package/lib/esm/utils/is-non-nullable.js +0 -13
  107. package/lib/esm/utils/render-message.js +0 -20
  108. package/lib/esm/utils/resolve-secret-inputs.js +0 -46
  109. package/lib/esm/utils/retry.js +0 -16
  110. package/lib/esm/utils/task-id.js +0 -3
  111. package/lib/esm/utils/tool-calls-transform.js +0 -15
  112. package/lib/types/assistant/generate-output.d.ts +0 -29
  113. package/lib/types/assistant/select-agent.d.ts +0 -14
  114. package/lib/types/assistant/type.d.ts +0 -61
  115. package/lib/types/common/aid.d.ts +0 -18
  116. package/lib/types/common/index.d.ts +0 -7
  117. package/lib/types/common/resource-manager.d.ts +0 -88
  118. package/lib/types/constants.d.ts +0 -6
  119. package/lib/types/executor/agent.d.ts +0 -5
  120. package/lib/types/executor/aigc.d.ts +0 -9
  121. package/lib/types/executor/api.d.ts +0 -9
  122. package/lib/types/executor/base.d.ts +0 -209
  123. package/lib/types/executor/blocklet.d.ts +0 -9
  124. package/lib/types/executor/call-agent.d.ts +0 -12
  125. package/lib/types/executor/decision.d.ts +0 -20
  126. package/lib/types/executor/image-blender.d.ts +0 -9
  127. package/lib/types/executor/index.d.ts +0 -8
  128. package/lib/types/executor/llm.d.ts +0 -38
  129. package/lib/types/executor/logic.d.ts +0 -9
  130. package/lib/types/libs/blocklet/vc.d.ts +0 -17
  131. package/lib/types/libs/openapi/request/index.d.ts +0 -17
  132. package/lib/types/libs/openapi/request/util.d.ts +0 -40
  133. package/lib/types/libs/openapi/types/index.d.ts +0 -20
  134. package/lib/types/libs/openapi/util/call.d.ts +0 -2
  135. package/lib/types/libs/openapi/util/check-schema.d.ts +0 -3
  136. package/lib/types/libs/openapi/util/convert-schema.d.ts +0 -8
  137. package/lib/types/libs/openapi/util/flatten-open-api.d.ts +0 -3
  138. package/lib/types/libs/openapi/util/get-open-api-i18n-text.d.ts +0 -2
  139. package/lib/types/runtime/resource-blocklet.d.ts +0 -2
  140. package/lib/types/runtime/runtime.d.ts +0 -20
  141. package/lib/types/types/assistant/index.d.ts +0 -405
  142. package/lib/types/types/assistant/mustache/ReadableMustache.d.ts +0 -2
  143. package/lib/types/types/assistant/mustache/directive.d.ts +0 -6
  144. package/lib/types/types/assistant/mustache/mustache.d.ts +0 -2
  145. package/lib/types/types/common/index.d.ts +0 -45
  146. package/lib/types/types/resource/index.d.ts +0 -17
  147. package/lib/types/types/resource/project.d.ts +0 -41
  148. package/lib/types/types/runtime/agent.d.ts +0 -33
  149. package/lib/types/types/runtime/error.d.ts +0 -10
  150. package/lib/types/types/runtime/index.d.ts +0 -116
  151. package/lib/types/types/runtime/runtime-resource-blocklet-state.d.ts +0 -5
  152. package/lib/types/types/runtime/schema.d.ts +0 -110
  153. package/lib/types/utils/cron-job.d.ts +0 -22
  154. package/lib/types/utils/extract-metadata-transform.d.ts +0 -16
  155. package/lib/types/utils/extract-metadata-transform.test.d.ts +0 -1
  156. package/lib/types/utils/fs.d.ts +0 -9
  157. package/lib/types/utils/get-blocklet-agent.d.ts +0 -219
  158. package/lib/types/utils/geti.d.ts +0 -1
  159. package/lib/types/utils/is-non-nullable.d.ts +0 -2
  160. package/lib/types/utils/render-message.d.ts +0 -6
  161. package/lib/types/utils/resolve-secret-inputs.d.ts +0 -11
  162. package/lib/types/utils/retry.d.ts +0 -1
  163. package/lib/types/utils/task-id.d.ts +0 -1
  164. package/lib/types/utils/tool-calls-transform.d.ts +0 -2
  165. /package/lib/cjs/types/{runtime/agent.js → agent.js} +0 -0
  166. /package/lib/cjs/types/{common/index.js → runnable.js} +0 -0
  167. /package/lib/esm/types/{runtime/agent.js → agent.js} +0 -0
  168. /package/lib/esm/types/{common/index.js → runnable.js} +0 -0
@@ -1,676 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AgentExecutorBase = exports.ExecutorContext = void 0;
7
- const crypto_1 = require("crypto");
8
- const quickjs_1 = require("@blocklet/quickjs");
9
- const component_1 = require("@blocklet/sdk/lib/component");
10
- const config_1 = __importDefault(require("@blocklet/sdk/lib/config"));
11
- const joi_1 = __importDefault(require("joi"));
12
- const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
13
- const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
14
- const isNil_1 = __importDefault(require("lodash/isNil"));
15
- const pick_1 = __importDefault(require("lodash/pick"));
16
- const toLower_1 = __importDefault(require("lodash/toLower"));
17
- const aid_1 = require("../common/aid");
18
- const constants_1 = require("../constants");
19
- const vc_1 = require("../libs/blocklet/vc");
20
- const logger_1 = __importDefault(require("../logger"));
21
- const types_1 = require("../types");
22
- const get_blocklet_agent_1 = require("../utils/get-blocklet-agent");
23
- const is_non_nullable_1 = require("../utils/is-non-nullable");
24
- const render_message_1 = require("../utils/render-message");
25
- const task_id_1 = require("../utils/task-id");
26
- function isPlainObject(value) {
27
- return typeof value === 'object' && value !== null && !Array.isArray(value);
28
- }
29
- class ExecutorContext {
30
- constructor(options) {
31
- this.entry = options.entry;
32
- this.getAgent = (0, quickjs_1.memoize)(options.getAgent, {
33
- keyGenerator: (o) => [o.aid, o.working].filter(is_non_nullable_1.isNonNullable).join('/'),
34
- });
35
- this.callAI = options.callAI;
36
- this.callAIImage = options.callAIImage;
37
- this.callback = options.callback;
38
- this.getMemoryVariables = (0, quickjs_1.memoize)(options.getMemoryVariables, {
39
- keyGenerator: (o) => [o.blockletDid, o.projectId, o.projectRef, o.working].filter(is_non_nullable_1.isNonNullable).join('/'),
40
- });
41
- this.user = options.user;
42
- this.sessionId = options.sessionId;
43
- this.messageId = options.messageId;
44
- this.clientTime = options.clientTime;
45
- this.executor = options.executor;
46
- this.entryProjectId = options.entryProjectId;
47
- this.queryCache = options.queryCache;
48
- this.setCache = options.setCache;
49
- }
50
- entry;
51
- getAgent;
52
- callAI;
53
- callAIImage;
54
- queryCache;
55
- setCache;
56
- callback;
57
- sessionId;
58
- messageId;
59
- clientTime;
60
- promise;
61
- entryProjectId;
62
- user;
63
- getMemoryVariables;
64
- maxRetries = 5;
65
- executor;
66
- async execute(agent, options) {
67
- return this.executor(agent, options).execute();
68
- }
69
- copy(options) {
70
- return new ExecutorContext({ ...this, ...options });
71
- }
72
- async getBlockletAgent(agentId) {
73
- this.promise ??= (0, get_blocklet_agent_1.getBlockletAgent)();
74
- const { openApis, agentsMap } = await this.promise;
75
- return { agent: agentsMap[agentId], openApis };
76
- }
77
- }
78
- exports.ExecutorContext = ExecutorContext;
79
- class AgentExecutorBase {
80
- context;
81
- agent;
82
- options;
83
- constructor(context, agent, options) {
84
- this.context = context;
85
- this.agent = agent;
86
- this.options = options;
87
- }
88
- async execute() {
89
- const { agent, options } = this;
90
- this.context.callback?.({
91
- type: types_1.AssistantResponseType.INPUT,
92
- assistantId: agent.id,
93
- taskId: options.taskId,
94
- parentTaskId: options.parentTaskId,
95
- assistantName: agent.name,
96
- inputParameters: this.hideSecretInputs(options.inputs || {}, agent),
97
- });
98
- this.finalInputs = await this.prepareInputs();
99
- const partial = await this.validateOutputs({ inputs: this.finalInputs, partial: true });
100
- if (!(0, isEmpty_1.default)(partial)) {
101
- this.context.callback?.({
102
- type: types_1.AssistantResponseType.CHUNK,
103
- taskId: options.taskId,
104
- assistantId: agent.id,
105
- delta: { object: this.hideSecretInputs(partial, agent) },
106
- });
107
- }
108
- this.context.callback?.({
109
- type: types_1.AssistantResponseType.EXECUTE,
110
- taskId: options.taskId,
111
- parentTaskId: options.parentTaskId,
112
- assistantId: agent.id,
113
- assistantName: agent.name,
114
- execution: { currentPhase: types_1.ExecutionPhase.EXECUTE_ASSISTANT_RUNNING },
115
- });
116
- this.context.callback?.({
117
- type: types_1.AssistantResponseType.INPUT,
118
- assistantId: agent.id,
119
- taskId: options.taskId,
120
- parentTaskId: options.parentTaskId,
121
- assistantName: agent.name,
122
- inputParameters: this.hideSecretInputs(this.finalInputs, agent),
123
- });
124
- let result;
125
- // query cache if the agent has cache enabled
126
- const cacheKey = this.globalContext.$cache.key;
127
- if (agent.cache?.enable && agent.identity) {
128
- try {
129
- const cache = await this.context.queryCache({ aid: agent.identity.aid, cacheKey });
130
- if (cache) {
131
- result = await this.validateOutputs({ inputs: this.finalInputs, outputs: cache.outputs });
132
- if ((0, isEmpty_1.default)(result))
133
- result = undefined;
134
- }
135
- }
136
- catch (error) {
137
- logger_1.default.error('query and validate cache error', { error });
138
- }
139
- if (typeof result?.$text === 'string') {
140
- this.context.callback?.({
141
- type: types_1.AssistantResponseType.CHUNK,
142
- taskId: options.taskId,
143
- assistantId: agent.id,
144
- delta: { content: result.$text },
145
- });
146
- }
147
- }
148
- if (result === undefined) {
149
- const outputs = await this.process({ inputs: this.finalInputs });
150
- result = await this.validateOutputs({ inputs: this.finalInputs, outputs, processCallAgentOutputs: true });
151
- // set cache if needed
152
- if (!(0, isEmpty_1.default)(result) && agent.cache?.enable && agent.identity) {
153
- await this.context.setCache({ aid: agent.identity.aid, cacheKey, inputs: this.finalInputs, outputs: result });
154
- }
155
- }
156
- await this.postProcessOutputs(agent, { outputs: result });
157
- this.context.callback?.({
158
- type: types_1.AssistantResponseType.CHUNK,
159
- taskId: options.taskId,
160
- assistantId: agent.id,
161
- delta: { object: result },
162
- });
163
- this.context.callback?.({
164
- type: types_1.AssistantResponseType.EXECUTE,
165
- taskId: options.taskId,
166
- parentTaskId: options.parentTaskId,
167
- assistantId: agent.id,
168
- assistantName: agent.name,
169
- execution: { currentPhase: types_1.ExecutionPhase.EXECUTE_ASSISTANT_END },
170
- });
171
- return result;
172
- }
173
- _finalInputs;
174
- get finalInputs() {
175
- if (!this._finalInputs)
176
- throw new Error('Final inputs is not ready');
177
- return this._finalInputs;
178
- }
179
- set finalInputs(value) {
180
- this._finalInputs = value;
181
- }
182
- cacheKey({ userRelated, onlyUserInputs } = {}) {
183
- // TODO: support custom cache key by specifying inputs of agent
184
- const i = Object.fromEntries((this.agent.parameters ?? [])
185
- .filter((i) => !!i.key && !i.hidden && (onlyUserInputs ? (0, types_1.isUserInputParameter)(i) : true))
186
- .map((i) => [i.key, this.finalInputs[i.key]]));
187
- return (0, crypto_1.hash)('md5', (0, json_stable_stringify_1.default)({ ...i, '$sys.user.did': userRelated ? this.globalContext.$sys.user?.did : undefined }), 'hex');
188
- }
189
- get globalContext() {
190
- const executor = this;
191
- const { agent } = this;
192
- return {
193
- $sys: {
194
- sessionId: this.context.sessionId,
195
- messageId: this.context.messageId,
196
- clientTime: this.context.clientTime,
197
- user: this.context.user,
198
- env: (0, pick_1.default)(config_1.default.env, 'appId', 'appName', 'appDescription', 'appUrl'),
199
- },
200
- $storage: {
201
- async getItem(key, { scope = 'global', onlyOne } = {}) {
202
- return executor.getMemory({ key, agentId: agent.id, scope, onlyOne });
203
- },
204
- async setItem(key, value, { scope = 'global', onlyOne } = {}) {
205
- return executor.setMemory({ key, data: value, agentId: agent.id, scope, reset: onlyOne });
206
- },
207
- },
208
- $cache: {
209
- get key() {
210
- return executor.cacheKey({ onlyUserInputs: true });
211
- },
212
- async getItem(key, { agentId } = {}) {
213
- if (agent.type === 'blocklet')
214
- throw new Error('Unsupported calling query cache in blocklet agent');
215
- const identity = (0, aid_1.parseIdentity)(agent.identity.aid, { rejectWhenError: true });
216
- return executor.context.queryCache({
217
- aid: (0, aid_1.stringifyIdentity)({ ...identity, agentId: agentId || identity.agentId }),
218
- cacheKey: key,
219
- });
220
- },
221
- },
222
- $blocklet: {
223
- issueVC: (args) => {
224
- const userDid = executor.context.user?.did;
225
- if (!userDid)
226
- throw new Error('Issue VC requires user did');
227
- return (0, vc_1.issueVC)({
228
- ...args,
229
- userDid,
230
- context: this.context,
231
- });
232
- },
233
- },
234
- };
235
- }
236
- async prepareInputs() {
237
- const { agent, options: { inputs, taskId, variables }, } = this;
238
- const inputParameters = Object.fromEntries(await Promise.all((agent.parameters || [])
239
- .filter((i) => !!i.key && i.type !== 'source' && !i.hidden)
240
- .map(async (i) => {
241
- const inputValue = inputs?.[i.key];
242
- if (typeof inputValue === 'string') {
243
- const template = String(inputValue || '').trim();
244
- return [
245
- i.key,
246
- template ? await this.renderMessage(template, variables, { stringify: false }) : inputValue,
247
- ];
248
- }
249
- if (isPlainObject(inputValue)) {
250
- const resolvedEntries = await Promise.all(Object.entries(inputValue).map(async ([key, value]) => {
251
- return [
252
- key,
253
- typeof value === 'string'
254
- ? await this.renderMessage(value, variables, { stringify: false })
255
- : value,
256
- ];
257
- }));
258
- return [i.key, Object.fromEntries(resolvedEntries)];
259
- }
260
- if (Array.isArray(inputValue) && inputValue.length) {
261
- const resolvedArray = await Promise.all(inputValue.map(async (item) => {
262
- if (isPlainObject(item)) {
263
- return Object.fromEntries(await Promise.all(Object.entries(item).map(async ([key, value]) => [
264
- key,
265
- typeof value === 'string'
266
- ? await this.renderMessage(value, variables, { stringify: false })
267
- : value,
268
- ])));
269
- }
270
- return await this.renderMessage(item, variables, { stringify: false });
271
- }));
272
- return [i.key, resolvedArray];
273
- }
274
- return [i.key, variables?.[i.key] || inputs?.[i.key]];
275
- }) ?? []));
276
- const inputVariables = { ...(inputs || {}), ...inputParameters };
277
- const partial = await this.validateOutputs({ inputs: inputVariables, partial: true });
278
- if (!(0, isEmpty_1.default)(partial)) {
279
- this.context.callback?.({
280
- type: types_1.AssistantResponseType.CHUNK,
281
- taskId,
282
- assistantId: agent.id,
283
- delta: { object: partial },
284
- });
285
- }
286
- const { callback } = this.context;
287
- const cb = (taskId) => (args) => {
288
- if (args.type === types_1.AssistantResponseType.CHUNK && args.taskId === taskId) {
289
- callback({ ...args });
290
- return;
291
- }
292
- callback(args);
293
- };
294
- const parameters = (agent.parameters || []).filter((i) => !i.hidden);
295
- for (const parameter of parameters) {
296
- if (!parameter.key)
297
- continue;
298
- if (parameter.type === 'source') {
299
- if (!agent.project) {
300
- throw new Error('Agent project not found.');
301
- }
302
- if (parameter.source?.variableFrom === 'secret') {
303
- const secret = inputs?.[parameter.key] || config_1.default.env[(parameter.key || '').toLocaleUpperCase()];
304
- if (!secret)
305
- throw new Error(`Missing required agent secret ${parameter.key}`);
306
- inputVariables[parameter.key] = secret;
307
- }
308
- else if (parameter.source?.variableFrom === 'tool' && parameter.source.agent) {
309
- const currentTaskId = (0, task_id_1.nextId)();
310
- const { agent: tool } = parameter.source;
311
- const identity = (0, aid_1.parseIdentity)(agent.identity.aid, { rejectWhenError: true });
312
- const toolAgent = await this.context.getAgent({
313
- aid: (0, aid_1.stringifyIdentity)({
314
- blockletDid: tool.blockletDid || identity.blockletDid,
315
- projectId: tool.projectId || identity.projectId,
316
- projectRef: identity.projectRef,
317
- agentId: tool.id,
318
- }),
319
- working: agent.identity.working,
320
- });
321
- if (!toolAgent)
322
- continue;
323
- const result = await this.context
324
- .executor(toolAgent, {
325
- inputs: tool.parameters,
326
- variables: { ...inputParameters, ...inputVariables },
327
- taskId: currentTaskId,
328
- parentTaskId: taskId,
329
- })
330
- .execute();
331
- inputVariables[parameter.key] = result ?? parameter.defaultValue;
332
- }
333
- else if (parameter.source?.variableFrom === 'datastore') {
334
- const currentTaskId = (0, task_id_1.nextId)();
335
- const key = (0, toLower_1.default)(parameter.source.variable?.key) || (0, toLower_1.default)(parameter.key);
336
- const scope = parameter.source.variable?.scope || 'session';
337
- const blocklet = await this.context.getBlockletAgent(get_blocklet_agent_1.MEMORY_API_ID);
338
- if (!blocklet.agent) {
339
- throw new Error('Blocklet agent api not found.');
340
- }
341
- const data = await this.context
342
- .executor(blocklet.agent, {
343
- inputs: {
344
- projectId: this.context.entryProjectId,
345
- sessionId: this.context.sessionId,
346
- scope,
347
- key,
348
- },
349
- taskId: currentTaskId,
350
- parentTaskId: taskId,
351
- })
352
- .execute();
353
- const m = await this.context.getMemoryVariables({
354
- ...(0, aid_1.parseIdentity)(agent.identity.aid, { rejectWhenError: true }),
355
- working: agent.identity.working,
356
- });
357
- const list = (data.datastores || []).map((x) => x?.data).filter((x) => x);
358
- const storageVariable = m.find((x) => (0, toLower_1.default)(x.key || '') === (0, toLower_1.default)(key || '') && x.scope === scope);
359
- let result = list?.length > 0
360
- ? list
361
- : [
362
- storageVariable?.type?.type === 'number' && typeof storageVariable?.defaultValue === 'string'
363
- ? Number(storageVariable.defaultValue)
364
- : storageVariable?.defaultValue,
365
- ];
366
- if (storageVariable?.reset) {
367
- result = (result?.length > 1 ? result : result[0]) ?? '';
368
- }
369
- inputVariables[parameter.key] = result ?? parameter.defaultValue;
370
- }
371
- else if (parameter.source?.variableFrom === 'knowledge' && parameter.source.knowledge) {
372
- const currentTaskId = (0, task_id_1.nextId)();
373
- const tool = parameter.source.knowledge;
374
- const blockletDid = parameter.source.knowledge.blockletDid ||
375
- (0, aid_1.parseIdentity)(agent.identity.aid, { rejectWhenError: true }).blockletDid;
376
- const blocklet = await this.context.getBlockletAgent(get_blocklet_agent_1.KNOWLEDGE_API_ID);
377
- if (!blocklet.agent) {
378
- throw new Error('Blocklet agent api not found.');
379
- }
380
- const data = await this.context
381
- .copy({ callback: cb(currentTaskId) })
382
- .executor(blocklet.agent, {
383
- inputs: tool?.parameters,
384
- variables: { ...inputVariables, blockletDid, datasetId: tool.id, knowledgeId: tool.id },
385
- taskId: currentTaskId,
386
- parentTaskId: taskId,
387
- })
388
- .execute();
389
- inputVariables[parameter.key] = JSON.stringify(data?.docs || []) ?? parameter.defaultValue;
390
- }
391
- else if (parameter.source?.variableFrom === 'history' && parameter.source.chatHistory) {
392
- const currentTaskId = (0, task_id_1.nextId)();
393
- const chat = parameter.source.chatHistory;
394
- const blocklet = await this.context.getBlockletAgent(get_blocklet_agent_1.HISTORY_API_ID);
395
- if (!blocklet.agent) {
396
- throw new Error('Blocklet agent api not found.');
397
- }
398
- const result = await this.context
399
- .executor(blocklet.agent, {
400
- inputs: {
401
- sessionId: this.context.sessionId,
402
- limit: chat.limit || 50,
403
- keyword: await this.renderMessage(chat.keyword || '', inputVariables, { stringify: false }),
404
- },
405
- taskId: currentTaskId,
406
- parentTaskId: taskId,
407
- })
408
- .execute();
409
- const memories = Array.isArray(result?.messages)
410
- ? result.messages
411
- : [];
412
- const agentIds = new Set(memories.map((i) => i.agentId).filter((i) => !!i));
413
- const identity = (0, aid_1.parseIdentity)(agent.identity.aid, { rejectWhenError: true });
414
- const assistantNameMap = Object.fromEntries((await Promise.all([...agentIds].map((agentId) => this.context
415
- .getAgent({ aid: (0, aid_1.stringifyIdentity)({ ...identity, agentId }), working: agent.identity.working })
416
- .catch((error) => {
417
- logger_1.default.error('get assistant in conversation history error', { error });
418
- return null;
419
- }))))
420
- .filter(is_non_nullable_1.isNonNullable)
421
- .map((i) => [
422
- i.id,
423
- i.outputVariables?.find((j) => j.name === types_1.RuntimeOutputVariable.profile)
424
- ?.initialValue?.name ||
425
- i.name ||
426
- i.id,
427
- ]));
428
- inputVariables[parameter.key] = memories.map((i) => ({
429
- ...i,
430
- name: i.agentId && assistantNameMap[i.agentId],
431
- }));
432
- }
433
- else if (parameter.source?.variableFrom === 'blockletAPI' && parameter.source.api) {
434
- const currentTaskId = (0, task_id_1.nextId)();
435
- const blocklet = await this.context.getBlockletAgent(parameter.source.api.id);
436
- if (!blocklet.agent) {
437
- throw new Error('Blocklet agent api not found.');
438
- }
439
- const result = await this.context
440
- .copy({ callback: cb?.(currentTaskId) })
441
- .executor(blocklet.agent, {
442
- inputs: parameter.source.api.parameters,
443
- variables: inputVariables,
444
- taskId: currentTaskId,
445
- parentTaskId: taskId,
446
- })
447
- .execute();
448
- inputVariables[parameter.key] = result;
449
- }
450
- }
451
- else if (['llmInputMessages', 'llmInputTools', 'llmInputToolChoice', 'llmInputResponseFormat'].includes(parameter.type)) {
452
- const v = inputs?.[parameter.key];
453
- const tryParse = (s) => {
454
- try {
455
- return JSON.parse(s);
456
- }
457
- catch {
458
- // ignore
459
- }
460
- return undefined;
461
- };
462
- const schema = {
463
- llmInputMessages: joi_1.default.array().items(joi_1.default.object({
464
- role: joi_1.default.string().valid('system', 'user', 'assistant').empty([null, '']).default('user'),
465
- content: joi_1.default.string().required(),
466
- name: joi_1.default.string().empty([null, '']),
467
- })),
468
- llmInputTools: joi_1.default.array()
469
- .items(joi_1.default.object({
470
- type: joi_1.default.string().valid('function').required(),
471
- function: joi_1.default.object({
472
- name: joi_1.default.string().required(),
473
- description: joi_1.default.string().empty([null, '']),
474
- parameters: joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.any()).required(),
475
- }).required(),
476
- }))
477
- .empty(joi_1.default.array().length(0)),
478
- llmInputToolChoice: joi_1.default.alternatives()
479
- .try(joi_1.default.string().valid('auto', 'none', 'required'), joi_1.default.object({
480
- type: joi_1.default.string().valid('function').required(),
481
- function: joi_1.default.object({
482
- name: joi_1.default.string().required(),
483
- description: joi_1.default.string(),
484
- }).required(),
485
- }))
486
- .empty([null, ''])
487
- .optional(),
488
- llmInputResponseFormat: joi_1.default.object({
489
- type: joi_1.default.string().valid('text', 'json_object', 'json_schema').empty([null, '']),
490
- }).when(joi_1.default.object({ type: joi_1.default.valid('json_schema') }), {
491
- then: joi_1.default.object({
492
- jsonSchema: joi_1.default.object({
493
- name: joi_1.default.string().required(),
494
- description: joi_1.default.string().empty([null, '']),
495
- schema: joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.any()).required(),
496
- strict: joi_1.default.boolean().empty([null, '']),
497
- }),
498
- }),
499
- }),
500
- }[parameter.type];
501
- const val = parameter.type === 'llmInputMessages'
502
- ? await schema.validateAsync((Array.isArray(v) ? v : tryParse(v)) ?? [
503
- { role: 'user', content: typeof v === 'string' ? v : JSON.stringify(v) },
504
- ], { stripUnknown: true })
505
- : parameter.type === 'llmInputTools'
506
- ? await schema.validateAsync(Array.isArray(v) ? v : tryParse(v), { stripUnknown: true })
507
- : await schema.validateAsync(tryParse(v) || v, { stripUnknown: true });
508
- inputVariables[parameter.key] = val;
509
- }
510
- else if (parameter.type === 'boolean') {
511
- const val = inputVariables[parameter.key];
512
- inputVariables[parameter.key] = Boolean((0, isNil_1.default)(val) ? parameter.defaultValue : val);
513
- }
514
- else if (parameter.type === 'number') {
515
- const val = inputVariables[parameter.key];
516
- const parsedValue = val && typeof val === 'number' ? val : (Number(val) ?? parameter.defaultValue ?? null);
517
- inputVariables[parameter.key] = Number.isNaN(parsedValue) ? (parameter.defaultValue ?? null) : parsedValue;
518
- }
519
- else {
520
- const val = inputVariables[parameter.key];
521
- if (!(0, isNil_1.default)(val))
522
- inputVariables[parameter.key] = val || null;
523
- }
524
- }
525
- return inputVariables;
526
- }
527
- renderMessage = async (template, variables, options) => {
528
- return (0, render_message_1.renderMessage)(template, { ...this._finalInputs, ...variables, ...this.globalContext }, options);
529
- };
530
- async validateOutputs({ inputs, outputs, partial, processCallAgentOutputs, }) {
531
- const { agent } = this;
532
- const joiSchema = (0, types_1.outputVariablesToJoiSchema)(agent, {
533
- partial,
534
- variables: agent.identity
535
- ? await this.context.getMemoryVariables({
536
- ...(0, aid_1.parseIdentity)(agent.identity.aid, { rejectWhenError: true }),
537
- working: agent.identity.working,
538
- })
539
- : [],
540
- });
541
- const outputVariables = (agent.outputVariables ?? []).filter((i) => !i.hidden);
542
- const outputInputs = outputVariables.reduce((res, output) => {
543
- let input;
544
- if (output.from?.type === 'input') {
545
- const fromId = output.from.id;
546
- input = agent.parameters?.find((input) => input.id === fromId && !input.hidden);
547
- }
548
- if (input?.key && output.name) {
549
- const val = inputs?.[input.key];
550
- if (!(0, isNil_1.default)(val))
551
- return { ...res, [output.name]: val };
552
- }
553
- return res;
554
- }, {});
555
- const result = await joiSchema.validateAsync({ ...outputs, ...outputInputs }, { stripUnknown: true });
556
- if (processCallAgentOutputs && this.agent.outputVariables) {
557
- const callAgentOutputs = this.agent.outputVariables.filter((i) => i.from?.type === 'callAgent' && !!i.from.callAgent?.agentId && !!i.name);
558
- const templateOutputs = this.agent.outputVariables.filter((i) => !!i.valueTemplate?.trim() && !!i.name);
559
- const isOutputActive = async (output) => {
560
- if (!output.activeWhen?.trim())
561
- return true;
562
- return joi_1.default.boolean().validate(await this.renderMessage(output.activeWhen, { ...outputs, ...result }, { stringify: false })).value;
563
- };
564
- const v = Object.fromEntries((await Promise.all(callAgentOutputs.map(async (i) => {
565
- if (!(await isOutputActive(i)))
566
- return null;
567
- return [
568
- i.name,
569
- await (async () => {
570
- if (!this.agent.identity)
571
- throw new Error('Agent identity not found');
572
- const identity = (0, aid_1.parseIdentity)(this.agent.identity.aid, { rejectWhenError: true });
573
- const toolAgent = await this.context.getAgent({
574
- aid: (0, aid_1.stringifyIdentity)({
575
- blockletDid: i.from.callAgent.blockletDid || identity.blockletDid,
576
- projectId: i.from.callAgent.projectId || identity.projectId,
577
- projectRef: identity.projectRef,
578
- agentId: i.from.callAgent.agentId,
579
- }),
580
- working: this.agent.identity.working,
581
- });
582
- if (!toolAgent)
583
- throw new Error('Tool agent not found');
584
- const currentTaskId = (0, task_id_1.nextId)();
585
- return await this.context
586
- .executor(toolAgent, {
587
- inputs: i.from.callAgent.inputs,
588
- variables: { ...inputs, ...outputs },
589
- taskId: currentTaskId,
590
- parentTaskId: this.options.taskId,
591
- })
592
- .execute();
593
- })(),
594
- ];
595
- }))).filter(is_non_nullable_1.isNonNullable));
596
- Object.assign(result, v);
597
- const v1 = Object.fromEntries((await Promise.all(templateOutputs.map(async (i) => {
598
- if (!(await isOutputActive(i)))
599
- return null;
600
- return [i.name, await this.renderMessage(i.valueTemplate, { ...outputs, ...v }, { stringify: false })];
601
- }))).filter(is_non_nullable_1.isNonNullable));
602
- Object.assign(result, v1);
603
- }
604
- return result;
605
- }
606
- async postProcessOutputs(agent, { outputs }) {
607
- const memoryVariables = agent.identity
608
- ? await this.context.getMemoryVariables({
609
- ...(0, aid_1.parseIdentity)(agent.identity.aid, { rejectWhenError: true }),
610
- working: agent.identity.working,
611
- })
612
- : [];
613
- const outputVariables = (agent.outputVariables ?? []).filter((i) => !i.hidden);
614
- for (const output of outputVariables) {
615
- if (!output?.variable?.key || !output?.name)
616
- continue;
617
- const value = outputs[output.name];
618
- if ((0, isNil_1.default)(value))
619
- continue;
620
- const variable = memoryVariables.find((x) => (0, toLower_1.default)(x.key || '') === (0, toLower_1.default)(output.variable?.key || '') && x.scope === output.variable?.scope);
621
- await this.setMemory({
622
- key: (0, toLower_1.default)(output.variable.key),
623
- data: value,
624
- scope: output.variable.scope,
625
- agentId: agent.id,
626
- reset: variable?.reset,
627
- });
628
- }
629
- }
630
- async setMemory({ key, data, scope, agentId, reset, }) {
631
- const res = await (0, component_1.call)({
632
- name: constants_1.AIGNE_RUNTIME_COMPONENT_DID,
633
- path: '/api/memories',
634
- method: 'POST',
635
- params: {
636
- userId: this.context.user?.did,
637
- projectId: this.context.entryProjectId,
638
- agentId,
639
- sessionId: this.context.sessionId,
640
- reset,
641
- },
642
- data: { key, data, scope },
643
- });
644
- return res.data;
645
- }
646
- async getMemory({ key, scope, onlyOne }) {
647
- const res = await (0, component_1.call)({
648
- name: constants_1.AIGNE_RUNTIME_COMPONENT_DID,
649
- path: '/api/memories/variable-by-query',
650
- method: 'GET',
651
- params: {
652
- userId: this.context.user?.did,
653
- projectId: this.context.entryProjectId,
654
- sessionId: this.context.sessionId,
655
- key,
656
- scope,
657
- },
658
- });
659
- const list = res.data?.datastores;
660
- if (!Array.isArray(list) || !list.length)
661
- return null;
662
- return onlyOne ? list.at(-1).data : list.map((i) => i.data);
663
- }
664
- hideSecretInputs(partial, agent) {
665
- const authInputs = (agent.parameters || []).filter((i) => i.key && i.type === 'source' && i.source?.variableFrom === 'secret' && !i.hidden);
666
- const secretInputs = authInputs.reduce((res, i) => {
667
- res[i.key] = '******';
668
- return res;
669
- }, {});
670
- return {
671
- ...(partial || {}),
672
- ...secretInputs,
673
- };
674
- }
675
- }
676
- exports.AgentExecutorBase = AgentExecutorBase;