@aigne/core 1.0.17 → 1.1.0-beta.2

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 (252) hide show
  1. package/lib/cjs/agents/agent.d.ts +55 -0
  2. package/lib/cjs/agents/agent.js +91 -0
  3. package/lib/cjs/agents/ai-agent.d.ts +20 -0
  4. package/lib/cjs/agents/ai-agent.js +86 -0
  5. package/lib/cjs/agents/mcp-agent.d.ts +27 -0
  6. package/lib/cjs/agents/mcp-agent.js +95 -0
  7. package/lib/cjs/agents/types.d.ts +9 -0
  8. package/lib/cjs/agents/types.js +16 -0
  9. package/lib/cjs/execution-engine/context.d.ts +10 -0
  10. package/lib/cjs/execution-engine/index.d.ts +45 -0
  11. package/lib/cjs/execution-engine/index.js +190 -0
  12. package/lib/cjs/execution-engine/message-queue.d.ts +5 -0
  13. package/lib/cjs/execution-engine/message-queue.js +9 -0
  14. package/lib/cjs/index.d.ts +10 -21
  15. package/lib/cjs/index.js +10 -21
  16. package/lib/cjs/models/chat-openai.d.ts +14 -0
  17. package/lib/cjs/{llm-models/openai-llm-model.js → models/chat-openai.js} +62 -27
  18. package/lib/cjs/models/chat.d.ts +78 -0
  19. package/lib/cjs/models/chat.js +91 -0
  20. package/lib/cjs/prompt/prompt-builder.d.ts +34 -0
  21. package/lib/cjs/prompt/prompt-builder.js +140 -0
  22. package/lib/cjs/prompt/template.d.ts +70 -0
  23. package/lib/cjs/prompt/template.js +172 -0
  24. package/lib/cjs/utils/logger.d.ts +6 -3
  25. package/lib/cjs/utils/logger.js +9 -14
  26. package/lib/cjs/utils/type-utils.d.ts +5 -1
  27. package/lib/cjs/utils/type-utils.js +23 -0
  28. package/lib/dts/agents/agent.d.ts +55 -0
  29. package/lib/dts/agents/ai-agent.d.ts +20 -0
  30. package/lib/dts/agents/mcp-agent.d.ts +27 -0
  31. package/lib/dts/agents/types.d.ts +9 -0
  32. package/lib/dts/execution-engine/context.d.ts +10 -0
  33. package/lib/dts/execution-engine/index.d.ts +45 -0
  34. package/lib/dts/execution-engine/message-queue.d.ts +5 -0
  35. package/lib/dts/index.d.ts +10 -21
  36. package/lib/dts/models/chat-openai.d.ts +14 -0
  37. package/lib/dts/models/chat.d.ts +78 -0
  38. package/lib/dts/prompt/prompt-builder.d.ts +34 -0
  39. package/lib/dts/prompt/template.d.ts +70 -0
  40. package/lib/dts/utils/logger.d.ts +6 -3
  41. package/lib/dts/utils/type-utils.d.ts +5 -1
  42. package/lib/esm/agents/agent.d.ts +55 -0
  43. package/lib/esm/agents/agent.js +83 -0
  44. package/lib/esm/agents/ai-agent.d.ts +20 -0
  45. package/lib/esm/agents/ai-agent.js +82 -0
  46. package/lib/esm/agents/mcp-agent.d.ts +27 -0
  47. package/lib/esm/agents/mcp-agent.js +90 -0
  48. package/lib/esm/agents/types.d.ts +9 -0
  49. package/lib/esm/agents/types.js +11 -0
  50. package/lib/esm/execution-engine/context.d.ts +10 -0
  51. package/lib/esm/execution-engine/index.d.ts +45 -0
  52. package/lib/esm/execution-engine/index.js +182 -0
  53. package/lib/esm/execution-engine/message-queue.d.ts +5 -0
  54. package/lib/esm/execution-engine/message-queue.js +5 -0
  55. package/lib/esm/index.d.ts +10 -21
  56. package/lib/esm/index.js +10 -21
  57. package/lib/esm/models/chat-openai.d.ts +14 -0
  58. package/lib/esm/{llm-models/openai-llm-model.js → models/chat-openai.js} +59 -24
  59. package/lib/esm/models/chat.d.ts +78 -0
  60. package/lib/esm/models/chat.js +87 -0
  61. package/lib/esm/prompt/prompt-builder.d.ts +34 -0
  62. package/lib/esm/prompt/prompt-builder.js +131 -0
  63. package/lib/esm/prompt/template.d.ts +70 -0
  64. package/lib/esm/prompt/template.js +158 -0
  65. package/lib/esm/utils/logger.d.ts +6 -3
  66. package/lib/esm/utils/logger.js +6 -14
  67. package/lib/esm/utils/type-utils.d.ts +5 -1
  68. package/lib/esm/utils/type-utils.js +17 -1
  69. package/package.json +18 -14
  70. package/lib/cjs/agent.d.ts +0 -96
  71. package/lib/cjs/agent.js +0 -165
  72. package/lib/cjs/constants.d.ts +0 -7
  73. package/lib/cjs/constants.js +0 -10
  74. package/lib/cjs/context.d.ts +0 -23
  75. package/lib/cjs/definitions/data-schema.d.ts +0 -61
  76. package/lib/cjs/definitions/data-schema.js +0 -47
  77. package/lib/cjs/definitions/data-type.d.ts +0 -32
  78. package/lib/cjs/definitions/data-type.js +0 -2
  79. package/lib/cjs/definitions/memory.d.ts +0 -53
  80. package/lib/cjs/definitions/memory.js +0 -23
  81. package/lib/cjs/definitions/open-api.d.ts +0 -36
  82. package/lib/cjs/definitions/open-api.js +0 -2
  83. package/lib/cjs/definitions/preload.d.ts +0 -43
  84. package/lib/cjs/definitions/preload.js +0 -34
  85. package/lib/cjs/function-agent.d.ts +0 -23
  86. package/lib/cjs/function-agent.js +0 -62
  87. package/lib/cjs/llm-agent.d.ts +0 -53
  88. package/lib/cjs/llm-agent.js +0 -140
  89. package/lib/cjs/llm-decision-agent.d.ts +0 -53
  90. package/lib/cjs/llm-decision-agent.js +0 -144
  91. package/lib/cjs/llm-model.d.ts +0 -80
  92. package/lib/cjs/llm-model.js +0 -27
  93. package/lib/cjs/llm-models/gemini-llm-model.d.ts +0 -24
  94. package/lib/cjs/llm-models/gemini-llm-model.js +0 -199
  95. package/lib/cjs/llm-models/openai-llm-model.d.ts +0 -26
  96. package/lib/cjs/memorable.d.ts +0 -198
  97. package/lib/cjs/memorable.js +0 -33
  98. package/lib/cjs/open-api-agent.d.ts +0 -26
  99. package/lib/cjs/open-api-agent.js +0 -68
  100. package/lib/cjs/pipeline-agent.d.ts +0 -56
  101. package/lib/cjs/pipeline-agent.js +0 -206
  102. package/lib/cjs/runnable.d.ts +0 -76
  103. package/lib/cjs/runnable.js +0 -37
  104. package/lib/cjs/runtime.d.ts +0 -64
  105. package/lib/cjs/runtime.js +0 -149
  106. package/lib/cjs/sandbox-function-agent.d.ts +0 -21
  107. package/lib/cjs/sandbox-function-agent.js +0 -78
  108. package/lib/cjs/sandbox-function-runner.d.ts +0 -16
  109. package/lib/cjs/sandbox-function-runner.js +0 -32
  110. package/lib/cjs/utils/constants.d.ts +0 -1
  111. package/lib/cjs/utils/constants.js +0 -4
  112. package/lib/cjs/utils/fetch-open-api.d.ts +0 -2
  113. package/lib/cjs/utils/fetch-open-api.js +0 -31
  114. package/lib/cjs/utils/fetch.d.ts +0 -1
  115. package/lib/cjs/utils/fetch.js +0 -21
  116. package/lib/cjs/utils/index.d.ts +0 -12
  117. package/lib/cjs/utils/index.js +0 -28
  118. package/lib/cjs/utils/is-non-nullable.d.ts +0 -2
  119. package/lib/cjs/utils/is-non-nullable.js +0 -20
  120. package/lib/cjs/utils/message-utils.d.ts +0 -20
  121. package/lib/cjs/utils/message-utils.js +0 -79
  122. package/lib/cjs/utils/mustache-utils.d.ts +0 -3
  123. package/lib/cjs/utils/mustache-utils.js +0 -14
  124. package/lib/cjs/utils/nullable.d.ts +0 -7
  125. package/lib/cjs/utils/nullable.js +0 -2
  126. package/lib/cjs/utils/omit.d.ts +0 -1
  127. package/lib/cjs/utils/omit.js +0 -2
  128. package/lib/cjs/utils/open-api-parameter.d.ts +0 -7
  129. package/lib/cjs/utils/open-api-parameter.js +0 -81
  130. package/lib/cjs/utils/ordered-map.d.ts +0 -37
  131. package/lib/cjs/utils/ordered-map.js +0 -103
  132. package/lib/cjs/utils/partial.d.ts +0 -3
  133. package/lib/cjs/utils/partial.js +0 -2
  134. package/lib/cjs/utils/runnable-type.d.ts +0 -5
  135. package/lib/cjs/utils/runnable-type.js +0 -2
  136. package/lib/cjs/utils/stream-utils.d.ts +0 -20
  137. package/lib/cjs/utils/stream-utils.js +0 -86
  138. package/lib/cjs/utils/structured-output-schema.d.ts +0 -3
  139. package/lib/cjs/utils/structured-output-schema.js +0 -43
  140. package/lib/cjs/utils/union.d.ts +0 -1
  141. package/lib/cjs/utils/union.js +0 -2
  142. package/lib/dts/agent.d.ts +0 -96
  143. package/lib/dts/constants.d.ts +0 -7
  144. package/lib/dts/context.d.ts +0 -23
  145. package/lib/dts/definitions/data-schema.d.ts +0 -61
  146. package/lib/dts/definitions/data-type.d.ts +0 -32
  147. package/lib/dts/definitions/memory.d.ts +0 -53
  148. package/lib/dts/definitions/open-api.d.ts +0 -36
  149. package/lib/dts/definitions/preload.d.ts +0 -43
  150. package/lib/dts/function-agent.d.ts +0 -23
  151. package/lib/dts/llm-agent.d.ts +0 -53
  152. package/lib/dts/llm-decision-agent.d.ts +0 -53
  153. package/lib/dts/llm-model.d.ts +0 -80
  154. package/lib/dts/llm-models/gemini-llm-model.d.ts +0 -24
  155. package/lib/dts/llm-models/openai-llm-model.d.ts +0 -26
  156. package/lib/dts/memorable.d.ts +0 -198
  157. package/lib/dts/open-api-agent.d.ts +0 -26
  158. package/lib/dts/pipeline-agent.d.ts +0 -56
  159. package/lib/dts/runnable.d.ts +0 -76
  160. package/lib/dts/runtime.d.ts +0 -64
  161. package/lib/dts/sandbox-function-agent.d.ts +0 -21
  162. package/lib/dts/sandbox-function-runner.d.ts +0 -16
  163. package/lib/dts/utils/constants.d.ts +0 -1
  164. package/lib/dts/utils/fetch-open-api.d.ts +0 -2
  165. package/lib/dts/utils/fetch.d.ts +0 -1
  166. package/lib/dts/utils/index.d.ts +0 -12
  167. package/lib/dts/utils/is-non-nullable.d.ts +0 -2
  168. package/lib/dts/utils/message-utils.d.ts +0 -20
  169. package/lib/dts/utils/mustache-utils.d.ts +0 -3
  170. package/lib/dts/utils/nullable.d.ts +0 -7
  171. package/lib/dts/utils/omit.d.ts +0 -1
  172. package/lib/dts/utils/open-api-parameter.d.ts +0 -7
  173. package/lib/dts/utils/ordered-map.d.ts +0 -37
  174. package/lib/dts/utils/partial.d.ts +0 -3
  175. package/lib/dts/utils/runnable-type.d.ts +0 -5
  176. package/lib/dts/utils/stream-utils.d.ts +0 -20
  177. package/lib/dts/utils/structured-output-schema.d.ts +0 -3
  178. package/lib/dts/utils/union.d.ts +0 -1
  179. package/lib/esm/agent.d.ts +0 -96
  180. package/lib/esm/agent.js +0 -161
  181. package/lib/esm/constants.d.ts +0 -7
  182. package/lib/esm/constants.js +0 -7
  183. package/lib/esm/context.d.ts +0 -23
  184. package/lib/esm/definitions/data-schema.d.ts +0 -61
  185. package/lib/esm/definitions/data-schema.js +0 -44
  186. package/lib/esm/definitions/data-type.d.ts +0 -32
  187. package/lib/esm/definitions/data-type.js +0 -1
  188. package/lib/esm/definitions/memory.d.ts +0 -53
  189. package/lib/esm/definitions/memory.js +0 -20
  190. package/lib/esm/definitions/open-api.d.ts +0 -36
  191. package/lib/esm/definitions/open-api.js +0 -1
  192. package/lib/esm/definitions/preload.d.ts +0 -43
  193. package/lib/esm/definitions/preload.js +0 -31
  194. package/lib/esm/function-agent.d.ts +0 -23
  195. package/lib/esm/function-agent.js +0 -59
  196. package/lib/esm/llm-agent.d.ts +0 -53
  197. package/lib/esm/llm-agent.js +0 -137
  198. package/lib/esm/llm-decision-agent.d.ts +0 -53
  199. package/lib/esm/llm-decision-agent.js +0 -141
  200. package/lib/esm/llm-model.d.ts +0 -80
  201. package/lib/esm/llm-model.js +0 -23
  202. package/lib/esm/llm-models/gemini-llm-model.d.ts +0 -24
  203. package/lib/esm/llm-models/gemini-llm-model.js +0 -195
  204. package/lib/esm/llm-models/openai-llm-model.d.ts +0 -26
  205. package/lib/esm/memorable.d.ts +0 -198
  206. package/lib/esm/memorable.js +0 -28
  207. package/lib/esm/open-api-agent.d.ts +0 -26
  208. package/lib/esm/open-api-agent.js +0 -65
  209. package/lib/esm/pipeline-agent.d.ts +0 -56
  210. package/lib/esm/pipeline-agent.js +0 -203
  211. package/lib/esm/runnable.d.ts +0 -76
  212. package/lib/esm/runnable.js +0 -30
  213. package/lib/esm/runtime.d.ts +0 -64
  214. package/lib/esm/runtime.js +0 -146
  215. package/lib/esm/sandbox-function-agent.d.ts +0 -21
  216. package/lib/esm/sandbox-function-agent.js +0 -74
  217. package/lib/esm/sandbox-function-runner.d.ts +0 -16
  218. package/lib/esm/sandbox-function-runner.js +0 -28
  219. package/lib/esm/utils/constants.d.ts +0 -1
  220. package/lib/esm/utils/constants.js +0 -1
  221. package/lib/esm/utils/fetch-open-api.d.ts +0 -2
  222. package/lib/esm/utils/fetch-open-api.js +0 -28
  223. package/lib/esm/utils/fetch.d.ts +0 -1
  224. package/lib/esm/utils/fetch.js +0 -18
  225. package/lib/esm/utils/index.d.ts +0 -12
  226. package/lib/esm/utils/index.js +0 -12
  227. package/lib/esm/utils/is-non-nullable.d.ts +0 -2
  228. package/lib/esm/utils/is-non-nullable.js +0 -13
  229. package/lib/esm/utils/message-utils.d.ts +0 -20
  230. package/lib/esm/utils/message-utils.js +0 -71
  231. package/lib/esm/utils/mustache-utils.d.ts +0 -3
  232. package/lib/esm/utils/mustache-utils.js +0 -8
  233. package/lib/esm/utils/nullable.d.ts +0 -7
  234. package/lib/esm/utils/nullable.js +0 -1
  235. package/lib/esm/utils/omit.d.ts +0 -1
  236. package/lib/esm/utils/omit.js +0 -1
  237. package/lib/esm/utils/open-api-parameter.d.ts +0 -7
  238. package/lib/esm/utils/open-api-parameter.js +0 -78
  239. package/lib/esm/utils/ordered-map.d.ts +0 -37
  240. package/lib/esm/utils/ordered-map.js +0 -100
  241. package/lib/esm/utils/partial.d.ts +0 -3
  242. package/lib/esm/utils/partial.js +0 -1
  243. package/lib/esm/utils/runnable-type.d.ts +0 -5
  244. package/lib/esm/utils/runnable-type.js +0 -1
  245. package/lib/esm/utils/stream-utils.d.ts +0 -20
  246. package/lib/esm/utils/stream-utils.js +0 -79
  247. package/lib/esm/utils/structured-output-schema.d.ts +0 -3
  248. package/lib/esm/utils/structured-output-schema.js +0 -37
  249. package/lib/esm/utils/union.d.ts +0 -1
  250. package/lib/esm/utils/union.js +0 -1
  251. /package/lib/cjs/{context.js → execution-engine/context.js} +0 -0
  252. /package/lib/esm/{context.js → execution-engine/context.js} +0 -0
