@aigne/core 1.14.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 (145) hide show
  1. package/CHANGELOG.md +27 -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 +12 -9
  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/agents/team-agent.js +1 -1
  14. package/lib/cjs/aigne/aigne.d.ts +3 -2
  15. package/lib/cjs/aigne/aigne.js +2 -2
  16. package/lib/cjs/aigne/context.d.ts +2 -1
  17. package/lib/cjs/aigne/context.js +8 -1
  18. package/lib/cjs/index.d.ts +1 -1
  19. package/lib/cjs/index.js +1 -1
  20. package/lib/cjs/loader/agent-yaml.d.ts +1 -1
  21. package/lib/cjs/loader/index.d.ts +18 -11
  22. package/lib/cjs/loader/index.js +8 -27
  23. package/lib/cjs/memory/retriever.d.ts +2 -2
  24. package/lib/cjs/prompt/prompt-builder.d.ts +3 -3
  25. package/lib/cjs/prompt/template.d.ts +3 -3
  26. package/lib/cjs/prompt/template.js +1 -1
  27. package/lib/cjs/utils/json-schema.js +1 -1
  28. package/lib/cjs/utils/logger.d.ts +33 -8
  29. package/lib/cjs/utils/logger.js +63 -5
  30. package/lib/cjs/utils/model-utils.d.ts +1 -1
  31. package/lib/cjs/utils/stream-utils.d.ts +3 -2
  32. package/lib/cjs/utils/stream-utils.js +50 -26
  33. package/lib/cjs/utils/type-utils.d.ts +5 -0
  34. package/lib/dts/agents/agent.d.ts +129 -6
  35. package/lib/dts/agents/ai-agent.d.ts +3 -2
  36. package/lib/{cjs/models → dts/agents}/chat-model.d.ts +24 -13
  37. package/lib/dts/agents/guide-rail-agent.d.ts +62 -0
  38. package/lib/dts/aigne/aigne.d.ts +3 -2
  39. package/lib/dts/aigne/context.d.ts +2 -1
  40. package/lib/dts/index.d.ts +1 -1
  41. package/lib/dts/loader/agent-yaml.d.ts +1 -1
  42. package/lib/dts/loader/index.d.ts +18 -11
  43. package/lib/dts/memory/retriever.d.ts +2 -2
  44. package/lib/dts/prompt/prompt-builder.d.ts +3 -3
  45. package/lib/dts/prompt/template.d.ts +3 -3
  46. package/lib/dts/utils/logger.d.ts +33 -8
  47. package/lib/dts/utils/model-utils.d.ts +1 -1
  48. package/lib/dts/utils/stream-utils.d.ts +3 -2
  49. package/lib/dts/utils/type-utils.d.ts +5 -0
  50. package/lib/esm/agents/agent.d.ts +129 -6
  51. package/lib/esm/agents/agent.js +112 -20
  52. package/lib/esm/agents/ai-agent.d.ts +3 -2
  53. package/lib/esm/agents/ai-agent.js +12 -9
  54. package/lib/{dts/models → esm/agents}/chat-model.d.ts +24 -13
  55. package/lib/esm/{models → agents}/chat-model.js +48 -7
  56. package/lib/esm/agents/guide-rail-agent.d.ts +62 -0
  57. package/lib/esm/agents/guide-rail-agent.js +11 -0
  58. package/lib/esm/agents/mcp-agent.js +9 -9
  59. package/lib/esm/agents/team-agent.js +2 -2
  60. package/lib/esm/aigne/aigne.d.ts +3 -2
  61. package/lib/esm/aigne/aigne.js +2 -2
  62. package/lib/esm/aigne/context.d.ts +2 -1
  63. package/lib/esm/aigne/context.js +9 -2
  64. package/lib/esm/index.d.ts +1 -1
  65. package/lib/esm/index.js +1 -1
  66. package/lib/esm/loader/agent-yaml.d.ts +1 -1
  67. package/lib/esm/loader/index.d.ts +18 -11
  68. package/lib/esm/loader/index.js +8 -27
  69. package/lib/esm/memory/retriever.d.ts +2 -2
  70. package/lib/esm/prompt/prompt-builder.d.ts +3 -3
  71. package/lib/esm/prompt/template.d.ts +3 -3
  72. package/lib/esm/prompt/template.js +1 -1
  73. package/lib/esm/utils/json-schema.js +1 -1
  74. package/lib/esm/utils/logger.d.ts +33 -8
  75. package/lib/esm/utils/logger.js +61 -4
  76. package/lib/esm/utils/model-utils.d.ts +1 -1
  77. package/lib/esm/utils/stream-utils.d.ts +3 -2
  78. package/lib/esm/utils/stream-utils.js +48 -25
  79. package/lib/esm/utils/type-utils.d.ts +5 -0
  80. package/package.json +1 -20
  81. package/lib/cjs/client/client.d.ts +0 -97
  82. package/lib/cjs/client/client.js +0 -87
  83. package/lib/cjs/client/index.d.ts +0 -1
  84. package/lib/cjs/client/index.js +0 -17
  85. package/lib/cjs/models/bedrock-chat-model.d.ts +0 -79
  86. package/lib/cjs/models/bedrock-chat-model.js +0 -303
  87. package/lib/cjs/models/claude-chat-model.d.ts +0 -114
  88. package/lib/cjs/models/claude-chat-model.js +0 -317
  89. package/lib/cjs/models/deepseek-chat-model.d.ts +0 -23
  90. package/lib/cjs/models/deepseek-chat-model.js +0 -35
  91. package/lib/cjs/models/gemini-chat-model.d.ts +0 -23
  92. package/lib/cjs/models/gemini-chat-model.js +0 -35
  93. package/lib/cjs/models/ollama-chat-model.d.ts +0 -22
  94. package/lib/cjs/models/ollama-chat-model.js +0 -34
  95. package/lib/cjs/models/open-router-chat-model.d.ts +0 -22
  96. package/lib/cjs/models/open-router-chat-model.js +0 -34
  97. package/lib/cjs/models/openai-chat-model.d.ts +0 -166
  98. package/lib/cjs/models/openai-chat-model.js +0 -415
  99. package/lib/cjs/models/xai-chat-model.d.ts +0 -21
  100. package/lib/cjs/models/xai-chat-model.js +0 -33
  101. package/lib/cjs/server/error.d.ts +0 -15
  102. package/lib/cjs/server/error.js +0 -22
  103. package/lib/cjs/server/index.d.ts +0 -2
  104. package/lib/cjs/server/index.js +0 -18
  105. package/lib/cjs/server/server.d.ts +0 -135
  106. package/lib/cjs/server/server.js +0 -188
  107. package/lib/dts/client/client.d.ts +0 -97
  108. package/lib/dts/client/index.d.ts +0 -1
  109. package/lib/dts/models/bedrock-chat-model.d.ts +0 -79
  110. package/lib/dts/models/claude-chat-model.d.ts +0 -114
  111. package/lib/dts/models/deepseek-chat-model.d.ts +0 -23
  112. package/lib/dts/models/gemini-chat-model.d.ts +0 -23
  113. package/lib/dts/models/ollama-chat-model.d.ts +0 -22
  114. package/lib/dts/models/open-router-chat-model.d.ts +0 -22
  115. package/lib/dts/models/openai-chat-model.d.ts +0 -166
  116. package/lib/dts/models/xai-chat-model.d.ts +0 -21
  117. package/lib/dts/server/error.d.ts +0 -15
  118. package/lib/dts/server/index.d.ts +0 -2
  119. package/lib/dts/server/server.d.ts +0 -135
  120. package/lib/esm/client/client.d.ts +0 -97
  121. package/lib/esm/client/client.js +0 -83
  122. package/lib/esm/client/index.d.ts +0 -1
  123. package/lib/esm/client/index.js +0 -1
  124. package/lib/esm/models/bedrock-chat-model.d.ts +0 -79
  125. package/lib/esm/models/bedrock-chat-model.js +0 -298
  126. package/lib/esm/models/claude-chat-model.d.ts +0 -114
  127. package/lib/esm/models/claude-chat-model.js +0 -310
  128. package/lib/esm/models/deepseek-chat-model.d.ts +0 -23
  129. package/lib/esm/models/deepseek-chat-model.js +0 -31
  130. package/lib/esm/models/gemini-chat-model.d.ts +0 -23
  131. package/lib/esm/models/gemini-chat-model.js +0 -31
  132. package/lib/esm/models/ollama-chat-model.d.ts +0 -22
  133. package/lib/esm/models/ollama-chat-model.js +0 -30
  134. package/lib/esm/models/open-router-chat-model.d.ts +0 -22
  135. package/lib/esm/models/open-router-chat-model.js +0 -30
  136. package/lib/esm/models/openai-chat-model.d.ts +0 -166
  137. package/lib/esm/models/openai-chat-model.js +0 -405
  138. package/lib/esm/models/xai-chat-model.d.ts +0 -21
  139. package/lib/esm/models/xai-chat-model.js +0 -29
  140. package/lib/esm/server/error.d.ts +0 -15
  141. package/lib/esm/server/error.js +0 -18
  142. package/lib/esm/server/index.d.ts +0 -2
  143. package/lib/esm/server/index.js +0 -2
  144. package/lib/esm/server/server.d.ts +0 -135
  145. package/lib/esm/server/server.js +0 -181
