@aigne/core 1.15.0 → 1.16.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 (141) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +9 -7
  3. package/README.zh.md +9 -7
  4. package/lib/cjs/agents/agent.d.ts +129 -6
  5. package/lib/cjs/agents/agent.js +112 -20
  6. package/lib/cjs/agents/ai-agent.d.ts +3 -2
  7. package/lib/cjs/agents/ai-agent.js +10 -6
  8. package/lib/{esm/models → cjs/agents}/chat-model.d.ts +24 -13
  9. package/lib/cjs/{models → agents}/chat-model.js +48 -7
  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.js +9 -9
  13. package/lib/cjs/aigne/aigne.d.ts +3 -2
  14. package/lib/cjs/aigne/aigne.js +2 -2
  15. package/lib/cjs/aigne/context.d.ts +2 -1
  16. package/lib/cjs/aigne/context.js +7 -0
  17. package/lib/cjs/index.d.ts +1 -1
  18. package/lib/cjs/index.js +1 -1
  19. package/lib/cjs/loader/agent-yaml.d.ts +1 -1
  20. package/lib/cjs/loader/index.d.ts +18 -11
  21. package/lib/cjs/loader/index.js +8 -27
  22. package/lib/cjs/memory/retriever.d.ts +2 -2
  23. package/lib/cjs/prompt/prompt-builder.d.ts +3 -3
  24. package/lib/cjs/prompt/template.d.ts +3 -3
  25. package/lib/cjs/utils/json-schema.js +1 -1
  26. package/lib/cjs/utils/logger.d.ts +33 -8
  27. package/lib/cjs/utils/logger.js +63 -5
  28. package/lib/cjs/utils/model-utils.d.ts +1 -1
  29. package/lib/cjs/utils/stream-utils.d.ts +3 -1
  30. package/lib/cjs/utils/stream-utils.js +31 -1
  31. package/lib/cjs/utils/type-utils.d.ts +5 -0
  32. package/lib/dts/agents/agent.d.ts +129 -6
  33. package/lib/dts/agents/ai-agent.d.ts +3 -2
  34. package/lib/{cjs/models → dts/agents}/chat-model.d.ts +24 -13
  35. package/lib/dts/agents/guide-rail-agent.d.ts +62 -0
  36. package/lib/dts/aigne/aigne.d.ts +3 -2
  37. package/lib/dts/aigne/context.d.ts +2 -1
  38. package/lib/dts/index.d.ts +1 -1
  39. package/lib/dts/loader/agent-yaml.d.ts +1 -1
  40. package/lib/dts/loader/index.d.ts +18 -11
  41. package/lib/dts/memory/retriever.d.ts +2 -2
  42. package/lib/dts/prompt/prompt-builder.d.ts +3 -3
  43. package/lib/dts/prompt/template.d.ts +3 -3
  44. package/lib/dts/utils/logger.d.ts +33 -8
  45. package/lib/dts/utils/model-utils.d.ts +1 -1
  46. package/lib/dts/utils/stream-utils.d.ts +3 -1
  47. package/lib/dts/utils/type-utils.d.ts +5 -0
  48. package/lib/esm/agents/agent.d.ts +129 -6
  49. package/lib/esm/agents/agent.js +112 -20
  50. package/lib/esm/agents/ai-agent.d.ts +3 -2
  51. package/lib/esm/agents/ai-agent.js +10 -6
  52. package/lib/{dts/models → esm/agents}/chat-model.d.ts +24 -13
  53. package/lib/esm/{models → agents}/chat-model.js +48 -7
  54. package/lib/esm/agents/guide-rail-agent.d.ts +62 -0
  55. package/lib/esm/agents/guide-rail-agent.js +11 -0
  56. package/lib/esm/agents/mcp-agent.js +9 -9
  57. package/lib/esm/aigne/aigne.d.ts +3 -2
  58. package/lib/esm/aigne/aigne.js +2 -2
  59. package/lib/esm/aigne/context.d.ts +2 -1
  60. package/lib/esm/aigne/context.js +7 -0
  61. package/lib/esm/index.d.ts +1 -1
  62. package/lib/esm/index.js +1 -1
  63. package/lib/esm/loader/agent-yaml.d.ts +1 -1
  64. package/lib/esm/loader/index.d.ts +18 -11
  65. package/lib/esm/loader/index.js +8 -27
  66. package/lib/esm/memory/retriever.d.ts +2 -2
  67. package/lib/esm/prompt/prompt-builder.d.ts +3 -3
  68. package/lib/esm/prompt/template.d.ts +3 -3
  69. package/lib/esm/utils/json-schema.js +1 -1
  70. package/lib/esm/utils/logger.d.ts +33 -8
  71. package/lib/esm/utils/logger.js +61 -4
  72. package/lib/esm/utils/model-utils.d.ts +1 -1
  73. package/lib/esm/utils/stream-utils.d.ts +3 -1
  74. package/lib/esm/utils/stream-utils.js +29 -1
  75. package/lib/esm/utils/type-utils.d.ts +5 -0
  76. package/package.json +1 -20
  77. package/lib/cjs/client/client.d.ts +0 -97
  78. package/lib/cjs/client/client.js +0 -87
  79. package/lib/cjs/client/index.d.ts +0 -1
  80. package/lib/cjs/client/index.js +0 -17
  81. package/lib/cjs/models/bedrock-chat-model.d.ts +0 -79
  82. package/lib/cjs/models/bedrock-chat-model.js +0 -303
  83. package/lib/cjs/models/claude-chat-model.d.ts +0 -114
  84. package/lib/cjs/models/claude-chat-model.js +0 -317
  85. package/lib/cjs/models/deepseek-chat-model.d.ts +0 -23
  86. package/lib/cjs/models/deepseek-chat-model.js +0 -35
  87. package/lib/cjs/models/gemini-chat-model.d.ts +0 -23
  88. package/lib/cjs/models/gemini-chat-model.js +0 -35
  89. package/lib/cjs/models/ollama-chat-model.d.ts +0 -22
  90. package/lib/cjs/models/ollama-chat-model.js +0 -34
  91. package/lib/cjs/models/open-router-chat-model.d.ts +0 -22
  92. package/lib/cjs/models/open-router-chat-model.js +0 -34
  93. package/lib/cjs/models/openai-chat-model.d.ts +0 -166
  94. package/lib/cjs/models/openai-chat-model.js +0 -415
  95. package/lib/cjs/models/xai-chat-model.d.ts +0 -21
  96. package/lib/cjs/models/xai-chat-model.js +0 -33
  97. package/lib/cjs/server/error.d.ts +0 -15
  98. package/lib/cjs/server/error.js +0 -22
  99. package/lib/cjs/server/index.d.ts +0 -2
  100. package/lib/cjs/server/index.js +0 -18
  101. package/lib/cjs/server/server.d.ts +0 -135
  102. package/lib/cjs/server/server.js +0 -187
  103. package/lib/dts/client/client.d.ts +0 -97
  104. package/lib/dts/client/index.d.ts +0 -1
  105. package/lib/dts/models/bedrock-chat-model.d.ts +0 -79
  106. package/lib/dts/models/claude-chat-model.d.ts +0 -114
  107. package/lib/dts/models/deepseek-chat-model.d.ts +0 -23
  108. package/lib/dts/models/gemini-chat-model.d.ts +0 -23
  109. package/lib/dts/models/ollama-chat-model.d.ts +0 -22
  110. package/lib/dts/models/open-router-chat-model.d.ts +0 -22
  111. package/lib/dts/models/openai-chat-model.d.ts +0 -166
  112. package/lib/dts/models/xai-chat-model.d.ts +0 -21
  113. package/lib/dts/server/error.d.ts +0 -15
  114. package/lib/dts/server/index.d.ts +0 -2
  115. package/lib/dts/server/server.d.ts +0 -135
  116. package/lib/esm/client/client.d.ts +0 -97
  117. package/lib/esm/client/client.js +0 -83
  118. package/lib/esm/client/index.d.ts +0 -1
  119. package/lib/esm/client/index.js +0 -1
  120. package/lib/esm/models/bedrock-chat-model.d.ts +0 -79
  121. package/lib/esm/models/bedrock-chat-model.js +0 -298
  122. package/lib/esm/models/claude-chat-model.d.ts +0 -114
  123. package/lib/esm/models/claude-chat-model.js +0 -310
  124. package/lib/esm/models/deepseek-chat-model.d.ts +0 -23
  125. package/lib/esm/models/deepseek-chat-model.js +0 -31
  126. package/lib/esm/models/gemini-chat-model.d.ts +0 -23
  127. package/lib/esm/models/gemini-chat-model.js +0 -31
  128. package/lib/esm/models/ollama-chat-model.d.ts +0 -22
  129. package/lib/esm/models/ollama-chat-model.js +0 -30
  130. package/lib/esm/models/open-router-chat-model.d.ts +0 -22
  131. package/lib/esm/models/open-router-chat-model.js +0 -30
  132. package/lib/esm/models/openai-chat-model.d.ts +0 -166
  133. package/lib/esm/models/openai-chat-model.js +0 -405
  134. package/lib/esm/models/xai-chat-model.d.ts +0 -21
  135. package/lib/esm/models/xai-chat-model.js +0 -29
  136. package/lib/esm/server/error.d.ts +0 -15
  137. package/lib/esm/server/error.js +0 -18
  138. package/lib/esm/server/index.d.ts +0 -2
  139. package/lib/esm/server/index.js +0 -2
  140. package/lib/esm/server/server.d.ts +0 -135
  141. package/lib/esm/server/server.js +0 -180
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ChatModel = void 0;
4
4
  const zod_1 = require("zod");
