@aigne/core 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +9 -7
  3. package/README.zh.md +9 -7
  4. package/lib/cjs/agents/agent.d.ts +168 -29
  5. package/lib/cjs/agents/agent.js +152 -56
  6. package/lib/cjs/agents/ai-agent.d.ts +7 -7
  7. package/lib/cjs/agents/ai-agent.js +19 -15
  8. package/lib/{esm/models → cjs/agents}/chat-model.d.ts +29 -19
  9. package/lib/cjs/{models → agents}/chat-model.js +56 -15
  10. package/lib/cjs/agents/guide-rail-agent.d.ts +62 -0
  11. package/lib/cjs/agents/guide-rail-agent.js +14 -0
  12. package/lib/cjs/agents/mcp-agent.d.ts +3 -4
  13. package/lib/cjs/agents/mcp-agent.js +11 -11
  14. package/lib/cjs/agents/team-agent.d.ts +7 -8
  15. package/lib/cjs/agents/team-agent.js +10 -10
  16. package/lib/cjs/agents/user-agent.d.ts +4 -4
  17. package/lib/cjs/agents/user-agent.js +10 -10
  18. package/lib/cjs/aigne/aigne.d.ts +13 -11
  19. package/lib/cjs/aigne/aigne.js +7 -6
  20. package/lib/cjs/aigne/context.d.ts +19 -8
  21. package/lib/cjs/aigne/context.js +27 -7
  22. package/lib/cjs/index.d.ts +2 -1
  23. package/lib/cjs/index.js +2 -1
  24. package/lib/cjs/loader/agent-yaml.d.ts +2 -2
  25. package/lib/cjs/loader/index.d.ts +18 -11
  26. package/lib/cjs/loader/index.js +8 -27
  27. package/lib/cjs/memory/default-memory/default-memory-storage/index.d.ts +30 -0
  28. package/lib/cjs/memory/default-memory/default-memory-storage/index.js +69 -0
  29. package/lib/cjs/memory/default-memory/default-memory-storage/migrate.d.ts +7 -0
  30. package/lib/cjs/memory/default-memory/default-memory-storage/migrate.js +53 -0
  31. package/lib/cjs/memory/default-memory/default-memory-storage/migrations/20250523165801-init.d.ts +7 -0
  32. package/lib/cjs/memory/default-memory/default-memory-storage/migrations/20250523165801-init.js +33 -0
  33. package/lib/cjs/memory/default-memory/default-memory-storage/models/memory.d.ts +10 -0
  34. package/lib/cjs/memory/default-memory/default-memory-storage/models/memory.js +32 -0
  35. package/lib/cjs/memory/default-memory/index.d.ts +10 -0
  36. package/lib/cjs/memory/{default-memory.js → default-memory/index.js} +16 -25
  37. package/lib/cjs/memory/default-memory/storage.d.ts +13 -0
  38. package/lib/cjs/memory/default-memory/storage.js +6 -0
  39. package/lib/cjs/memory/memory.d.ts +3 -2
  40. package/lib/cjs/memory/memory.js +1 -1
  41. package/lib/cjs/memory/retriever.d.ts +2 -2
  42. package/lib/cjs/prompt/prompt-builder.d.ts +10 -4
  43. package/lib/cjs/prompt/prompt-builder.js +4 -4
  44. package/lib/cjs/prompt/template.d.ts +3 -3
  45. package/lib/cjs/utils/json-schema.js +1 -1
  46. package/lib/cjs/utils/logger.d.ts +33 -8
  47. package/lib/cjs/utils/logger.js +63 -5
  48. package/lib/cjs/utils/model-utils.d.ts +1 -1
  49. package/lib/cjs/utils/stream-utils.d.ts +3 -1
  50. package/lib/cjs/utils/stream-utils.js +31 -1
  51. package/lib/cjs/utils/type-utils.d.ts +7 -2
  52. package/lib/dts/agents/agent.d.ts +168 -29
  53. package/lib/dts/agents/ai-agent.d.ts +7 -7
  54. package/lib/{cjs/models → dts/agents}/chat-model.d.ts +29 -19
  55. package/lib/dts/agents/guide-rail-agent.d.ts +62 -0
  56. package/lib/dts/agents/mcp-agent.d.ts +3 -4
  57. package/lib/dts/agents/team-agent.d.ts +7 -8
  58. package/lib/dts/agents/user-agent.d.ts +4 -4
  59. package/lib/dts/aigne/aigne.d.ts +13 -11
  60. package/lib/dts/aigne/context.d.ts +19 -8
  61. package/lib/dts/index.d.ts +2 -1
  62. package/lib/dts/loader/agent-yaml.d.ts +2 -2
  63. package/lib/dts/loader/index.d.ts +18 -11
  64. package/lib/dts/memory/default-memory/default-memory-storage/index.d.ts +30 -0
  65. package/lib/dts/memory/default-memory/default-memory-storage/migrate.d.ts +7 -0
  66. package/lib/dts/memory/default-memory/default-memory-storage/migrations/20250523165801-init.d.ts +7 -0
  67. package/lib/dts/memory/default-memory/default-memory-storage/models/memory.d.ts +10 -0
  68. package/lib/dts/memory/default-memory/index.d.ts +10 -0
  69. package/lib/dts/memory/default-memory/storage.d.ts +13 -0
  70. package/lib/dts/memory/memory.d.ts +3 -2
  71. package/lib/dts/memory/retriever.d.ts +2 -2
  72. package/lib/dts/prompt/prompt-builder.d.ts +10 -4
  73. package/lib/dts/prompt/template.d.ts +3 -3
  74. package/lib/dts/utils/logger.d.ts +33 -8
  75. package/lib/dts/utils/model-utils.d.ts +1 -1
  76. package/lib/dts/utils/stream-utils.d.ts +3 -1
  77. package/lib/dts/utils/type-utils.d.ts +7 -2
  78. package/lib/esm/agents/agent.d.ts +168 -29
  79. package/lib/esm/agents/agent.js +152 -56
  80. package/lib/esm/agents/ai-agent.d.ts +7 -7
  81. package/lib/esm/agents/ai-agent.js +18 -14
  82. package/lib/{dts/models → esm/agents}/chat-model.d.ts +29 -19
  83. package/lib/esm/{models → agents}/chat-model.js +56 -15
  84. package/lib/esm/agents/guide-rail-agent.d.ts +62 -0
  85. package/lib/esm/agents/guide-rail-agent.js +11 -0
  86. package/lib/esm/agents/mcp-agent.d.ts +3 -4
  87. package/lib/esm/agents/mcp-agent.js +11 -11
  88. package/lib/esm/agents/team-agent.d.ts +7 -8
  89. package/lib/esm/agents/team-agent.js +10 -10
  90. package/lib/esm/agents/user-agent.d.ts +4 -4
  91. package/lib/esm/agents/user-agent.js +10 -10
  92. package/lib/esm/aigne/aigne.d.ts +13 -11
  93. package/lib/esm/aigne/aigne.js +7 -6
  94. package/lib/esm/aigne/context.d.ts +19 -8
  95. package/lib/esm/aigne/context.js +28 -8
  96. package/lib/esm/index.d.ts +2 -1
  97. package/lib/esm/index.js +2 -1
  98. package/lib/esm/loader/agent-yaml.d.ts +2 -2
  99. package/lib/esm/loader/index.d.ts +18 -11
  100. package/lib/esm/loader/index.js +8 -27
  101. package/lib/esm/memory/default-memory/default-memory-storage/index.d.ts +30 -0
  102. package/lib/esm/memory/default-memory/default-memory-storage/index.js +64 -0
  103. package/lib/esm/memory/default-memory/default-memory-storage/migrate.d.ts +7 -0
  104. package/lib/esm/memory/default-memory/default-memory-storage/migrate.js +16 -0
  105. package/lib/esm/memory/default-memory/default-memory-storage/migrations/20250523165801-init.d.ts +7 -0
  106. package/lib/esm/memory/default-memory/default-memory-storage/migrations/20250523165801-init.js +28 -0
  107. package/lib/esm/memory/default-memory/default-memory-storage/models/memory.d.ts +10 -0
  108. package/lib/esm/memory/default-memory/default-memory-storage/models/memory.js +29 -0
  109. package/lib/esm/memory/default-memory/index.d.ts +10 -0
  110. package/lib/esm/memory/{default-memory.js → default-memory/index.js} +15 -24
  111. package/lib/esm/memory/default-memory/storage.d.ts +13 -0
  112. package/lib/esm/memory/default-memory/storage.js +2 -0
  113. package/lib/esm/memory/memory.d.ts +3 -2
  114. package/lib/esm/memory/memory.js +2 -2
  115. package/lib/esm/memory/retriever.d.ts +2 -2
  116. package/lib/esm/prompt/prompt-builder.d.ts +10 -4
  117. package/lib/esm/prompt/prompt-builder.js +4 -4
  118. package/lib/esm/prompt/template.d.ts +3 -3
  119. package/lib/esm/utils/json-schema.js +1 -1
  120. package/lib/esm/utils/logger.d.ts +33 -8
  121. package/lib/esm/utils/logger.js +61 -4
  122. package/lib/esm/utils/model-utils.d.ts +1 -1
  123. package/lib/esm/utils/stream-utils.d.ts +3 -1
  124. package/lib/esm/utils/stream-utils.js +29 -1
  125. package/lib/esm/utils/type-utils.d.ts +7 -2
  126. package/package.json +4 -20
  127. package/lib/cjs/client/client.d.ts +0 -97
  128. package/lib/cjs/client/client.js +0 -87
  129. package/lib/cjs/client/index.d.ts +0 -1
  130. package/lib/cjs/client/index.js +0 -17
  131. package/lib/cjs/memory/default-memory.d.ts +0 -16
  132. package/lib/cjs/models/bedrock-chat-model.d.ts +0 -79
  133. package/lib/cjs/models/bedrock-chat-model.js +0 -303
  134. package/lib/cjs/models/claude-chat-model.d.ts +0 -114
  135. package/lib/cjs/models/claude-chat-model.js +0 -317
  136. package/lib/cjs/models/deepseek-chat-model.d.ts +0 -23
  137. package/lib/cjs/models/deepseek-chat-model.js +0 -35
  138. package/lib/cjs/models/gemini-chat-model.d.ts +0 -23
  139. package/lib/cjs/models/gemini-chat-model.js +0 -35
  140. package/lib/cjs/models/ollama-chat-model.d.ts +0 -22
  141. package/lib/cjs/models/ollama-chat-model.js +0 -34
  142. package/lib/cjs/models/open-router-chat-model.d.ts +0 -22
  143. package/lib/cjs/models/open-router-chat-model.js +0 -34
  144. package/lib/cjs/models/openai-chat-model.d.ts +0 -166
  145. package/lib/cjs/models/openai-chat-model.js +0 -415
  146. package/lib/cjs/models/xai-chat-model.d.ts +0 -21
  147. package/lib/cjs/models/xai-chat-model.js +0 -33
  148. package/lib/cjs/server/error.d.ts +0 -15
  149. package/lib/cjs/server/error.js +0 -22
  150. package/lib/cjs/server/index.d.ts +0 -2
  151. package/lib/cjs/server/index.js +0 -18
  152. package/lib/cjs/server/server.d.ts +0 -135
  153. package/lib/cjs/server/server.js +0 -187
  154. package/lib/dts/client/client.d.ts +0 -97
  155. package/lib/dts/client/index.d.ts +0 -1
  156. package/lib/dts/memory/default-memory.d.ts +0 -16
  157. package/lib/dts/models/bedrock-chat-model.d.ts +0 -79
  158. package/lib/dts/models/claude-chat-model.d.ts +0 -114
  159. package/lib/dts/models/deepseek-chat-model.d.ts +0 -23
  160. package/lib/dts/models/gemini-chat-model.d.ts +0 -23
  161. package/lib/dts/models/ollama-chat-model.d.ts +0 -22
  162. package/lib/dts/models/open-router-chat-model.d.ts +0 -22
  163. package/lib/dts/models/openai-chat-model.d.ts +0 -166
  164. package/lib/dts/models/xai-chat-model.d.ts +0 -21
  165. package/lib/dts/server/error.d.ts +0 -15
  166. package/lib/dts/server/index.d.ts +0 -2
  167. package/lib/dts/server/server.d.ts +0 -135
  168. package/lib/esm/client/client.d.ts +0 -97
  169. package/lib/esm/client/client.js +0 -83
  170. package/lib/esm/client/index.d.ts +0 -1
  171. package/lib/esm/client/index.js +0 -1
  172. package/lib/esm/memory/default-memory.d.ts +0 -16
  173. package/lib/esm/models/bedrock-chat-model.d.ts +0 -79
  174. package/lib/esm/models/bedrock-chat-model.js +0 -298
  175. package/lib/esm/models/claude-chat-model.d.ts +0 -114
  176. package/lib/esm/models/claude-chat-model.js +0 -310
  177. package/lib/esm/models/deepseek-chat-model.d.ts +0 -23
  178. package/lib/esm/models/deepseek-chat-model.js +0 -31
  179. package/lib/esm/models/gemini-chat-model.d.ts +0 -23
  180. package/lib/esm/models/gemini-chat-model.js +0 -31
  181. package/lib/esm/models/ollama-chat-model.d.ts +0 -22
  182. package/lib/esm/models/ollama-chat-model.js +0 -30
  183. package/lib/esm/models/open-router-chat-model.d.ts +0 -22
  184. package/lib/esm/models/open-router-chat-model.js +0 -30
  185. package/lib/esm/models/openai-chat-model.d.ts +0 -166
  186. package/lib/esm/models/openai-chat-model.js +0 -405
  187. package/lib/esm/models/xai-chat-model.d.ts +0 -21
  188. package/lib/esm/models/xai-chat-model.js +0 -29
  189. package/lib/esm/server/error.d.ts +0 -15
  190. package/lib/esm/server/error.js +0 -18
  191. package/lib/esm/server/index.d.ts +0 -2
  192. package/lib/esm/server/index.js +0 -2
  193. package/lib/esm/server/server.d.ts +0 -135
  194. package/lib/esm/server/server.js +0 -180
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { Agent } from "../agents/agent.js";
2
+ import { Agent } from "./agent.js";
3
3
  /**
4
4
  * ChatModel is an abstract base class for interacting with Large Language Models (LLMs).
5
5
  *
@@ -9,19 +9,19 @@ import { Agent } from "../agents/agent.js";
9
9
  *
10
10
  * @example
11
11
  * Here's how to implement a custom ChatModel:
12
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model}
12
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model}
13
13
  *
14
14
  * @example
15
15
  * Here's an example showing streaming response with readable stream:
16
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-streaming}
16
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-streaming}
17
17
  *
18
18
  * @example
19
19
  * Here's an example showing streaming response with async generator:
20
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-streaming-async-generator}
20
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-streaming-async-generator}
21
21
  *
22
22
  * @example
23
23
  * Here's an example with tool calls:
24
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
24
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
25
25
  */