@@ -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,6 +56,19 @@ 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
  *
@@ -65,14 +78,29 @@ export class ChatModel extends Agent {
65
78
  * @param context Execution context
66
79
  * @throws Error if token usage exceeds maximum limit
67
80
  */
68
- preprocess(input, context) {
81
+ async preprocess(input, context) {
69
82
  super.preprocess(input, context);
70
83
  const { limits, usage } = 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
@@ -84,6 +112,19 @@ export class ChatModel extends Agent {
84
112
  * @param context Execution context
85
113
  */
86
114
  postprocess(input, output, context) {
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
+ }
87
128
  super.postprocess(input, output, context);
88
129
  const { usage } = output;
89
130
  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,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
+ };
@@ -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;
@@ -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,4 +1,4 @@
1
- import { mergeAgentResponseChunk, readableStreamToAsyncIterator } from "../utils/stream-utils.js";
1
+ import { mergeAgentResponseChunk } from "../utils/stream-utils.js";
2
2
  import { isEmpty } from "../utils/type-utils.js";
3
3
  import { Agent, } from "./agent.js";
4
4
  /**
@@ -116,7 +116,7 @@ export class TeamAgent extends Agent {
116
116
  const newAgents = [];
117
117
  for (const agent of agents) {
118
118
  const [o, transferToAgent] = await context.invoke(agent, { ...input, ...output }, { returnActiveAgent: true, streaming: true });
119
- for await (const chunk of readableStreamToAsyncIterator(o)) {
119
+ for await (const chunk of o) {
120
120
  yield chunk;
121
121
  mergeAgentResponseChunk(output, chunk);
122
122
  }
@@ -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
  *
@@ -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,
@@ -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
@@ -5,7 +5,7 @@ import { Agent, } from "../agents/agent.js";
5
5
  import { isTransferAgentOutput, transferAgentOutputKey } from "../agents/types.js";
6
6
  import { UserAgent } from "../agents/user-agent.js";
7
7
  import { createMessage } from "../prompt/prompt-builder.js";
8
- import { agentResponseStreamToObject, asyncGeneratorToReadableStream, onAgentResponseStreamEnd, readableStreamToAsyncIterator, } from "../utils/stream-utils.js";
8
+ import { agentResponseStreamToObject, asyncGeneratorToReadableStream, onAgentResponseStreamEnd, } from "../utils/stream-utils.js";
9
9
  import { checkArguments, isNil, omitBy, } from "../utils/type-utils.js";
10
10
  import { MessageQueue, toMessagePayload, } from "./message-queue.js";
11
11
  import { newEmptyContextUsage } from "./usage.js";
@@ -167,8 +167,15 @@ class AIGNEContextInternal {
167
167
  let output;
168
168
  for (;;) {
169
169
  const result = {};
170
+ if (options?.sourceAgent && activeAgent !== options.sourceAgent) {
171
+ options.sourceAgent.hooks.onHandoff?.({
172
+ source: options.sourceAgent,
173
+ target: activeAgent,
174
+ input,
175
+ });
176
+ }
170
177
  const stream = await activeAgent.invoke(input, context, { streaming: true });
171
- for await (const value of readableStreamToAsyncIterator(stream)) {
178
+ for await (const value of stream) {
172
179
  if (value.delta.text) {
173
180
  yield { delta: { text: value.delta.text } };
174
181
  }
@@ -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/esm/index.js CHANGED
@@ -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";
@@ -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;
@@ -5,14 +5,6 @@ import { z } from "zod";
5
5
  import { FunctionAgent } from "../agents/agent.js";
6
6
  import { AIAgent } from "../agents/ai-agent.js";
7
7
  import { MCPAgent } from "../agents/mcp-agent.js";
8
- import { BedrockChatModel } from "../models/bedrock-chat-model.js";
9
- import { ClaudeChatModel } from "../models/claude-chat-model.js";
10
- import { DeepSeekChatModel } from "../models/deepseek-chat-model.js";
11
- import { GeminiChatModel } from "../models/gemini-chat-model.js";
12
- import { OllamaChatModel } from "../models/ollama-chat-model.js";
13
- import { OpenRouterChatModel } from "../models/open-router-chat-model.js";
14
- import { OpenAIChatModel } from "../models/openai-chat-model.js";
15
- import { XAIChatModel } from "../models/xai-chat-model.js";
16
8
  import { tryOrThrow } from "../utils/type-utils.js";
17
9
  import { loadAgentFromJsFile } from "./agent-js.js";
18
10
  import { loadAgentFromYamlFile } from "./agent-yaml.js";
@@ -26,7 +18,7 @@ export async function load(options) {
26
18
  const skills = await Promise.all((aigne.skills ?? []).map((filename) => loadAgent(join(rootDir, filename))));
27
19
  return {
28
20
  ...aigne,
29
- model: await loadModel(aigne.chat_model),
21
+ model: await loadModel(options.models, aigne.chat_model),
30
22
  agents,
31
23
  skills,
32
24
  };
@@ -64,26 +56,15 @@ export async function loadAgent(path) {
64
56
  }
65
57
  const { MODEL_PROVIDER, MODEL_NAME } = process.env;
66
58
  const DEFAULT_MODEL_PROVIDER = "openai";
67
- const DEFAULT_MODEL_NAME = "gpt-4o-mini";
68
- export async function loadModel(model, modelOptions) {
59
+ export async function loadModel(models, model, modelOptions) {
69
60
  const params = {
70
- model: MODEL_NAME ?? model?.name ?? DEFAULT_MODEL_NAME,
61
+ model: MODEL_NAME ?? model?.name ?? undefined,
71
62
  temperature: model?.temperature ?? undefined,
72
- topP: model?.top_p ?? undefined,
73
- frequencyPenalty: model?.frequent_penalty ?? undefined,
74
- presencePenalty: model?.presence_penalty ?? undefined,
63
+ topP: model?.topP ?? undefined,
64
+ frequencyPenalty: model?.frequencyPenalty ?? undefined,
65
+ presencePenalty: model?.presencePenalty ?? undefined,
75
66
  };
76
- const availableModels = [
77
- OpenAIChatModel,
78
- ClaudeChatModel,
79
- XAIChatModel,
80
- GeminiChatModel,
81
- DeepSeekChatModel,
82
- OpenRouterChatModel,
83
- OllamaChatModel,
84
- BedrockChatModel,
85
- ];
86
- const M = availableModels.find((m) => m.name
67
+ const M = models.find((m) => m.name
87
68
  .toLowerCase()
88
69
  .includes((MODEL_PROVIDER ?? model?.provider ?? DEFAULT_MODEL_PROVIDER).toLowerCase()));
89
70
  if (!M)
@@ -101,7 +82,7 @@ const aigneFileSchema = z.object({
101
82
  name: z.string().nullish(),
102
83
  temperature: z.number().min(0).max(2).nullish(),
103
84
  top_p: z.number().min(0).nullish(),
104
- frequent_penalty: z.number().min(-2).max(2).nullish(),
85
+ frequency_penalty: z.number().min(-2).max(2).nullish(),
105
86
  presence_penalty: z.number().min(-2).max(2).nullish(),
106
87
  }),
107
88
  ])
@@ -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;
@@ -80,7 +80,7 @@ export class ToolMessageTemplate extends ChatMessageTemplate {
80
80
  constructor(content, toolCallId, name) {
81
81
  super("tool", typeof content === "string"
82
82
  ? content
83
- : tryOrThrow(() => JSON.stringify(content), `Failed to stringify tool content. toolCallId: ${toolCallId}, content: ${inspect(content)}`), name);
83
+ : tryOrThrow(() => JSON.stringify(content, (_, value) => typeof value === "bigint" ? value.toString() : value), `Failed to stringify tool content. toolCallId: ${toolCallId}, content: ${inspect(content)}`), name);
84
84
  this.toolCallId = toolCallId;
85
85
  }
86
86
  format(variables) {
@@ -23,7 +23,7 @@ export function parseJSON(json) {
23
23
  return JSON.parse(json);
24
24
  }
25
25
  catch (error) {
26
- logger.core("Failed to parse JSON", { json, error });
26
+ logger.error("Failed to parse JSON", { json, error });
27
27
  throw error;
28
28
  }
29
29
  }