5
- const agent_js_1 = require("../agents/agent.js");
5
+ const agent_js_1 = require("./agent.js");
6
6
  /**
7
7
  * ChatModel is an abstract base class for interacting with Large Language Models (LLMs).
8
8
  *
@@ -12,19 +12,19 @@ const agent_js_1 = require("../agents/agent.js");
12
12
  *
13
13
  * @example
14
14
  * Here's how to implement a custom ChatModel:
15
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model}
15
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model}
16
16
  *
17
17
  * @example
18
18
  * Here's an example showing streaming response with readable stream:
19
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-streaming}
19
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-streaming}
20
20
  *
21
21
  * @example
22
22
  * Here's an example showing streaming response with async generator:
23
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-streaming-async-generator}
23
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-streaming-async-generator}
24
24
  *
25
25
  * @example
26
26
  * Here's an example with tool calls:
27
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
27
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
28
28
  */
29
29
  class ChatModel extends agent_js_1.Agent {
30
30
  constructor() {
@@ -59,6 +59,19 @@ class ChatModel extends agent_js_1.Agent {
59
59
  }
60
60
  }
61
61
  }
62
+ /**
63
+ * Normalizes tool names to ensure compatibility with language models
64
+ *
65
+ * This method converts tool names to a format that complies with model requirements
66
+ * by replacing hyphens and whitespace characters with underscores. The normalized
67
+ * names are used for tool calls while preserving the original names for reference.
68
+ *
69
+ * @param name - The original tool name to normalize
70
+ * @returns A promise that resolves to the normalized tool name
71
+ */
72
+ async normalizeToolName(name) {
73
+ return name.replaceAll(/[-\s]/g, "_");
74
+ }
62
75
  /**
63
76
  * Performs preprocessing operations before handling input
64
77
  *
@@ -68,14 +81,29 @@ class ChatModel extends agent_js_1.Agent {
68
81
  * @param context Execution context
69
82
  * @throws Error if token usage exceeds maximum limit
70
83
  */