26
26
  export class ChatModel extends Agent {
27
27
  constructor() {
@@ -56,23 +56,51 @@ export class ChatModel extends Agent {
56
56
  }
57
57
  }
58
58
  }
59
+ /**
60
+ * Normalizes tool names to ensure compatibility with language models
61
+ *
62
+ * This method converts tool names to a format that complies with model requirements
63
+ * by replacing hyphens and whitespace characters with underscores. The normalized
64
+ * names are used for tool calls while preserving the original names for reference.
65
+ *
66
+ * @param name - The original tool name to normalize
67
+ * @returns A promise that resolves to the normalized tool name
68
+ */
69
+ async normalizeToolName(name) {
70
+ return name.replaceAll(/[-\s]/g, "_");
71
+ }
59
72
  /**
60
73
  * Performs preprocessing operations before handling input
61
74
  *
62
75
  * Primarily checks if token usage exceeds limits, throwing an exception if limits are exceeded
63
76
  *
64
77
  * @param input Input message
65
- * @param context Execution context
78
+ * @param options Options for invoking the agent
66
79
  * @throws Error if token usage exceeds maximum limit
67
80
  */
68
- preprocess(input, context) {
69
- super.preprocess(input, context);
70
- const { limits, usage } = context;
81
+ async preprocess(input, options) {
82
+ super.preprocess(input, options);
83
+ const { limits, usage } = options.context;
71
84
  const usedTokens = usage.outputTokens + usage.inputTokens;
72
85
  if (limits?.maxTokens && usedTokens >= limits.maxTokens) {
73
86
  throw new Error(`Exceeded max tokens ${usedTokens}/${limits.maxTokens}`);
74
87
  }
75
- this.validateToolNames(input.tools);
88
+ // Automatically convert tool names to a valid format
89
+ if (input.tools?.length) {
90
+ const toolsMap = {};
91
+ const tools = [];
92
+ for (const originalTool of input.tools) {
93
+ const name = await this.normalizeToolName(originalTool.function.name);
94
+ const tool = {
95
+ ...originalTool,
96
+ function: { ...originalTool.function, name },
97
+ };
98
+ tools.push(tool);
99
+ toolsMap[name] = originalTool;
100
+ }
101
+ this.validateToolNames(tools);
102
+ Object.assign(input, { _toolsMap: toolsMap, tools });
103
+ }
76
104
  }
77
105
  /**
78
106
  * Performs postprocessing operations after handling output
@@ -81,14 +109,27 @@ export class ChatModel extends Agent {
81
109
  *
82
110
  * @param input Input message
83
111
  * @param output Output message
84
- * @param context Execution context
112
+ * @param options Options for invoking the agent
85
113
  */
86
- postprocess(input, output, context) {
87
- super.postprocess(input, output, context);
114
+ async postprocess(input, output, options) {
115
+ // Restore original tool names in the output
116
+ if (output.toolCalls?.length) {
117
+ const toolsMap = input._toolsMap;
118
+ if (toolsMap) {
119
+ for (const toolCall of output.toolCalls) {
120
+ const originalTool = toolsMap[toolCall.function.name];
121
+ if (!originalTool) {
122
+ throw new Error(`Tool "${toolCall.function.name}" not found in tools map`);
123
+ }
124
+ toolCall.function.name = originalTool.function.name;
125
+ }
126
+ }
127
+ }
128
+ super.postprocess(input, output, options);
88
129
  const { usage } = output;
89
130
  if (usage) {
90
- context.usage.outputTokens += usage.outputTokens;
91
- context.usage.inputTokens += usage.inputTokens;
131
+ options.context.usage.outputTokens += usage.outputTokens;
132
+ options.context.usage.inputTokens += usage.inputTokens;
92
133
  }
93
134
  }
94
135
  }
@@ -0,0 +1,62 @@
1
+ import type { Agent, AgentOptions, Message } from "./agent.js";
2
+ /**
3
+ * Input interface for GuideRail agents
4
+ *
5
+ * GuideRail agents receive both input and expected output, allowing them to
6
+ * validate, transform, or control the flow of messages between other agents.
7
+ */
8
+ export interface GuideRailAgentInput extends Message {
9
+ /**
10
+ * The input data to be processed
11
+ *
12
+ * This is the original message that would be sent to the target agent
13
+ */
14
+ input?: unknown;
15
+ /**
16
+ * The expected output data
17
+ *
18
+ * This is what the target agent is expected to produce, allowing
19
+ * the GuideRail agent to validate or transform the data flow
20
+ */
21
+ output?: unknown;
22
+ }
23
+ /**
24
+ * Output interface for GuideRail agents
25
+ *
26
+ * GuideRail agents can either allow the process to continue or abort it with a reason.
27
+ * This provides a mechanism for enforcing rules, validating data, and controlling
28
+ * the execution flow of the agent system.
29
+ */
30
+ export interface GuideRailAgentOutput extends Message {
31
+ /**
32
+ * Whether to abort the current process
33
+ *
34
+ * When true, the agent system should stop the current execution flow
35
+ * and prevent further processing based on this input/output pair
36
+ *
37
+ * @default false
38
+ */
39
+ abort?: boolean;
40
+ /**
41
+ * Reason for aborting the process
42
+ *
43
+ * When abort is true, this provides a human-readable explanation
44
+ * for why the process was stopped
45
+ */
46
+ reason?: string;
47
+ }
48
+ /**
49
+ * GuideRail agent type definition
50
+ *
51
+ * GuideRail agents act as validators, transformers, or controllers for the message
52
+ * flow between agents. They can enforce rules, perform safety checks, ensure data
53
+ * quality, or implement business logic validations.
54
+ *
55
+ * Use GuideRail agents when you need to:
56
+ * - Validate inputs or outputs against specific criteria
57
+ * - Enforce security or safety policies
58
+ * - Implement business rules that control agent interactions
59
+ * - Monitor and audit agent behavior
60
+ */
61
+ export type GuideRailAgent = Agent<GuideRailAgentInput, GuideRailAgentOutput>;
62
+ export declare const guideRailAgentOptions: AgentOptions<GuideRailAgentInput, GuideRailAgentOutput>;
@@ -0,0 +1,11 @@
1
+ import { z } from "zod";
2
+ export const guideRailAgentOptions = {
3
+ inputSchema: z.object({
4
+ input: z.unknown(),
5
+ output: z.unknown(),
6
+ }),
7
+ outputSchema: z.object({
8
+ abort: z.boolean().optional().describe("Whether to abort the current process"),
9
+ reason: z.string().optional().describe("Reason for aborting the process"),
10
+ }),
11
+ };
@@ -6,9 +6,8 @@ import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.j
6
6
  import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
7
7
  import type { CallToolResult, GetPromptResult, Implementation, ReadResourceResult, Request } from "@modelcontextprotocol/sdk/types.js";
8
8
  import { type ZodType, z } from "zod";
9
- import type { Context } from "../aigne/context.js";
10
9
  import { type PromiseOrValue } from "../utils/type-utils.js";
11
- import { Agent, type AgentOptions, type Message } from "./agent.js";
10
+ import { Agent, type AgentInvokeOptions, type AgentOptions, type Message } from "./agent.js";
12
11
  export interface MCPAgentOptions extends AgentOptions {
13
12
  client: Client;
14
13
  prompts?: MCPPrompt[];
@@ -150,10 +149,10 @@ export declare class MCPAgent extends Agent {
150
149
  * throws an error if called.
151
150
  *
152
151
  * @param _input Input message (unused)
153
- * @param _context Execution context (unused)
152
+ * @param _options AgentInvokeOptions (unused)
154
153
  * @throws Error This method always throws an error since MCPAgent is not directly invokable
155
154
  */
156
- process(_input: Message, _context?: Context): Promise<Message>;
155
+ process(_input: Message, _options: AgentInvokeOptions): Promise<Message>;
157
156
  /**
158
157
  * Shut down the agent and close the MCP connection.
159
158
  *
@@ -78,25 +78,25 @@ export class MCPAgent extends Agent {
78
78
  version: MCP_AGENT_CLIENT_VERSION,
79
79
  }, undefined, isSSEServerParameters(options) ? { transportCreator, ...options } : undefined);
80
80
  const transport = transportCreator();
81
- logger.mcp(`Connecting to MCP server: ${getMCPServerString(options)}`);
81
+ logger.debug(`Connecting to MCP server: ${getMCPServerString(options)}`);
82
82
  await client.connect(transport);
83
83
  const mcpServer = getMCPServerName(client);
84
84
  const { tools: isToolsAvailable, prompts: isPromptsAvailable, resources: isResourcesAvailable, } = client.getServerCapabilities() ?? {};
85
- logger.mcp(`Listing tools from ${mcpServer}`);
85
+ logger.debug(`Listing tools from ${mcpServer}`);
86
86
  const skills = isToolsAvailable
87
87
  ? await client.listTools().then(({ tools }) => {
88
- logger.mcp(`Listing tools from ${mcpServer} completed %O`, tools?.map((i) => i.name));
88
+ logger.debug(`Listing tools from ${mcpServer} completed %O`, tools?.map((i) => i.name));
89
89
  return tools.map((tool) => toolFromMCPTool(tool, { client }));
90
90
  })
91
91
  : undefined;
92
- logger.mcp(`Listing prompts from ${mcpServer}`);
92
+ logger.debug(`Listing prompts from ${mcpServer}`);
93
93
  const prompts = isPromptsAvailable
94
94
  ? await client.listPrompts().then(({ prompts }) => {
95
- logger.mcp(`Listing prompts from ${mcpServer} completed %O`, prompts?.map((i) => i.name));
95
+ logger.debug(`Listing prompts from ${mcpServer} completed %O`, prompts?.map((i) => i.name));
96
96
  return prompts.map((prompt) => promptFromMCPPrompt(prompt, { client }));
97
97
  })
98
98
  : undefined;
99
- logger.mcp(`Listing resources from ${mcpServer}`);
99
+ logger.debug(`Listing resources from ${mcpServer}`);
100
100
  // TODO: should conditionally call listResourceTemplates based on the server capabilities
101
101
  // but the capability is not correct in the current SDK version
102
102
  const resources = isResourcesAvailable
@@ -105,7 +105,7 @@ export class MCPAgent extends Agent {
105
105
  client.listResourceTemplates().catch(() => ({ resourceTemplates: [] })),
106
106
  ]).then(([{ resources }, { resourceTemplates }]) => {
107
107
  const result = [...resources, ...resourceTemplates].map((resource) => resourceFromMCPResource(resource, { client }));
108
- logger.mcp(`Listing resources from ${mcpServer} completed %O`, result.map((i) => i.name));
108
+ logger.debug(`Listing resources from ${mcpServer} completed %O`, result.map((i) => i.name));
109
109
  return result;
110
110
  })
111
111
  : undefined;
@@ -177,10 +177,10 @@ export class MCPAgent extends Agent {
177
177
  * throws an error if called.
178
178
  *
179
179
  * @param _input Input message (unused)
180
- * @param _context Execution context (unused)
180
+ * @param _options AgentInvokeOptions (unused)
181
181
  * @throws Error This method always throws an error since MCPAgent is not directly invokable
182
182
  */
183
- async process(_input, _context) {
183
+ async process(_input, _options) {
184
184
  throw new Error("Method not implemented.");
185
185
  }
186
186
  /**
@@ -228,7 +228,7 @@ class ClientWithReconnect extends Client {
228
228
  }, {
229
229
  retries: this.reconnectOptions?.maxReconnects ?? DEFAULT_MAX_RECONNECTS,
230
230
  shouldRetry: this.shouldReconnect,
231
- onFailedAttempt: (error) => logger.mcp("Reconnect attempt failed: %O", error),
231
+ onFailedAttempt: (error) => logger.error("Reconnect attempt failed: %O", error),
232
232
  });
233
233
  }
234
234
  async request(request, resultSchema, options) {
@@ -241,7 +241,7 @@ class ClientWithReconnect extends Client {
241
241
  }
242
242
  catch (error) {
243
243
  if (this.shouldReconnect(error)) {
244
- logger.mcp("Error occurred, reconnecting to MCP server: %O", error);
244
+ logger.error("Error occurred, reconnecting to MCP server: %O", error);
245
245
  await this.reconnect();
246
246
  return await super.request(request, resultSchema, mergedOptions);
247
247
  }
@@ -1,6 +1,5 @@
1
- import type { Context } from "../aigne/context.js";
2
1
  import { type PromiseOrValue } from "../utils/type-utils.js";
3
- import { Agent, type AgentOptions, type AgentProcessResult, type Message } from "./agent.js";
2
+ import { Agent, type AgentInvokeOptions, type AgentOptions, type AgentProcessResult, type Message } from "./agent.js";
4
3
  /**
5
4
  * Defines the processing modes available for a TeamAgent.
6
5
  *
@@ -89,10 +88,10 @@ export declare class TeamAgent<I extends Message, O extends Message> extends Age
89
88
  * - In parallel mode: Process input through all agents simultaneously and combine their outputs
90
89
  *
91
90
  * @param input The message to process
92
- * @param context The execution context
91
+ * @param options The invocation options
93
92
  * @returns A stream of message chunks that collectively form the response
94
93
  */
95
- process(input: I, context: Context): PromiseOrValue<AgentProcessResult<O>>;
94
+ process(input: I, options: AgentInvokeOptions): PromiseOrValue<AgentProcessResult<O>>;
96
95
  /**
97
96
  * Process input sequentially through each agent in the team.
98
97
  *
@@ -103,12 +102,12 @@ export declare class TeamAgent<I extends Message, O extends Message> extends Age
103
102
  * 4. Updates the team's agent list with any changes that occurred during processing
104
103
  *
105
104
  * @param input The message to process
106
- * @param context The execution context
105
+ * @param options The invocation options
107
106
  * @returns A stream of message chunks from all agents
108
107
  *
109
108
  * @private
110
109
  */
111
- _processSequential(input: I, context: Context): PromiseOrValue<AgentProcessResult<O>>;
110
+ _processSequential(input: I, options: AgentInvokeOptions): PromiseOrValue<AgentProcessResult<O>>;
112
111
  /**
113
112
  * Process input in parallel through all agents in the team.
114
113
  *
@@ -118,10 +117,10 @@ export declare class TeamAgent<I extends Message, O extends Message> extends Age
118
117
  * 3. Updates the team's agent list with any changes that occurred during processing
119
118
  *
120
119
  * @param input The message to process
121
- * @param context The execution context
120
+ * @param options The invocation options
122
121
  * @returns A stream of combined message chunks from all agents
123
122
  *
124
123
  * @private
125
124
  */
126
- _processParallel(input: I, context: Context): PromiseOrValue<AgentProcessResult<O>>;
125
+ _processParallel(input: I, options: AgentInvokeOptions): PromiseOrValue<AgentProcessResult<O>>;
127
126
  }
@@ -83,15 +83,15 @@ export class TeamAgent extends Agent {
83
83
  * - In parallel mode: Process input through all agents simultaneously and combine their outputs
84
84
  *
85
85
  * @param input The message to process
86
- * @param context The execution context
86
+ * @param options The invocation options
87
87
  * @returns A stream of message chunks that collectively form the response
88
88
  */
89
- process(input, context) {
89
+ process(input, options) {
90
90
  switch (this.mode) {
91
91
  case ProcessMode.sequential:
92
- return this._processSequential(input, context);
92
+ return this._processSequential(input, options);
93
93
  case ProcessMode.parallel:
94
- return this._processParallel(input, context);
94
+ return this._processParallel(input, options);
95
95
  }
96
96
  }
97
97
  /**
@@ -104,18 +104,18 @@ export class TeamAgent extends Agent {
104
104
  * 4. Updates the team's agent list with any changes that occurred during processing
105
105
  *
106
106
  * @param input The message to process
107
- * @param context The execution context
107
+ * @param options The invocation options
108
108
  * @returns A stream of message chunks from all agents
109
109
  *
110
110
  * @private
111
111
  */
112
- async *_processSequential(input, context) {
112
+ async *_processSequential(input, options) {
113
113
  const output = {};
114
114
  // Clone the agents to run, so that we can update the agents list during the loop
115
115
  const agents = [...this.skills];
116
116
  const newAgents = [];
117
117
  for (const agent of agents) {
118
- const [o, transferToAgent] = await context.invoke(agent, { ...input, ...output }, { returnActiveAgent: true, streaming: true });
118
+ const [o, transferToAgent] = await options.context.invoke(agent, { ...input, ...output }, { returnActiveAgent: true, streaming: true });
119
119
  for await (const chunk of o) {
120
120
  yield chunk;
121
121
  mergeAgentResponseChunk(output, chunk);
@@ -134,13 +134,13 @@ export class TeamAgent extends Agent {
134
134
  * 3. Updates the team's agent list with any changes that occurred during processing
135
135
  *
136
136
  * @param input The message to process
137
- * @param context The execution context
137
+ * @param options The invocation options
138
138
  * @returns A stream of combined message chunks from all agents
139
139
  *
140
140
  * @private
141
141
  */
142
- async *_processParallel(input, context) {
143
- const result = await Promise.all(this.skills.map((agent) => context.invoke(agent, input, { returnActiveAgent: true, streaming: true })));
142
+ async *_processParallel(input, options) {
143
+ const result = await Promise.all(this.skills.map((agent) => options.context.invoke(agent, input, { returnActiveAgent: true, streaming: true })));
144
144
  const streams = result.map((i) => i[0]);
145
145
  const read = async (index, reader) => {
146
146
  const promise = reader.read();
@@ -1,7 +1,7 @@
1
1
  import { ReadableStream } from "node:stream/web";
2
2
  import type { Context } from "../aigne/context.js";
3
3
  import { type MessagePayload } from "../aigne/message-queue.js";
4
- import { Agent, type AgentOptions, type AgentProcessResult, type FunctionAgentFn, type Message } from "./agent.js";
4
+ import { Agent, type AgentInvokeOptions, type AgentOptions, type AgentProcessResult, type FunctionAgentFn, type Message } from "./agent.js";
5
5
  export interface UserAgentOptions<I extends Message = Message, O extends Message = Message> extends AgentOptions<I, O> {
6
6
  context: Context;
7
7
  process?: FunctionAgentFn<I, O>;
@@ -14,14 +14,14 @@ export declare class UserAgent<I extends Message = Message, O extends Message =
14
14
  private _process?;
15
15
  private activeAgent?;
16
16
  protected subscribeToTopics(context: Pick<Context, "subscribe">): void;
17
- protected publishToTopics(output: O, context: Context): Promise<void>;
17
+ protected publishToTopics(output: O, options: AgentInvokeOptions): Promise<void>;
18
18
  invoke: Agent<I, O>["invoke"];
19
- process(input: I, context: Context): Promise<AgentProcessResult<O>>;
19
+ process(input: I, options: AgentInvokeOptions): Promise<AgentProcessResult<O>>;
20
20
  publish: Context["publish"];
21
21
  subscribe: Context["subscribe"];
22
22
  unsubscribe: Context["unsubscribe"];
23
23
  get stream(): ReadableStream<MessagePayload & {
24
24
  topic: string;
25
25
  }>;
26
- protected checkAgentInvokesUsage(_context: Context): void;
26
+ protected checkAgentInvokesUsage(_options: AgentInvokeOptions): void;
27
27
  }
@@ -19,21 +19,21 @@ export class UserAgent extends Agent {
19
19
  if (this._process)
20
20
  super.subscribeToTopics(context);
21
21
  }
22
- async publishToTopics(output, context) {
22
+ async publishToTopics(output, options) {
23
23
  if (this._process)
24
- super.publishToTopics(output, context);
24
+ super.publishToTopics(output, options);
25
25
  }
26
- invoke = ((input, context, options) => {
27
- if (!context)
26
+ invoke = ((input, options = {}) => {
27
+ if (!options.context)
28
28
  this.context = this.context.newContext({ reset: true });
29
- return super.invoke(input, context ?? this.context, options);
29
+ return super.invoke(input, { ...options, context: this.context });
30
30
  });
31
- async process(input, context) {
31
+ async process(input, options) {
32
32
  if (this._process) {
33
- return this._process(input, context);
33
+ return this._process(input, options);
34
34
  }
35
35
  if (this.activeAgent) {
36
- const [output, agent] = await context.invoke(this.activeAgent, input, {
36
+ const [output, agent] = await options.context.invoke(this.activeAgent, input, {
37
37
  returnActiveAgent: true,
38
38
  streaming: true,
39
39
  });
@@ -44,7 +44,7 @@ export class UserAgent extends Agent {
44
44
  }
45
45
  const publicTopic = typeof this.publishTopic === "function" ? await this.publishTopic(input) : this.publishTopic;
46
46
  if (publicTopic?.length) {
47
- context.publish(publicTopic, input);
47
+ options.context.publish(publicTopic, input);
48
48
  if (this.subscribeTopic) {
49
49
  return this.subscribe(this.subscribeTopic).then((res) => res.message);
50
50
  }
@@ -77,7 +77,7 @@ export class UserAgent extends Agent {
77
77
  },
78
78
  });
79
79
  }
80
- checkAgentInvokesUsage(_context) {
80
+ checkAgentInvokesUsage(_options) {
81
81
  // ignore calls usage check for UserAgent
82
82
  }
83
83
  }
@@ -1,7 +1,8 @@
1
1
  import { Agent, type AgentResponse, type AgentResponseStream, type Message } from "../agents/agent.js";
2
+ import { ChatModel } from "../agents/chat-model.js";
2
3
  import type { UserAgent } from "../agents/user-agent.js";
3
- import { ChatModel } from "../models/chat-model.js";
4
- import { AIGNEContext, type InvokeOptions } from "./context.js";
4
+ import { type LoadOptions } from "../loader/index.js";
5
+ import { AIGNEContext, type Context, type InvokeOptions, type UserContext } from "./context.js";
5
6
  import { type MessagePayload, MessageQueue, type MessageQueueListener, type Unsubscribe } from "./message-queue.js";
6
7
  import type { ContextLimits } from "./usage.js";
7
8
  /**
@@ -45,7 +46,7 @@ export interface AIGNEOptions {
45
46
  * Here's an example of how to use AIGNE with streaming response:
46
47
  * {@includeCode ../../test/aigne/aigne.test.ts#example-streaming}
47
48
  */
48
- export declare class AIGNE {
49
+ export declare class AIGNE<U extends UserContext = UserContext> {
49
50
  /**
50
51
  * Loads an AIGNE instance from a directory containing an aigne.yaml file and agent definitions.
51
52
  * This static method provides a convenient way to initialize an AIGNE system from configuration files.
@@ -54,7 +55,7 @@ export declare class AIGNE {
54
55
  * @param options - Options to override the loaded configuration.
55
56
  * @returns A fully initialized AIGNE instance with configured agents and skills.
56
57
  */
57
- static load(path: string, options?: AIGNEOptions): Promise<AIGNE>;
58
+ static load(path: string, options: AIGNEOptions & Pick<LoadOptions, "models">): Promise<AIGNE>;
58
59
  /**
59
60
  * Creates a new AIGNE instance with the specified options.
60
61
  *
@@ -110,7 +111,7 @@ export declare class AIGNE {
110
111
  *
111
112
  * @returns A new AIGNEContext instance bound to this AIGNE.
112
113
  */
113
- newContext(): AIGNEContext;
114
+ newContext(options?: Partial<Context>): AIGNEContext;
114
115
  /**
115
116
  * Creates a user agent for consistent interactions with a specified agent.
116
117
  * This method allows you to create a wrapper around an agent for repeated invocations.
@@ -133,7 +134,7 @@ export declare class AIGNE {
133
134
  * @param options.streaming - Must be false to return a response stream
134
135
  * @returns A promise resolving to a tuple containing the agent's response and the final active agent
135
136
  */
136
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions & {
137
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions<U> & {
137
138
  returnActiveAgent: true;
138
139
  streaming?: false;
139
140
  }): Promise<[O, Agent]>;
@@ -147,7 +148,7 @@ export declare class AIGNE {
147
148
  * @param options.streaming - Must be true to return a response stream
148
149
  * @returns A promise resolving to a tuple containing the agent's response stream and a promise for the final agent
149
150
  */
150
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions & {
151
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions<U> & {
151
152
  returnActiveAgent: true;
152
153
  streaming: true;
153
154
  }): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
@@ -164,7 +165,7 @@ export declare class AIGNE {
164
165
  * Here's a simple example of how to invoke an agent:
165
166
  * {@includeCode ../../test/aigne/aigne.test.ts#example-simple}
166
167
  */
167
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options?: InvokeOptions & {
168
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options?: InvokeOptions<U> & {
168
169
  returnActiveAgent?: false;
169
170
  streaming?: false;
170
171
  }): Promise<O>;
@@ -181,7 +182,7 @@ export declare class AIGNE {
181
182
  * Here's an example of how to invoke an agent with streaming response:
182
183
  * {@includeCode ../../test/aigne/aigne.test.ts#example-streaming}
183
184
  */
184
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions & {
185
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions<U> & {
185
186
  returnActiveAgent?: false;
186
187
  streaming: true;
187
188
  }): Promise<AgentResponseStream<O>>;
@@ -195,7 +196,7 @@ export declare class AIGNE {
195
196
  * @returns Either a UserAgent (when no message provided) or a promise resolving to the agent's response
196
197
  * with optional active agent information based on the provided options
197
198
  */
198
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I | string, options?: InvokeOptions): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
199
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I | string, options?: InvokeOptions<U>): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
199
200
  /**
200
201
  * Publishes a message to the message queue for inter-agent communication.
201
202
  * This method broadcasts a message to all subscribers of the specified topic(s).
@@ -203,12 +204,13 @@ export declare class AIGNE {
203
204
  *
204
205
  * @param topic - The topic or array of topics to publish the message to
205
206
  * @param payload - The message payload to be delivered to subscribers
207
+ * @param options - Optional configuration parameters for the publish operation
206
208
  *
207
209
  * @example
208
210
  * Here's an example of how to publish a message:
209
211
  * {@includeCode ../../test/aigne/aigne.test.ts#example-publish-message}
210
212
  */
211
- publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message | string): void;
213
+ publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message | string, options?: InvokeOptions<U>): void;
212
214
  /**
213
215
  * Subscribes to receive the next message on a specific topic.
214
216
  * This overload returns a Promise that resolves with the next message published to the topic.
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { Agent, } from "../agents/agent.js";
3
+ import { ChatModel } from "../agents/chat-model.js";
3
4
  import { load } from "../loader/index.js";
4
- import { ChatModel } from "../models/chat-model.js";
5
5
  import { checkArguments, createAccessorArray } from "../utils/type-utils.js";
6
6
  import { AIGNEContext } from "./context.js";
7
7
  import { MessageQueue, } from "./message-queue.js";
@@ -27,7 +27,7 @@ export class AIGNE {
27
27
  * @returns A fully initialized AIGNE instance with configured agents and skills.
28
28
  */
29
29
  static async load(path, options) {
30
- const { model, agents, skills, ...aigne } = await load({ path });
30
+ const { model, agents, skills, ...aigne } = await load({ models: options.models, path });
31
31
  return new AIGNE({
32
32
  ...options,
33
33
  model: options?.model || model,
@@ -106,8 +106,8 @@ export class AIGNE {
106
106
  *
107
107
  * @returns A new AIGNEContext instance bound to this AIGNE.
108
108
  */
109
- newContext() {
110
- return new AIGNEContext(this);
109
+ newContext(options) {
110
+ return new AIGNEContext(this, options);
111
111
  }
112
112
  invoke(agent, message, options) {
113
113
  return new AIGNEContext(this).invoke(agent, message, options);
@@ -119,13 +119,14 @@ export class AIGNE {
119
119
  *
120
120
  * @param topic - The topic or array of topics to publish the message to
121
121
  * @param payload - The message payload to be delivered to subscribers
122
+ * @param options - Optional configuration parameters for the publish operation
122
123
  *
123
124
  * @example
124
125
  * Here's an example of how to publish a message:
125
126
  * {@includeCode ../../test/aigne/aigne.test.ts#example-publish-message}
126
127
  */
127
- publish(topic, payload) {
128
- return new AIGNEContext(this).publish(topic, payload);
128
+ publish(topic, payload, options) {
129
+ return new AIGNEContext(this).publish(topic, payload, options);
129
130
  }
130
131
  subscribe(topic, listener) {
131
132
  return this.messageQueue.subscribe(topic, listener);