@@ -0,0 +1,55 @@
1
+ import EventEmitter from "node:events";
2
+ import { type ZodObject, type ZodType } from "zod";
3
+ import type { Context } from "../execution-engine/context";
4
+ import { type TransferAgentOutput } from "./types";
5
+ export type AgentInput = Record<string, unknown>;
6
+ export type AgentOutput = Record<string, unknown> & Partial<TransferAgentOutput>;
7
+ export type SubscribeTopic = string | string[];
8
+ export type PublishTopic<O extends AgentOutput = AgentOutput> = string | string[] | ((output: O) => string | string[] | Promise<string | string[]>);
9
+ export interface AgentOptions<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> {
10
+ subscribeTopic?: SubscribeTopic;
11
+ publishTopic?: PublishTopic<O>;
12
+ name?: string;
13
+ description?: string;
14
+ inputSchema?: ZodObject<{
15
+ [key in keyof I]: ZodType;
16
+ }>;
17
+ outputSchema?: ZodObject<{
18
+ [key in keyof O]: ZodType;
19
+ }>;
20
+ includeInputInOutput?: boolean;
21
+ tools?: (Agent | FunctionAgentFn)[];
22
+ }
23
+ export declare class Agent<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> extends EventEmitter {
24
+ static from<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput>(options: AgentOptions<I, O>): Agent<I, O>;
25
+ constructor(options: AgentOptions<I, O>);
26
+ readonly name: string;
27
+ readonly description?: string;
28
+ readonly inputSchema: ZodObject<{
29
+ [key in keyof I]: ZodType;
30
+ }>;
31
+ readonly outputSchema: ZodObject<{
32
+ [key in keyof O]: ZodType;
33
+ }>;
34
+ readonly includeInputInOutput?: boolean;
35
+ readonly subscribeTopic?: SubscribeTopic;
36
+ readonly publishTopic?: PublishTopic<AgentOutput>;
37
+ readonly tools: Agent<AgentInput, AgentOutput>[] & {
38
+ [key: string]: Agent<AgentInput, AgentOutput>;
39
+ };
40
+ addTool<I extends AgentInput, O extends AgentOutput>(tool: Agent<I, O> | FunctionAgentFn<I, O>): void;
41
+ get isCallable(): boolean;
42
+ call(input: I | string, context?: Context): Promise<O>;
43
+ process?(input: I, context?: Context): Promise<O>;
44
+ shutdown(): Promise<void>;
45
+ }
46
+ export interface FunctionAgentOptions<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> extends AgentOptions<I, O> {
47
+ fn?: FunctionAgentFn<I, O>;
48
+ }
49
+ export declare class FunctionAgent<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> extends Agent<I, O> {
50
+ static from<I extends AgentInput, O extends AgentOutput>(options: FunctionAgentOptions<I, O> | FunctionAgentFn<I, O>): FunctionAgent<I, O>;
51
+ constructor(options: FunctionAgentOptions<I, O>);
52
+ fn: FunctionAgentFn<I, O>;
53
+ process(input: I, context?: Context): Promise<O>;
54
+ }
55
+ export type FunctionAgentFn<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> = (input: I, context?: Context) => O | Promise<O> | Agent | Promise<Agent>;
@@ -0,0 +1,91 @@
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.FunctionAgent = exports.Agent = void 0;
7
+ const node_events_1 = __importDefault(require("node:events"));
8
+ const zod_1 = require("zod");
9
+ const prompt_builder_1 = require("../prompt/prompt-builder");
10
+ const logger_1 = require("../utils/logger");
11
+ const types_1 = require("./types");
12
+ class Agent extends node_events_1.default {
13
+ static from(options) {
14
+ return new Agent(options);
15
+ }
16
+ constructor(options) {
17
+ super();
18
+ this.name = options.name || this.constructor.name;
19
+ this.description = options.description;
20
+ this.inputSchema =
21
+ options.inputSchema || zod_1.z.object({});
22
+ this.outputSchema =
23
+ options.outputSchema || zod_1.z.object({});
24
+ this.includeInputInOutput = options.includeInputInOutput;
25
+ this.subscribeTopic = options.subscribeTopic;
26
+ this.publishTopic = options.publishTopic;
27
+ if (options.tools?.length)
28
+ this.tools.push(...options.tools.map(functionToAgent));
29
+ }
30
+ name;
31
+ description;
32
+ inputSchema;
33
+ outputSchema;
34
+ includeInputInOutput;
35
+ subscribeTopic;
36
+ publishTopic;
37
+ tools = new Proxy([], {
38
+ get: (t, p, r) => Reflect.get(t, p, r) ?? t.find((t) => t.name === p),
39
+ });
40
+ addTool(tool) {
41
+ this.tools.push(typeof tool === "function" ? functionToAgent(tool) : tool);
42
+ }
43
+ get isCallable() {
44
+ return !!this.process;
45
+ }
46
+ async call(input, context) {
47
+ if (!this.process)
48
+ throw new Error("Agent must implement process method");
49
+ const _input = typeof input === "string" ? (0, prompt_builder_1.userInput)(input) : input;
50
+ const parsedInput = this.inputSchema.passthrough().parse(_input);
51
+ logger_1.logger.debug(`Call agent ${this.name} start`, parsedInput);
52
+ const output = await this.process(parsedInput, context);
53
+ const parsedOutput = this.outputSchema.passthrough().parse(output);
54
+ const finalOutput = this.includeInputInOutput
55
+ ? { ...parsedInput, ...parsedOutput }
56
+ : parsedOutput;
57
+ logger_1.logger.debug(`Call agent ${this.name} successfully`, {
58
+ ...finalOutput,
59
+ ...(finalOutput[types_1.transferAgentOutputKey]
60
+ ? { [types_1.transferAgentOutputKey]: finalOutput[types_1.transferAgentOutputKey].agent.name }
61
+ : {}),
62
+ });
63
+ return finalOutput;
64
+ }
65
+ async shutdown() { }
66
+ }
67
+ exports.Agent = Agent;
68
+ class FunctionAgent extends Agent {
69
+ static from(options) {
70
+ return typeof options === "function" ? functionToAgent(options) : new FunctionAgent(options);
71
+ }
72
+ constructor(options) {
73
+ super(options);
74
+ this.fn = options.fn ?? (() => ({}));
75
+ }
76
+ fn;
77
+ async process(input, context) {
78
+ const result = await this.fn(input, context);
79
+ if (result instanceof Agent) {
80
+ return (0, types_1.transferToAgentOutput)(result);
81
+ }
82
+ return result;
83
+ }
84
+ }
85
+ exports.FunctionAgent = FunctionAgent;
86
+ function functionToAgent(agent) {
87
+ if (typeof agent === "function") {
88
+ return FunctionAgent.from({ name: agent.name, fn: agent });
89
+ }
90
+ return agent;
91
+ }
@@ -0,0 +1,20 @@
1
+ import type { Context } from "../execution-engine/context";
2
+ import type { ChatModel } from "../models/chat";
3
+ import { PromptBuilder } from "../prompt/prompt-builder";
4
+ import { Agent, type AgentInput, type AgentOptions, type AgentOutput } from "./agent";
5
+ export interface AIAgentOptions<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> extends AgentOptions<I, O> {
6
+ model?: ChatModel;
7
+ instructions?: string | PromptBuilder;
8
+ outputKey?: string;
9
+ toolChoice?: AIAgentToolChoice;
10
+ }
11
+ export type AIAgentToolChoice = "auto" | "none" | "required" | "router" | Agent;
12
+ export declare class AIAgent<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> extends Agent<I, O> {
13
+ static from<I extends AgentInput, O extends AgentOutput>(options: AIAgentOptions<I, O>): AIAgent<I, O>;
14
+ constructor(options: AIAgentOptions<I, O>);
15
+ model?: ChatModel;
16
+ instructions: PromptBuilder;
17
+ outputKey?: string;
18
+ toolChoice?: AIAgentToolChoice;
19
+ process(input: I, context?: Context): Promise<O>;
20
+ }
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AIAgent = void 0;
4
+ const prompt_builder_1 = require("../prompt/prompt-builder");
5
+ const template_1 = require("../prompt/template");
6
+ const agent_1 = require("./agent");
7
+ const types_1 = require("./types");
8
+ const DEFAULT_OUTPUT_KEY = "text";
9
+ class AIAgent extends agent_1.Agent {
10
+ static from(options) {
11
+ return new AIAgent(options);
12
+ }
13
+ constructor(options) {
14
+ super(options);
15
+ this.model = options.model;
16
+ this.instructions =
17
+ typeof options.instructions === "string"
18
+ ? prompt_builder_1.PromptBuilder.from(options.instructions)
19
+ : (options.instructions ?? new prompt_builder_1.PromptBuilder());
20
+ this.outputKey = options.outputKey;
21
+ this.toolChoice = options.toolChoice;
22
+ }
23
+ model;
24
+ instructions;
25
+ outputKey;
26
+ toolChoice;
27
+ async process(input, context) {
28
+ const model = context?.model ?? this.model;
29
+ if (!model)
30
+ throw new Error("model is required to run AIAgent");
31
+ let transferOutput;
32
+ const { toolAgents, ...modelInput } = await this.instructions.build({
33
+ agent: this,
34
+ input,
35
+ model,
36
+ context,
37
+ });
38
+ const toolsMap = new Map(toolAgents?.map((i) => [i.name, i]));
39
+ for (;;) {
40
+ const { text, json, toolCalls } = await model.call(modelInput, context);
41
+ if (toolCalls?.length) {
42
+ const executedToolCalls = [];
43
+ for (const call of toolCalls) {
44
+ const tool = toolsMap.get(call.function.name);
45
+ if (!tool)
46
+ throw new Error(`Tool not found: ${call.function.name}`);
47
+ const output = await tool.call(call.function.arguments, context);
48
+ // Save the TransferAgentOutput for later
49
+ if ((0, types_1.isTransferAgentOutput)(output)) {
50
+ transferOutput = output;
51
+ }
52
+ else {
53
+ executedToolCalls.push({ call, output });
54
+ }
55
+ }
56
+ if (this.toolChoice === "router") {
57
+ const output = executedToolCalls[0]?.output;
58
+ if (!output || executedToolCalls.length !== 1) {
59
+ throw new Error("Router toolChoice requires exactly one tool to be executed");
60
+ }
61
+ return output;
62
+ }
63
+ // Continue LLM function calling loop if any tools were executed
64
+ if (executedToolCalls.length) {
65
+ modelInput.messages.push(template_1.AgentMessageTemplate.from(executedToolCalls.map(({ call }) => call)).format());
66
+ modelInput.messages.push(...executedToolCalls.map(({ call, output }) => template_1.ToolMessageTemplate.from(output, call.id).format()));
67
+ continue;
68
+ }
69
+ }
70
+ const result = {};
71
+ if (modelInput.responseFormat?.type === "json_schema") {
72
+ Object.assign(result, json);
73
+ }
74
+ else {
75
+ const outputKey = this.outputKey || DEFAULT_OUTPUT_KEY;
76
+ Object.assign(result, { [outputKey]: text });
77
+ }
78
+ // Return the TransferAgentOutput if it exists
79
+ if (transferOutput) {
80
+ result[types_1.transferAgentOutputKey] = transferOutput[types_1.transferAgentOutputKey];
81
+ }
82
+ return result;
83
+ }
84
+ }
85
+ }
86
+ exports.AIAgent = AIAgent;
@@ -0,0 +1,27 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { type StdioServerParameters } from "@modelcontextprotocol/sdk/client/stdio.js";
3
+ import { Agent, type AgentInput, type AgentOptions, type AgentOutput } from "./agent";
4
+ export interface MCPAgentOptions extends AgentOptions {
5
+ client: Client;
6
+ }
7
+ export type MCPServerOptions = SSEServerParameters | StdioServerParameters;
8
+ export type SSEServerParameters = {
9
+ url: string;
10
+ };
11
+ export declare class MCPAgent extends Agent {
12
+ static from(options: MCPServerOptions): Promise<MCPAgent>;
13
+ static from(options: MCPAgentOptions): MCPAgent;
14
+ private static fromTransport;
15
+ constructor(options: MCPAgentOptions);
16
+ private client;
17
+ shutdown(): Promise<void>;
18
+ }
19
+ export interface MCPToolOptions extends AgentOptions {
20
+ client: Client;
21
+ }
22
+ export declare class MCPTool extends Agent {
23
+ constructor(options: MCPToolOptions);
24
+ private client;
25
+ private get mcpServer();
26
+ process(input: AgentInput): Promise<AgentOutput>;
27
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MCPTool = exports.MCPAgent = void 0;
4
+ const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
5
+ const sse_js_1 = require("@modelcontextprotocol/sdk/client/sse.js");
6
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/client/stdio.js");
7
+ const json_schema_to_zod_1 = require("@n8n/json-schema-to-zod");
8
+ const zod_1 = require("zod");
9
+ const logger_1 = require("../utils/logger");
10
+ const agent_1 = require("./agent");
11
+ const MCP_AGENT_CLIENT_NAME = "MCPAgent";
12
+ const MCP_AGENT_CLIENT_VERSION = "0.0.1";
13
+ const debug = logger_1.logger.base.extend("mcp-agent:debug", "/");
14
+ function isSSEServerParameters(options) {
15
+ return "url" in options && typeof options.url === "string";
16
+ }
17
+ function isStdioServerParameters(options) {
18
+ return "command" in options && typeof options.command === "string";
19
+ }
20
+ class MCPAgent extends agent_1.Agent {
21
+ static from(options) {
22
+ if (isSSEServerParameters(options)) {
23
+ const transport = new sse_js_1.SSEClientTransport(new URL(options.url));
24
+ return MCPAgent.fromTransport(transport);
25
+ }
26
+ if (isStdioServerParameters(options)) {
27
+ const transport = new stdio_js_1.StdioClientTransport(options);
28
+ return MCPAgent.fromTransport(transport);
29
+ }
30
+ return new MCPAgent(options);
31
+ }
32
+ static async fromTransport(transport) {
33
+ const client = new index_js_1.Client({
34
+ name: MCP_AGENT_CLIENT_NAME,
35
+ version: MCP_AGENT_CLIENT_VERSION,
36
+ });
37
+ debug(`Connecting to MCP server with transport ${transport.constructor.name}`);
38
+ await client.connect(transport);
39
+ debug(`Connected to MCP server with transport ${transport.constructor.name}`);
40
+ const mcpServer = getMCPServerName(client);
41
+ debug(`Listing tools from ${mcpServer}`);
42
+ const { tools: mcpTools } = await client.listTools();
43
+ debug(`Listed tools from ${mcpServer}`, mcpTools.map((i) => i.name));
44
+ const tools = mcpTools.map((tool) => {
45
+ return new MCPTool({
46
+ client,
47
+ name: tool.name,
48
+ description: tool.description,
49
+ inputSchema: (0, json_schema_to_zod_1.jsonSchemaToZod)(tool.inputSchema),
50
+ outputSchema: zod_1.z
51
+ .object({
52
+ _meta: zod_1.z.record(zod_1.z.unknown()).optional(),
53
+ content: zod_1.z.array(zod_1.z.record(zod_1.z.unknown())),
54
+ isError: zod_1.z.boolean().optional(),
55
+ })
56
+ .passthrough(),
57
+ });
58
+ });
59
+ return new MCPAgent({ client, tools });
60
+ }
61
+ constructor(options) {
62
+ super(options);
63
+ this.client = options.client;
64
+ }
65
+ client;
66
+ async shutdown() {
67
+ super.shutdown();
68
+ await this.client.close();
69
+ }
70
+ }
71
+ exports.MCPAgent = MCPAgent;
72
+ class MCPTool extends agent_1.Agent {
73
+ constructor(options) {
74
+ super(options);
75
+ this.client = options.client;
76
+ }
77
+ client;
78
+ get mcpServer() {
79
+ return getMCPServerName(this.client);
80
+ }
81
+ async process(input) {
82
+ debug(`Start call tool ${this.name} from ${this.mcpServer} with input`, input);
83
+ const result = await this.client.callTool({ name: this.name, arguments: input });
84
+ debug(`End call tool ${this.name} from ${this.mcpServer} with result`, result);
85
+ return result;
86
+ }
87
+ }
88
+ exports.MCPTool = MCPTool;
89
+ function getMCPServerName(client) {
90
+ const info = client.getServerVersion();
91
+ if (!info)
92
+ return undefined;
93
+ const { name, version } = info;
94
+ return `${name}@${version}`;
95
+ }
@@ -0,0 +1,9 @@
1
+ import type { Agent, AgentOutput } from "./agent";
2
+ export declare const transferAgentOutputKey = "$transferAgentTo";
3
+ export interface TransferAgentOutput extends Record<string, unknown> {
4
+ [transferAgentOutputKey]: {
5
+ agent: Agent;
6
+ };
7
+ }
8
+ export declare function transferToAgentOutput(agent: Agent): TransferAgentOutput;
9
+ export declare function isTransferAgentOutput(output: AgentOutput): output is TransferAgentOutput;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transferAgentOutputKey = void 0;
4
+ exports.transferToAgentOutput = transferToAgentOutput;
5
+ exports.isTransferAgentOutput = isTransferAgentOutput;
6
+ exports.transferAgentOutputKey = "$transferAgentTo";
7
+ function transferToAgentOutput(agent) {
8
+ return {
9
+ [exports.transferAgentOutputKey]: {
10
+ agent,
11
+ },
12
+ };
13
+ }
14
+ function isTransferAgentOutput(output) {
15
+ return exports.transferAgentOutputKey in output;
16
+ }
@@ -0,0 +1,10 @@
1
+ import type EventEmitter from "node:events";
2
+ import type { Agent, AgentInput, AgentOutput } from "../agents/agent";
3
+ import type { ChatModel } from "../models/chat";
4
+ export interface Context extends EventEmitter {
5
+ model?: ChatModel;
6
+ tools?: Agent[];
7
+ publish(topic: string, message: unknown): void;
8
+ subscribe(topic: string, listener: (message: AgentInput) => void): void;
9
+ unsubscribe(topic: string, listener: (message: AgentOutput) => void): void;
10
+ }
@@ -0,0 +1,45 @@
1
+ import EventEmitter from "node:events";
2
+ import { Agent, type AgentInput, type AgentOptions, type AgentOutput } from "../agents/agent";
3
+ import type { ChatModel } from "../models/chat";
4
+ import type { Context } from "./context";
5
+ export interface ExecutionEngineOptions {
6
+ model?: ChatModel;
7
+ tools?: Agent[];
8
+ agents?: Agent[];
9
+ }
10
+ export interface ExecutionEngineRunOptions {
11
+ concurrency?: boolean;
12
+ }
13
+ export declare class ExecutionEngine extends EventEmitter implements Context {
14
+ constructor(options?: ExecutionEngineOptions);
15
+ private messageQueue;
16
+ model?: ChatModel;
17
+ tools: Agent[];
18
+ private agents;
19
+ private agentListeners;
20
+ addAgent(...agents: Agent[]): void;
21
+ private attachAgentSubscriptions;
22
+ publish(topic: string, message: unknown): void;
23
+ subscribe(topic: string, listener: (message: AgentOutput) => void): void;
24
+ unsubscribe(topic: string, listener: (message: AgentOutput) => void): void;
25
+ run(agent: Agent): Promise<UserAgent>;
26
+ run(input: AgentInput | string): Promise<AgentOutput>;
27
+ run(input: AgentInput | string, ...agents: Agent[]): Promise<AgentOutput>;
28
+ run(input: AgentInput | string, options: ExecutionEngineRunOptions, ...agents: Agent[]): Promise<AgentOutput>;
29
+ private splitOptionsAndAgents;
30
+ private runSequential;
31
+ private runParallel;
32
+ private publishUserInputTopic;
33
+ private runChatLoop;
34
+ private callAgent;
35
+ shutdown(): Promise<void>;
36
+ }
37
+ export declare class UserAgent<I extends AgentInput = AgentInput, O extends AgentOutput = AgentOutput> extends Agent<I, O> {
38
+ options: AgentOptions<I, O> & {
39
+ run: (input: I) => Promise<O>;
40
+ };
41
+ constructor(options: AgentOptions<I, O> & {
42
+ run: (input: I) => Promise<O>;
43
+ });
44
+ process(input: I): Promise<O>;
45
+ }
@@ -0,0 +1,190 @@
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.UserAgent = exports.ExecutionEngine = void 0;
7
+ const node_events_1 = __importDefault(require("node:events"));
8
+ const nanoid_1 = require("nanoid");
9
+ const agent_1 = require("../agents/agent");
10
+ const types_1 = require("../agents/types");
11
+ const prompt_builder_1 = require("../prompt/prompt-builder");
12
+ const type_utils_1 = require("../utils/type-utils");
13
+ const message_queue_1 = require("./message-queue");
14
+ class ExecutionEngine extends node_events_1.default {
15
+ constructor(options) {
16
+ super();
17
+ this.model = options?.model;
18
+ this.tools = options?.tools ?? [];
19
+ if (options?.agents?.length)
20
+ this.addAgent(...options.agents);
21
+ }
22
+ messageQueue = new message_queue_1.MessageQueue();
23
+ model;
24
+ tools;
25
+ agents = [];
26
+ agentListeners = new Map();
27
+ addAgent(...agents) {
28
+ for (const agent of agents) {
29
+ this.agents.push(agent);
30
+ this.attachAgentSubscriptions(agent);
31
+ }
32
+ }
33
+ attachAgentSubscriptions(agent) {
34
+ for (const topic of (0, type_utils_1.orArrayToArray)(agent.subscribeTopic)) {
35
+ const listener = async (input) => {
36
+ try {
37
+ const { output } = await this.callAgent(input, agent);
38
+ const topics = typeof agent.publishTopic === "function"
39
+ ? await agent.publishTopic(output)
40
+ : agent.publishTopic;
41
+ for (const topic of (0, type_utils_1.orArrayToArray)(topics)) {
42
+ this.publish(topic, output);
43
+ }
44
+ }
45
+ catch (error) {
46
+ this.emit("error", error);
47
+ }
48
+ };
49
+ this.subscribe(topic, listener);
50
+ const listeners = this.agentListeners.get(agent) || [];
51
+ listeners.push({ topic, listener });
52
+ this.agentListeners.set(agent, listeners);
53
+ }
54
+ }
55
+ publish(topic, message) {
56
+ this.messageQueue.emit(topic, message);
57
+ }
58
+ subscribe(topic, listener) {
59
+ this.messageQueue.on(topic, listener);
60
+ }
61
+ unsubscribe(topic, listener) {
62
+ this.messageQueue.off(topic, listener);
63
+ }
64
+ async run(_input, _options, ..._agents) {
65
+ if (_input instanceof agent_1.Agent)
66
+ return this.runChatLoop(_input);
67
+ const [options, agents] = this.splitOptionsAndAgents(_options, ..._agents);
68
+ const input = typeof _input === "string" ? (0, prompt_builder_1.userInput)(_input) : _input;
69
+ if (agents.length === 0)
70
+ return this.publishUserInputTopic(input);
71
+ if (options?.concurrency)
72
+ return this.runParallel(input, ...agents);
73
+ return this.runSequential(input, ...agents);
74
+ }
75
+ splitOptionsAndAgents(options, ...agents) {
76
+ if (options instanceof agent_1.Agent) {
77
+ return [{}, [options, ...agents]];
78
+ }
79
+ return [options, agents];
80
+ }
81
+ async runSequential(input, ...agents) {
82
+ const output = {};
83
+ for (const agent of agents.flat()) {
84
+ const { output: o } = await this.callAgent({ ...input, ...output }, agent);
85
+ Object.assign(output, o);
86
+ }
87
+ return output;
88
+ }
89
+ async runParallel(input, ...agents) {
90
+ const outputs = await Promise.all(agents.map((agent) => this.callAgent(input, agent).then((res) => res.output)));
91
+ return Object.assign({}, ...outputs);
92
+ }
93
+ async publishUserInputTopic(input) {
94
+ this.publish(message_queue_1.UserInputTopic, input);
95
+ // TODO: 处理超时、错误、无限循环、饿死等情况
96
+ const result = await new Promise((resolve) => {
97
+ this.messageQueue.on(message_queue_1.UserOutputTopic, (result) => resolve(result));
98
+ });
99
+ return result;
100
+ }
101
+ async runChatLoop(agent) {
102
+ const inputStream = new TransformStream({});
103
+ const inputWriter = inputStream.writable.getWriter();
104
+ const userAgent = new UserAgent({
105
+ async run(input) {
106
+ const wait = Promise.withResolvers();
107
+ inputWriter.write({ ...wait, input });
108
+ return wait.promise;
109
+ },
110
+ });
111
+ // Run the loop in a separate async function, so that we can return the userAgent
112
+ (async () => {
113
+ let activeAgent = agent;
114
+ const reader = inputStream.readable.getReader();
115
+ for (;;) {
116
+ const { value, done } = await reader.read();
117
+ if (done)
118
+ break;
119
+ const { input, resolve } = value;
120
+ const { agent, output } = await this.callAgent(input, activeAgent);
121
+ if (agent)
122
+ activeAgent = agent;
123
+ resolve(output);
124
+ }
125
+ })();
126
+ return userAgent;
127
+ }
128
+ async callAgent(input, agent) {
129
+ let activeAgent = agent;
130
+ let output;
131
+ for (;;) {
132
+ output = await activeAgent.call(input, this);
133
+ if ((0, types_1.isTransferAgentOutput)(output)) {
134
+ // TODO: 不要修改原始对象,可能被外部丢弃
135
+ const transferToolCallId = (0, nanoid_1.nanoid)();
136
+ Object.assign(input, (0, prompt_builder_1.addMessagesToInput)(input, [
137
+ {
138
+ role: "agent",
139
+ name: agent.name,
140
+ toolCalls: [
141
+ {
142
+ id: transferToolCallId,
143
+ type: "function",
144
+ function: {
145
+ name: "transfer_to_agent",
146
+ arguments: {
147
+ to: output[types_1.transferAgentOutputKey].agent.name,
148
+ },
149
+ },
150
+ },
151
+ ],
152
+ },
153
+ {
154
+ role: "tool",
155
+ toolCallId: transferToolCallId,
156
+ content: `Transferred to ${output[types_1.transferAgentOutputKey].agent.name}. Adopt persona immediately.`,
157
+ },
158
+ ]));
159
+ activeAgent = output[types_1.transferAgentOutputKey].agent;
160
+ }
161
+ else {
162
+ break;
163
+ }
164
+ }
165
+ return {
166
+ agent: activeAgent,
167
+ output,
168
+ };
169
+ }
170
+ async shutdown() {
171
+ for (const tool of this.tools) {
172
+ await tool.shutdown();
173
+ }
174
+ for (const agent of this.agents) {
175
+ await agent.shutdown();
176
+ }
177
+ }
178
+ }
179
+ exports.ExecutionEngine = ExecutionEngine;
180
+ class UserAgent extends agent_1.Agent {
181
+ options;
182
+ constructor(options) {
183
+ super(options);
184
+ this.options = options;
185
+ }
186
+ process(input) {
187
+ return this.options.run(input);
188
+ }
189
+ }
190
+ exports.UserAgent = UserAgent;
@@ -0,0 +1,5 @@
1
+ import { EventEmitter } from "node:events";
2
+ export declare const UserInputTopic = "UserInputTopic";
3
+ export declare const UserOutputTopic = "UserOutputTopic";
4
+ export declare class MessageQueue extends EventEmitter {
5
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MessageQueue = exports.UserOutputTopic = exports.UserInputTopic = void 0;
4
+ const node_events_1 = require("node:events");
5
+ exports.UserInputTopic = "UserInputTopic";
6
+ exports.UserOutputTopic = "UserOutputTopic";
7
+ class MessageQueue extends node_events_1.EventEmitter {
8
+ }
9
+ exports.MessageQueue = MessageQueue;