71
- preprocess(input, context) {
84
+ async preprocess(input, context) {
72
85
  super.preprocess(input, context);
73
86
  const { limits, usage } = context;
74
87
  const usedTokens = usage.outputTokens + usage.inputTokens;
75
88
  if (limits?.maxTokens && usedTokens >= limits.maxTokens) {
76
89
  throw new Error(`Exceeded max tokens ${usedTokens}/${limits.maxTokens}`);
77
90
  }
78
- this.validateToolNames(input.tools);
91
+ // Automatically convert tool names to a valid format
92
+ if (input.tools?.length) {
93
+ const toolsMap = {};
94
+ const tools = [];
95
+ for (const originalTool of input.tools) {
96
+ const name = await this.normalizeToolName(originalTool.function.name);
97
+ const tool = {
98
+ ...originalTool,
99
+ function: { ...originalTool.function, name },
100
+ };
101
+ tools.push(tool);
102
+ toolsMap[name] = originalTool;
103
+ }
104
+ this.validateToolNames(tools);
105
+ Object.assign(input, { _toolsMap: toolsMap, tools });
106
+ }
79
107
  }
80
108
  /**
81
109
  * Performs postprocessing operations after handling output
@@ -87,6 +115,19 @@ class ChatModel extends agent_js_1.Agent {
87
115
  * @param context Execution context
88
116
  */
89
117
  postprocess(input, output, context) {
118
+ // Restore original tool names in the output
119
+ if (output.toolCalls?.length) {
120
+ const toolsMap = input._toolsMap;
121
+ if (toolsMap) {
122
+ for (const toolCall of output.toolCalls) {
123
+ const originalTool = toolsMap[toolCall.function.name];
124
+ if (!originalTool) {
125
+ throw new Error(`Tool "${toolCall.function.name}" not found in tools map`);
126
+ }
127
+ toolCall.function.name = originalTool.function.name;
128
+ }
129
+ }
130
+ }
90
131
  super.postprocess(input, output, context);
91
132
  const { usage } = output;
92
133
  if (usage) {
@@ -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,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.guideRailAgentOptions = void 0;
4
+ const zod_1 = require("zod");
5
+ exports.guideRailAgentOptions = {
6
+ inputSchema: zod_1.z.object({
7
+ input: zod_1.z.unknown(),
8
+ output: zod_1.z.unknown(),
9
+ }),
10
+ outputSchema: zod_1.z.object({
11
+ abort: zod_1.z.boolean().optional().describe("Whether to abort the current process"),
12
+ reason: zod_1.z.string().optional().describe("Reason for aborting the process"),
13
+ }),
14
+ };
@@ -84,25 +84,25 @@ class MCPAgent extends agent_js_1.Agent {
84
84
  version: MCP_AGENT_CLIENT_VERSION,
85
85
  }, undefined, isSSEServerParameters(options) ? { transportCreator, ...options } : undefined);
86
86
  const transport = transportCreator();
87
- logger_js_1.logger.mcp(`Connecting to MCP server: ${getMCPServerString(options)}`);
87
+ logger_js_1.logger.debug(`Connecting to MCP server: ${getMCPServerString(options)}`);
88
88
  await client.connect(transport);
89
89
  const mcpServer = getMCPServerName(client);
90
90
  const { tools: isToolsAvailable, prompts: isPromptsAvailable, resources: isResourcesAvailable, } = client.getServerCapabilities() ?? {};
91
- logger_js_1.logger.mcp(`Listing tools from ${mcpServer}`);
91
+ logger_js_1.logger.debug(`Listing tools from ${mcpServer}`);
92
92
  const skills = isToolsAvailable
93
93
  ? await client.listTools().then(({ tools }) => {
94
- logger_js_1.logger.mcp(`Listing tools from ${mcpServer} completed %O`, tools?.map((i) => i.name));
94
+ logger_js_1.logger.debug(`Listing tools from ${mcpServer} completed %O`, tools?.map((i) => i.name));
95
95
  return tools.map((tool) => (0, mcp_utils_js_1.toolFromMCPTool)(tool, { client }));
96
96
  })
97
97
  : undefined;
98
- logger_js_1.logger.mcp(`Listing prompts from ${mcpServer}`);
98
+ logger_js_1.logger.debug(`Listing prompts from ${mcpServer}`);
99
99
  const prompts = isPromptsAvailable
100
100
  ? await client.listPrompts().then(({ prompts }) => {
101
- logger_js_1.logger.mcp(`Listing prompts from ${mcpServer} completed %O`, prompts?.map((i) => i.name));
101
+ logger_js_1.logger.debug(`Listing prompts from ${mcpServer} completed %O`, prompts?.map((i) => i.name));
102
102
  return prompts.map((prompt) => (0, mcp_utils_js_1.promptFromMCPPrompt)(prompt, { client }));
103
103
  })
104
104
  : undefined;
105
- logger_js_1.logger.mcp(`Listing resources from ${mcpServer}`);
105
+ logger_js_1.logger.debug(`Listing resources from ${mcpServer}`);
106
106
  // TODO: should conditionally call listResourceTemplates based on the server capabilities
107
107
  // but the capability is not correct in the current SDK version
108
108
  const resources = isResourcesAvailable
@@ -111,7 +111,7 @@ class MCPAgent extends agent_js_1.Agent {
111
111
  client.listResourceTemplates().catch(() => ({ resourceTemplates: [] })),
112
112
  ]).then(([{ resources }, { resourceTemplates }]) => {
113
113
  const result = [...resources, ...resourceTemplates].map((resource) => (0, mcp_utils_js_1.resourceFromMCPResource)(resource, { client }));
114
- logger_js_1.logger.mcp(`Listing resources from ${mcpServer} completed %O`, result.map((i) => i.name));
114
+ logger_js_1.logger.debug(`Listing resources from ${mcpServer} completed %O`, result.map((i) => i.name));
115
115
  return result;
116
116
  })
117
117
  : undefined;
@@ -235,7 +235,7 @@ class ClientWithReconnect extends index_js_1.Client {
235
235
  }, {
236
236
  retries: this.reconnectOptions?.maxReconnects ?? DEFAULT_MAX_RECONNECTS,
237
237
  shouldRetry: this.shouldReconnect,
238
- onFailedAttempt: (error) => logger_js_1.logger.mcp("Reconnect attempt failed: %O", error),
238
+ onFailedAttempt: (error) => logger_js_1.logger.error("Reconnect attempt failed: %O", error),
239
239
  });
240
240
  }
241
241
  async request(request, resultSchema, options) {
@@ -248,7 +248,7 @@ class ClientWithReconnect extends index_js_1.Client {
248
248
  }
249
249
  catch (error) {
250
250
  if (this.shouldReconnect(error)) {
251
- logger_js_1.logger.mcp("Error occurred, reconnecting to MCP server: %O", error);
251
+ logger_js_1.logger.error("Error occurred, reconnecting to MCP server: %O", error);
252
252
  await this.reconnect();
253
253
  return await super.request(request, resultSchema, mergedOptions);
254
254
  }
@@ -1,6 +1,7 @@
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 { type LoadOptions } from "../loader/index.js";
4
5
  import { AIGNEContext, type InvokeOptions } 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";
@@ -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
  *
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AIGNE = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const agent_js_1 = require("../agents/agent.js");
6
+ const chat_model_js_1 = require("../agents/chat-model.js");
6
7
  const index_js_1 = require("../loader/index.js");
7
- const chat_model_js_1 = require("../models/chat-model.js");
8
8
  const type_utils_js_1 = require("../utils/type-utils.js");
9
9
  const context_js_1 = require("./context.js");
10
10
  const message_queue_js_1 = require("./message-queue.js");
@@ -30,7 +30,7 @@ class AIGNE {
30
30
  * @returns A fully initialized AIGNE instance with configured agents and skills.
31
31
  */
32
32
  static async load(path, options) {
33
- const { model, agents, skills, ...aigne } = await (0, index_js_1.load)({ path });
33
+ const { model, agents, skills, ...aigne } = await (0, index_js_1.load)({ models: options.models, path });
34
34
  return new AIGNE({
35
35
  ...options,
36
36
  model: options?.model || model,
@@ -1,7 +1,7 @@
1
1
  import EventEmitter from "node:events";
2
2
  import { Agent, type AgentInvokeOptions, type AgentProcessAsyncGenerator, type AgentResponse, type AgentResponseStream, type Message } from "../agents/agent.js";
3
+ import type { ChatModel } from "../agents/chat-model.js";
3
4
  import { UserAgent } from "../agents/user-agent.js";
4
- import type { ChatModel } from "../models/chat-model.js";
5
5
  import { type OmitPropertiesFromArrayFirstElement } from "../utils/type-utils.js";
6
6
  import type { Args, Listener, TypedEventEmitter } from "../utils/typed-event-emtter.js";
7
7
  import { type MessagePayload, MessageQueue, type MessageQueueListener, type Unsubscribe } from "./message-queue.js";
@@ -41,6 +41,7 @@ export type ContextEmitEventMap = {
41
41
  export interface InvokeOptions extends AgentInvokeOptions {
42
42
  returnActiveAgent?: boolean;
43
43
  disableTransfer?: boolean;
44
+ sourceAgent?: Agent;
44
45
  }
45
46
  /**
46
47
  * @hidden
@@ -174,6 +174,13 @@ class AIGNEContextInternal {
174
174
  let output;
175
175
  for (;;) {
176
176
  const result = {};
177
+ if (options?.sourceAgent && activeAgent !== options.sourceAgent) {
178
+ options.sourceAgent.hooks.onHandoff?.({
179
+ source: options.sourceAgent,
180
+ target: activeAgent,
181
+ input,
182
+ });
183
+ }
177
184
  const stream = await activeAgent.invoke(input, context, { streaming: true });
178
185
  for await (const value of stream) {
179
186
  if (value.delta.text) {
@@ -5,6 +5,6 @@ export * from "./agents/team-agent.js";
5
5
  export * from "./agents/types.js";
6
6
  export * from "./agents/user-agent.js";
7
7
  export * from "./aigne/index.js";
8
- export * from "./models/chat-model.js";
8
+ export * from "./agents/chat-model.js";
9
9
  export * from "./prompt/prompt-builder.js";
10
10
  export * from "./prompt/template.js";
package/lib/cjs/index.js CHANGED
@@ -21,6 +21,6 @@ __exportStar(require("./agents/team-agent.js"), exports);
21
21
  __exportStar(require("./agents/types.js"), exports);
22
22
  __exportStar(require("./agents/user-agent.js"), exports);
23
23
  __exportStar(require("./aigne/index.js"), exports);
24
- __exportStar(require("./models/chat-model.js"), exports);
24
+ __exportStar(require("./agents/chat-model.js"), exports);
25
25
  __exportStar(require("./prompt/prompt-builder.js"), exports);
26
26
  __exportStar(require("./prompt/template.js"), exports);
@@ -14,13 +14,13 @@ export declare function loadAgentFromYamlFile(path: string): Promise<{
14
14
  }, {
15
15
  [x: string]: any;
16
16
  }> | undefined;
17
- toolChoice?: AIAgentToolChoice | undefined;
18
17
  outputSchema?: ZodObject<Record<string, ZodType<any, z.ZodTypeDef, any>>, z.UnknownKeysParam, z.ZodTypeAny, {
19
18
  [x: string]: any;
20
19
  }, {
21
20
  [x: string]: any;
22
21
  }> | undefined;
23
22
  outputKey?: string | undefined;
23
+ toolChoice?: AIAgentToolChoice | undefined;
24
24
  } | {
25
25
  type: "mcp";
26
26
  url?: string | undefined;
@@ -1,7 +1,14 @@
1
+ import type { Camelize } from "camelize-ts";
1
2
  import { z } from "zod";
2
3
  import { type Agent } from "../agents/agent.js";
3
- import type { ChatModel, ChatModelOptions } from "../models/chat-model.js";
4
+ import type { ChatModel, ChatModelOptions } from "../agents/chat-model.js";
4
5
  export interface LoadOptions {
6
+ models: {
7
+ new (parameters: {
8
+ model?: string;
9
+ modelOptions?: ChatModelOptions;
10
+ }): ChatModel;
11
+ }[];
5
12
  path: string;
6
13
  }
7
14
  export declare function load(options: LoadOptions): Promise<{
@@ -15,12 +22,12 @@ export declare function load(options: LoadOptions): Promise<{
15
22
  temperature?: number | null | undefined;
16
23
  provider?: string | null | undefined;
17
24
  top_p?: number | null | undefined;
18
- frequent_penalty?: number | null | undefined;
25
+ frequency_penalty?: number | null | undefined;
19
26
  presence_penalty?: number | null | undefined;
20
27
  } | null | undefined;
21
28
  }>;
22
29
  export declare function loadAgent(path: string): Promise<Agent>;
23
- export declare function loadModel(model?: z.infer<typeof aigneFileSchema>["chat_model"], modelOptions?: ChatModelOptions): Promise<ChatModel | undefined>;
30
+ export declare function loadModel(models: LoadOptions["models"], model?: Camelize<z.infer<typeof aigneFileSchema>["chat_model"]>, modelOptions?: ChatModelOptions): Promise<ChatModel | undefined>;
24
31
  declare const aigneFileSchema: z.ZodObject<{
25
32
  name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
26
33
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -29,35 +36,35 @@ declare const aigneFileSchema: z.ZodObject<{
29
36
  name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
30
37
  temperature: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
31
38
  top_p: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
32
- frequent_penalty: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
39
+ frequency_penalty: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
33
40
  presence_penalty: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
34
41
  }, "strip", z.ZodTypeAny, {
35
42
  name?: string | null | undefined;
36
43
  temperature?: number | null | undefined;
37
44
  provider?: string | null | undefined;
38
45
  top_p?: number | null | undefined;
39
- frequent_penalty?: number | null | undefined;
46
+ frequency_penalty?: number | null | undefined;
40
47
  presence_penalty?: number | null | undefined;
41
48
  }, {
42
49
  name?: string | null | undefined;
43
50
  temperature?: number | null | undefined;
44
51
  provider?: string | null | undefined;
45
52
  top_p?: number | null | undefined;
46
- frequent_penalty?: number | null | undefined;
53
+ frequency_penalty?: number | null | undefined;
47
54
  presence_penalty?: number | null | undefined;
48
55
  }>]>>>, {
49
56
  name?: string | null | undefined;
50
57
  temperature?: number | null | undefined;
51
58
  provider?: string | null | undefined;
52
59
  top_p?: number | null | undefined;
53
- frequent_penalty?: number | null | undefined;
60
+ frequency_penalty?: number | null | undefined;
54
61
  presence_penalty?: number | null | undefined;
55
62
  } | null | undefined, string | {
56
63
  name?: string | null | undefined;
57
64
  temperature?: number | null | undefined;
58
65
  provider?: string | null | undefined;
59
66
  top_p?: number | null | undefined;
60
- frequent_penalty?: number | null | undefined;
67
+ frequency_penalty?: number | null | undefined;
61
68
  presence_penalty?: number | null | undefined;
62
69
  } | null | undefined>;
63
70
  agents: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString, "many">>>;
@@ -71,7 +78,7 @@ declare const aigneFileSchema: z.ZodObject<{
71
78
  temperature?: number | null | undefined;
72
79
  provider?: string | null | undefined;
73
80
  top_p?: number | null | undefined;
74
- frequent_penalty?: number | null | undefined;
81
+ frequency_penalty?: number | null | undefined;
75
82
  presence_penalty?: number | null | undefined;
76
83
  } | null | undefined;
77
84
  agents?: string[] | null | undefined;
@@ -84,7 +91,7 @@ declare const aigneFileSchema: z.ZodObject<{
84
91
  temperature?: number | null | undefined;
85
92
  provider?: string | null | undefined;
86
93
  top_p?: number | null | undefined;
87
- frequent_penalty?: number | null | undefined;
94
+ frequency_penalty?: number | null | undefined;
88
95
  presence_penalty?: number | null | undefined;
89
96
  } | null | undefined;
90
97
  agents?: string[] | null | undefined;
@@ -98,7 +105,7 @@ export declare function loadAIGNEFile(path: string): Promise<{
98
105
  temperature?: number | null | undefined;
99
106
  provider?: string | null | undefined;
100
107
  top_p?: number | null | undefined;
101
- frequent_penalty?: number | null | undefined;
108
+ frequency_penalty?: number | null | undefined;
102
109
  presence_penalty?: number | null | undefined;
103
110
  } | null | undefined;
104
111
  agents?: string[] | null | undefined;
@@ -11,14 +11,6 @@ const zod_1 = require("zod");
11
11
  const agent_js_1 = require("../agents/agent.js");
12
12
  const ai_agent_js_1 = require("../agents/ai-agent.js");
13
13
  const mcp_agent_js_1 = require("../agents/mcp-agent.js");
14
- const bedrock_chat_model_js_1 = require("../models/bedrock-chat-model.js");
15
- const claude_chat_model_js_1 = require("../models/claude-chat-model.js");
16
- const deepseek_chat_model_js_1 = require("../models/deepseek-chat-model.js");
17
- const gemini_chat_model_js_1 = require("../models/gemini-chat-model.js");
18
- const ollama_chat_model_js_1 = require("../models/ollama-chat-model.js");
19
- const open_router_chat_model_js_1 = require("../models/open-router-chat-model.js");
20
- const openai_chat_model_js_1 = require("../models/openai-chat-model.js");
21
- const xai_chat_model_js_1 = require("../models/xai-chat-model.js");
22
14
  const type_utils_js_1 = require("../utils/type-utils.js");
23
15
  const agent_js_js_1 = require("./agent-js.js");
24
16
  const agent_yaml_js_1 = require("./agent-yaml.js");
@@ -32,7 +24,7 @@ async function load(options) {
32
24
  const skills = await Promise.all((aigne.skills ?? []).map((filename) => loadAgent((0, node_path_1.join)(rootDir, filename))));
33
25
  return {
34
26
  ...aigne,
35
- model: await loadModel(aigne.chat_model),
27
+ model: await loadModel(options.models, aigne.chat_model),
36
28
  agents,
37
29
  skills,
38
30
  };
@@ -70,26 +62,15 @@ async function loadAgent(path) {
70
62
  }
71
63
  const { MODEL_PROVIDER, MODEL_NAME } = process.env;
72
64
  const DEFAULT_MODEL_PROVIDER = "openai";
73
- const DEFAULT_MODEL_NAME = "gpt-4o-mini";
74
- async function loadModel(model, modelOptions) {
65
+ async function loadModel(models, model, modelOptions) {
75
66
  const params = {
76
- model: MODEL_NAME ?? model?.name ?? DEFAULT_MODEL_NAME,
67
+ model: MODEL_NAME ?? model?.name ?? undefined,
77
68
  temperature: model?.temperature ?? undefined,
78
- topP: model?.top_p ?? undefined,
79
- frequencyPenalty: model?.frequent_penalty ?? undefined,
80
- presencePenalty: model?.presence_penalty ?? undefined,
69
+ topP: model?.topP ?? undefined,
70
+ frequencyPenalty: model?.frequencyPenalty ?? undefined,
71
+ presencePenalty: model?.presencePenalty ?? undefined,
81
72
  };
82
- const availableModels = [
83
- openai_chat_model_js_1.OpenAIChatModel,
84
- claude_chat_model_js_1.ClaudeChatModel,
85
- xai_chat_model_js_1.XAIChatModel,
86
- gemini_chat_model_js_1.GeminiChatModel,
87
- deepseek_chat_model_js_1.DeepSeekChatModel,
88
- open_router_chat_model_js_1.OpenRouterChatModel,
89
- ollama_chat_model_js_1.OllamaChatModel,
90
- bedrock_chat_model_js_1.BedrockChatModel,
91
- ];
92
- const M = availableModels.find((m) => m.name
73
+ const M = models.find((m) => m.name
93
74
  .toLowerCase()
94
75
  .includes((MODEL_PROVIDER ?? model?.provider ?? DEFAULT_MODEL_PROVIDER).toLowerCase()));
95
76
  if (!M)
@@ -107,7 +88,7 @@ const aigneFileSchema = zod_1.z.object({
107
88
  name: zod_1.z.string().nullish(),
108
89
  temperature: zod_1.z.number().min(0).max(2).nullish(),
109
90
  top_p: zod_1.z.number().min(0).nullish(),
110
- frequent_penalty: zod_1.z.number().min(-2).max(2).nullish(),
91
+ frequency_penalty: zod_1.z.number().min(-2).max(2).nullish(),
111
92
  presence_penalty: zod_1.z.number().min(-2).max(2).nullish(),
112
93
  }),
113
94
  ])
@@ -39,11 +39,11 @@ export declare const memoryRetrieverInputSchema: z.ZodObject<{
39
39
  limit: z.ZodOptional<z.ZodNumber>;
40
40
  search: z.ZodOptional<z.ZodString>;
41
41
  }, "strip", z.ZodTypeAny, {
42
- limit?: number | undefined;
43
42
  search?: string | undefined;
44
- }, {
45
43
  limit?: number | undefined;
44
+ }, {
46
45
  search?: string | undefined;
46
+ limit?: number | undefined;
47
47
  }>;
48
48
  /**
49
49
  * @hidden
@@ -1,9 +1,9 @@
1
1
  import type { GetPromptResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { Agent, type Message } from "../agents/agent.js";
3
3
  import type { AIAgent } from "../agents/ai-agent.js";
4
+ import type { ChatModel, ChatModelInput } from "../agents/chat-model.js";
4
5
  import type { Context } from "../aigne/context.js";
5
6
  import type { MemoryAgent } from "../memory/memory.js";
6
- import type { ChatModel, ChatModelInput } from "../models/chat-model.js";
7
7
  import { ChatMessagesTemplate } from "./template.js";
8
8
  export declare const MESSAGE_KEY = "$message";
9
9
  export declare function createMessage<I extends Message>(message: string | I): I;
@@ -11,7 +11,7 @@ export declare function getMessage(input: Message): string | undefined;
11
11
  export interface PromptBuilderOptions {
12
12
  instructions?: string | ChatMessagesTemplate;
13
13
  }
14
- export interface PromptBuilderBuildOptions {
14
+ export interface PromptBuildOptions {
15
15
  memory?: MemoryAgent | MemoryAgent[];
16
16
  context: Context;
17
17
  agent?: AIAgent;
@@ -32,7 +32,7 @@ export declare class PromptBuilder {
32
32
  private static fromMCPPromptResult;
33
33
  constructor(options?: PromptBuilderOptions);
34
34
  instructions?: string | ChatMessagesTemplate;
35
- build(options: PromptBuilderBuildOptions): Promise<ChatModelInput & {
35
+ build(options: PromptBuildOptions): Promise<ChatModelInput & {
36
36
  toolAgents?: Agent[];
37
37
  }>;
38
38
  private buildMessages;
@@ -1,4 +1,4 @@
1
- import type { ChatModelInputMessage, ChatModelInputMessageContent, ChatModelOutputToolCall } from "../models/chat-model.js";
1
+ import type { ChatModelInputMessage, ChatModelInputMessageContent, ChatModelOutputToolCall } from "../agents/chat-model.js";
2
2
  export declare class PromptTemplate {
3
3
  template: string;
4
4
  static from(template: string): PromptTemplate;
@@ -24,7 +24,7 @@ export declare class AgentMessageTemplate extends ChatMessageTemplate {
24
24
  constructor(content?: ChatModelInputMessage["content"], toolCalls?: ChatModelOutputToolCall[] | undefined, name?: string);
25
25
  format(variables?: Record<string, unknown>): {
26
26
  toolCalls: ChatModelOutputToolCall[] | undefined;
27
- role: import("../models/chat-model.js").Role;
27
+ role: import("../agents/chat-model.js").Role;
28
28
  content?: ChatModelInputMessageContent;
29
29
  toolCallId?: string;
30
30
  name?: string;
@@ -36,7 +36,7 @@ export declare class ToolMessageTemplate extends ChatMessageTemplate {
36
36
  constructor(content: object | string, toolCallId: string, name?: string);
37
37
  format(variables?: Record<string, unknown>): {
38
38
  toolCallId: string;
39
- role: import("../models/chat-model.js").Role;
39
+ role: import("../agents/chat-model.js").Role;
40
40
  content?: ChatModelInputMessageContent;
41
41
  toolCalls?: {
42
42
  id: string;
@@ -28,7 +28,7 @@ function parseJSON(json) {
28
28
  return JSON.parse(json);
29
29
  }
30
30
  catch (error) {
31
- logger_js_1.logger.core("Failed to parse JSON", { json, error });
31
+ logger_js_1.logger.error("Failed to parse JSON", { json, error });
32
32
  throw error;
33
33
  }
34
34
  }
@@ -1,8 +1,33 @@
1
- import debug from "debug";
2
- export declare const logger: debug.Debug & {
3
- debug: debug.Debug;
4
- default: debug.Debug;
5
- } & {
6
- core: debug.Debugger;
7
- mcp: debug.Debugger;
8
- };
1
+ export declare enum LogLevel {
2
+ ERROR = "error",
3
+ WARN = "warn",
4
+ INFO = "info",
5
+ DEBUG = "debug"
6
+ }
7
+ export declare class Logger {
8
+ constructor(options: {
9
+ level: LogLevel;
10
+ ns: string;
11
+ });
12
+ level: LogLevel;
13
+ private debugLogger;
14
+ private infoLogger;
15
+ private warnLogger;
16
+ private errorLogger;
17
+ logMessage: {
18
+ (...data: any[]): void;
19
+ (...data: any[]): void;
20
+ (message?: any, ...optionalParams: any[]): void;
21
+ };
22
+ logError: {
23
+ (...data: any[]): void;
24
+ (...data: any[]): void;
25
+ (message?: any, ...optionalParams: any[]): void;
26
+ };
27
+ debug(message: string, ...args: unknown[]): void;
28
+ info(message: string, ...args: unknown[]): void;
29
+ warn(message: string, ...args: unknown[]): void;
30
+ error(message: string, ...args: unknown[]): void;
31
+ enabled(level: LogLevel): boolean;
32
+ }
33
+ export declare const logger: Logger;