@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
@@ -3,10 +3,68 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.logger = void 0;
6
+ exports.logger = exports.Logger = exports.LogLevel = void 0;
7
+ const node_tty_1 = require("node:tty");
7
8
  const debug_1 = __importDefault(require("debug"));
8
- const base = (0, debug_1.default)("aigne");
9
- exports.logger = Object.assign(debug_1.default, {
10
- core: base.extend("core"),
11
- mcp: base.extend("mcp"),
9
+ var LogLevel;
10
+ (function (LogLevel) {
11
+ LogLevel["ERROR"] = "error";
12
+ LogLevel["WARN"] = "warn";
13
+ LogLevel["INFO"] = "info";
14
+ LogLevel["DEBUG"] = "debug";
15
+ })(LogLevel || (exports.LogLevel = LogLevel = {}));
16
+ const levels = Object.values(LogLevel);
17
+ class Logger {
18
+ constructor(options) {
19
+ this.level = options.level;
20
+ this.debugLogger = (0, debug_1.default)(`${options.ns}:debug`);
21
+ this.infoLogger = (0, debug_1.default)(`${options.ns}:info`);
22
+ this.warnLogger = (0, debug_1.default)(`${options.ns}:warn`);
23
+ this.errorLogger = (0, debug_1.default)(`${options.ns}:error`);
24
+ for (const logger of [this.debugLogger, this.infoLogger, this.warnLogger]) {
25
+ // @ts-ignore
26
+ logger.useColors = (0, node_tty_1.isatty)(process.stdout.fd);
27
+ logger.enabled = true;
28
+ logger.log = (...args) => this.logMessage(...args);
29
+ }
30
+ this.errorLogger.log = (...args) => this.logError(...args);
31
+ // @ts-ignore
32
+ this.errorLogger.useColors = (0, node_tty_1.isatty)(process.stderr.fd);
33
+ this.errorLogger.enabled = true;
34
+ }
35
+ level;
36
+ debugLogger;
37
+ infoLogger;
38
+ warnLogger;
39
+ errorLogger;
40
+ logMessage = console.log;
41
+ logError = console.error;
42
+ debug(message, ...args) {
43
+ if (this.enabled(LogLevel.DEBUG)) {
44
+ this.debugLogger(message, ...args);
45
+ }
46
+ }
47
+ info(message, ...args) {
48
+ if (this.enabled(LogLevel.INFO)) {
49
+ this.infoLogger(message, ...args);
50
+ }
51
+ }
52
+ warn(message, ...args) {
53
+ if (this.enabled(LogLevel.WARN)) {
54
+ this.warnLogger(message, ...args);
55
+ }
56
+ }
57
+ error(message, ...args) {
58
+ if (this.enabled(LogLevel.ERROR)) {
59
+ this.errorLogger(message, ...args);
60
+ }
61
+ }
62
+ enabled(level) {
63
+ return levels.indexOf(this.level) >= levels.indexOf(level);
64
+ }
65
+ }
66
+ exports.Logger = Logger;
67
+ exports.logger = new Logger({
68
+ ns: "aigne:core",
69
+ level: LogLevel.INFO,
12
70
  });
@@ -1,3 +1,3 @@
1
- import type { ChatModelOutputUsage } from "../models/chat-model.js";
1
+ import type { ChatModelOutputUsage } from "../agents/chat-model.js";
2
2
  import type { Nullish } from "./type-utils.js";
3
3
  export declare function mergeUsage(...usages: Nullish<ChatModelOutputUsage>[]): ChatModelOutputUsage;
@@ -6,7 +6,7 @@ export declare function mergeAgentResponseChunk<T extends Message>(output: T, ch
6
6
  export declare function agentResponseStreamToObject<T extends Message>(stream: AgentResponseStream<T> | AgentProcessAsyncGenerator<T>): Promise<T>;
7
7
  export declare function asyncGeneratorToReadableStream<T extends Message>(generator: AgentProcessAsyncGenerator<T>): AgentResponseStream<T>;
8
8
  export declare function onAgentResponseStreamEnd<T extends Message>(stream: AgentResponseStream<T>, callback: (result: T) => PromiseOrValue<Partial<T> | void>, options?: {
9
- errorCallback?: (error: Error) => Error;
9
+ errorCallback?: (error: Error) => PromiseOrValue<Error>;
10
10
  processChunk?: (chunk: AgentResponseChunk<T>) => AgentResponseChunk<T>;
11
11
  }): ReadableStream<any>;
12
12
  export declare function isAsyncGenerator<T extends AsyncGenerator>(value: AsyncGenerator | unknown): value is T;
@@ -19,3 +19,5 @@ export declare function readableStreamToArray<T>(stream: ReadableStream<T>, opti
19
19
  catchError?: false;
20
20
  }): Promise<T[]>;
21
21
  export declare function stringToAgentResponseStream(str: string, key?: "text" | typeof MESSAGE_KEY | string): AgentResponseStream<Message>;
22
+ export declare function toReadableStream(stream: NodeJS.ReadStream): ReadableStream<Uint8Array<ArrayBufferLike>>;
23
+ export declare function readAllString(stream: NodeJS.ReadStream | ReadableStream): Promise<string>;
@@ -13,6 +13,8 @@ exports.arrayToAgentProcessAsyncGenerator = arrayToAgentProcessAsyncGenerator;
13
13
  exports.arrayToReadableStream = arrayToReadableStream;
14
14
  exports.readableStreamToArray = readableStreamToArray;
15
15
  exports.stringToAgentResponseStream = stringToAgentResponseStream;
16
+ exports.toReadableStream = toReadableStream;
17
+ exports.readAllString = readAllString;
16
18
  const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
17
19
  const agent_js_1 = require("../agents/agent.js");
18
20
  const type_utils_js_1 = require("./type-utils.js");
@@ -113,7 +115,7 @@ function onAgentResponseStreamEnd(stream, callback, options) {
113
115
  }
114
116
  }
115
117
  catch (error) {
116
- controller.error(options?.errorCallback?.(error) ?? error);
118
+ controller.error((await options?.errorCallback?.(error)) ?? error);
117
119
  }
118
120
  },
119
121
  });
@@ -166,3 +168,31 @@ function stringToAgentResponseStream(str, key = "text") {
166
168
  const segments = segmenter.segment(str);
167
169
  return arrayToReadableStream(Array.from(segments).map((segment) => ({ delta: { text: { [key]: segment.segment } } })));
168
170
  }
171
+ function toReadableStream(stream) {
172
+ return new ReadableStream({
173
+ start(controller) {
174
+ const onData = (chunk) => {
175
+ controller.enqueue(new Uint8Array(chunk));
176
+ };
177
+ const onEnd = () => {
178
+ cleanup();
179
+ controller.close();
180
+ };
181
+ const onError = (err) => {
182
+ cleanup();
183
+ controller.error(err);
184
+ };
185
+ function cleanup() {
186
+ stream.off("data", onData);
187
+ stream.off("end", onEnd);
188
+ stream.off("error", onError);
189
+ }
190
+ stream.on("data", onData);
191
+ stream.on("end", onEnd);
192
+ stream.on("error", onError);
193
+ },
194
+ });
195
+ }
196
+ async function readAllString(stream) {
197
+ return (await readableStreamToArray((stream instanceof ReadableStream ? stream : toReadableStream(stream)).pipeThrough(new TextDecoderStream()))).join("");
198
+ }
@@ -2,6 +2,11 @@ import { type ZodType } from "zod";
2
2
  export type PromiseOrValue<T> = T | Promise<T>;
3
3
  export type Nullish<T> = T | null | undefined | void;
4
4
  export type OmitPropertiesFromArrayFirstElement<T extends unknown[], K extends string | number | symbol> = T extends [infer U, ...infer Rest] ? [Omit<U, K>, ...Rest] : never;
5
+ export type XOr<T, K extends keyof T, O extends keyof T> = (Omit<T, O> & {
6
+ [key in O]?: undefined;
7
+ }) | (Omit<T, K> & {
8
+ [key in K]?: undefined;
9
+ });
5
10
  export declare function isNil(value: unknown): value is null | undefined;
6
11
  export declare function isRecord<T>(value: unknown): value is Record<string, T>;
7
12
  export declare function isEmpty(obj: unknown): boolean;
@@ -3,7 +3,8 @@ import { ZodObject, type ZodType } from "zod";
3
3
  import type { Context } from "../aigne/context.js";
4
4
  import type { MessagePayload } from "../aigne/message-queue.js";
5
5
  import type { MemoryAgent } from "../memory/memory.js";
6
- import { type Nullish, type PromiseOrValue } from "../utils/type-utils.js";
6
+ import { type Nullish, type PromiseOrValue, type XOr } from "../utils/type-utils.js";
7
+ import type { GuideRailAgent, GuideRailAgentOutput } from "./guide-rail-agent.js";
7
8
  import { type TransferAgentOutput } from "./types.js";
8
9
  export * from "./types.js";
9
10
  /**
@@ -29,7 +30,7 @@ export type PublishTopic<O extends Message> = string | string[] | ((output: O) =
29
30
  * @template I The agent input message type
30
31
  * @template O The agent output message type
31
32
  */
32
- export interface AgentOptions<I extends Message = Message, O extends Message = Message> {
33
+ export interface AgentOptions<I extends Message = Message, O extends Message = Message> extends Partial<Pick<Agent, "guideRails" | "hooks">> {
33
34
  /**
34
35
  * Topics the agent should subscribe to
35
36
  *
@@ -139,6 +140,35 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
139
140
  * List of memories this agent can use
140
141
  */
141
142
  readonly memories: MemoryAgent[];
143
+ /**
144
+ * Lifecycle hooks for agent processing.
145
+ *
146
+ * Hooks enable tracing, logging, monitoring, and custom behavior
147
+ * without modifying the core agent implementation
148
+ *
149
+ * @example
150
+ * Here's an example of using hooks:
151
+ * {@includeCode ../../test/agents/agent.test.ts#example-agent-hooks}
152
+ */
153
+ readonly hooks: AgentHooks;
154
+ /**
155
+ * List of GuideRail agents applied to this agent
156
+ *
157
+ * GuideRail agents validate, transform, or control the message flow by:
158
+ * - Enforcing rules and safety policies
159
+ * - Validating inputs/outputs against specific criteria
160
+ * - Implementing business logic validations
161
+ * - Monitoring and auditing agent behavior
162
+ *
163
+ * Each GuideRail agent can examine both input and expected output,
164
+ * and has the ability to abort the process with an explanation
165
+ *
166
+ * @example
167
+ * Here's an example of using GuideRail agents:
168
+ *
169
+ * {@includeCode ../../test/agents/agent.test.ts#example-agent-guide-rails}
170
+ */
171
+ readonly guideRails?: GuideRailAgent[];
142
172
  /**
143
173
  * Name of the agent, used for identification and logging
144
174
  *
@@ -301,6 +331,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
301
331
  * @returns Agent response (streaming or regular)
302
332
  */
303
333
  invoke(input: I | string, context?: Context, options?: AgentInvokeOptions): Promise<AgentResponse<O>>;
334
+ protected invokeSkill<I extends Message, O extends Message>(skill: Agent<I, O>, input: I, context: Context): Promise<O>;
304
335
  /**
305
336
  * Process agent output
306
337
  *
@@ -319,7 +350,6 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
319
350
  *
320
351
  * @param error Caught error
321
352
  * @param context Execution context
322
- * @throws Always throws the received error
323
353
  */
324
354
  private processAgentError;
325
355
  /**
@@ -342,7 +372,25 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
342
372
  * @param _ Input message (unused)
343
373
  * @param context Execution context
344
374
  */
345
- protected preprocess(_: I, context: Context): void;
375
+ protected preprocess(_: I, context: Context): PromiseOrValue<void>;
376
+ private checkResponseByGuideRails;
377
+ private runGuideRails;
378
+ /**
379
+ * Handle errors detected by GuideRail agents
380
+ *
381
+ * This method is called when a GuideRail agent aborts the process, providing
382
+ * a way for agents to customize error handling behavior. By default, it simply
383
+ * returns the original error, but subclasses can override this method to:
384
+ * - Transform the error into a more specific response
385
+ * - Apply recovery strategies
386
+ * - Log or report the error in a custom format
387
+ * - Return a fallback output instead of an error
388
+ *
389
+ * @param error The GuideRail agent output containing abort=true and a reason
390
+ * @returns Either the original/modified error or a substitute output object
391
+ * which will be tagged with $status: "GuideRailError"
392
+ */
393
+ protected onGuideRailError(error: GuideRailAgentOutput): Promise<O | GuideRailAgentOutput>;
346
394
  /**
347
395
  * Post-processing operations after handling output
348
396
  *
@@ -354,7 +402,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
354
402
  * @param output Output message
355
403
  * @param context Execution context
356
404
  */
357
- protected postprocess(input: I, output: O, context: Context): void;
405
+ protected postprocess(input: I, output: O, context: Context): PromiseOrValue<void>;
358
406
  protected publishToTopics(output: Message, context: Context): Promise<void>;
359
407
  /**
360
408
  * Core processing method of the agent, must be implemented in subclasses
@@ -419,6 +467,81 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
419
467
  */
420
468
  [Symbol.asyncDispose](): Promise<void>;
421
469
  }
470
+ /**
471
+ * Lifecycle hooks for agent execution
472
+ *
473
+ * Hooks provide a way to intercept and extend agent behavior at key points during
474
+ * the agent's lifecycle, enabling custom functionality like logging, monitoring,
475
+ * tracing, error handling, and more.
476
+ */
477
+ export interface AgentHooks<I extends Message = Message, O extends Message = Message> {
478
+ /**
479
+ * Called when agent processing begins
480
+ *
481
+ * This hook runs before the agent processes input, allowing for
482
+ * setup operations, logging, or input transformations.
483
+ *
484
+ * @param event Object containing the input message
485
+ */
486
+ onStart?: (event: {
487
+ input: I;
488
+ }) => PromiseOrValue<void>;
489
+ /**
490
+ * Called when agent processing completes or fails
491
+ *
492
+ * This hook runs after processing finishes, receiving either the output
493
+ * or an error if processing failed. Useful for cleanup operations,
494
+ * logging results, or error handling.
495
+ *
496
+ * @param event Object containing the input message and either output or error
497
+ */
498
+ onEnd?: (event: XOr<{
499
+ input: I;
500
+ output: O;
501
+ error: Error;
502
+ }, "output", "error">) => PromiseOrValue<void>;
503
+ /**
504
+ * Called before a skill (sub-agent) is invoked
505
+ *
506
+ * This hook runs when the agent delegates work to a skill,
507
+ * allowing for tracking skill usage or transforming input to the skill.
508
+ *
509
+ * @param event Object containing the skill being used and input message
510
+ */
511
+ onSkillStart?: (event: {
512
+ skill: Agent;
513
+ input: I;
514
+ }) => PromiseOrValue<void>;
515
+ /**
516
+ * Called after a skill (sub-agent) completes or fails
517
+ *
518
+ * This hook runs when a skill finishes execution, receiving either the output
519
+ * or an error if the skill failed. Useful for monitoring skill performance
520
+ * or handling skill-specific errors.
521
+ *
522
+ * @param event Object containing the skill used, input message, and either output or error
523
+ */
524
+ onSkillEnd?: (event: XOr<{
525
+ skill: Agent;
526
+ input: I;
527
+ output: O;
528
+ error: Error;
529
+ }, "output", "error">) => PromiseOrValue<void>;
530
+ /**
531
+ * Called when an agent hands off processing to another agent
532
+ *
533
+ * This hook runs when a source agent transfers control to a target agent,
534
+ * allowing for tracking of handoffs between agents and monitoring the flow
535
+ * of processing in multi-agent systems.
536
+ *
537
+ * @param event Object containing the source agent, target agent, and input message
538
+ */
539
+ onHandoff?: (event: {
540
+ source: Agent;
541
+ target: Agent;
542
+ input: I;
543
+ }) => PromiseOrValue<void>;
544
+ }
422
545
  /**
423
546
  * Response type for an agent, can be:
424
547
  * - Direct response object
@@ -427,7 +550,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
427
550
  *
428
551
  * @template T Response data type
429
552
  */
430
- export type AgentResponse<T> = T | TransferAgentOutput | AgentResponseStream<T>;
553
+ export type AgentResponse<T> = T | AgentResponseStream<T> | TransferAgentOutput | GuideRailAgentOutput;
431
554
  /**
432
555
  * Streaming response type for an agent
433
556
  *
@@ -1,10 +1,10 @@
1
1
  import { type ZodObject, type ZodType, z } from "zod";
2
2
  import type { Context } from "../aigne/context.js";
3
3
  import { type DefaultMemoryOptions } from "../memory/default-memory.js";
4
- import { ChatModel } from "../models/chat-model.js";
5
- import type { ChatModelInput } from "../models/chat-model.js";
6
4
  import { PromptBuilder } from "../prompt/prompt-builder.js";
7
5
  import { Agent, type AgentOptions, type AgentProcessAsyncGenerator, type Message } from "./agent.js";
6
+ import { ChatModel, type ChatModelInput } from "./chat-model.js";
7
+ import type { GuideRailAgentOutput } from "./guide-rail-agent.js";
8
8
  /**
9
9
  * Configuration options for an AI Agent
10
10
  *
@@ -216,6 +216,7 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
216
216
  * @protected
217
217
  */
218
218
  process(input: I, context: Context): AgentProcessAsyncGenerator<O>;
219
+ protected onGuideRailError(error: GuideRailAgentOutput): Promise<O | GuideRailAgentOutput>;
219
220
  /**
220
221
  * Process router mode requests
221
222
  *
@@ -1,6 +1,6 @@
1
- import { Agent, type AgentProcessResult, type Message } from "../agents/agent.js";
2
1
  import type { Context } from "../aigne/context.js";
3
2
  import type { PromiseOrValue } from "../utils/type-utils.js";
3
+ import { Agent, type AgentProcessResult, type Message } from "./agent.js";
4
4
  /**
5
5
  * ChatModel is an abstract base class for interacting with Large Language Models (LLMs).
6
6
  *
@@ -10,19 +10,19 @@ import type { PromiseOrValue } from "../utils/type-utils.js";
10
10
  *
11
11
  * @example
12
12
  * Here's how to implement a custom ChatModel:
13
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model}
13
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model}
14
14
  *
15
15
  * @example
16
16
  * Here's an example showing streaming response with readable stream:
17
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-streaming}
17
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-streaming}
18
18
  *
19
19
  * @example
20
20
  * Here's an example showing streaming response with async generator:
21
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-streaming-async-generator}
21
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-streaming-async-generator}
22
22
  *
23
23
  * @example
24
24
  * Here's an example with tool calls:
25
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
25
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
26
26
  */
27
27
  export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelOutput> {
28
28
  constructor();
@@ -44,6 +44,17 @@ export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelO
44
44
  supportsParallelToolCalls: boolean;
45
45
  };
46
46
  private validateToolNames;
47
+ /**
48
+ * Normalizes tool names to ensure compatibility with language models
49
+ *
50
+ * This method converts tool names to a format that complies with model requirements
51
+ * by replacing hyphens and whitespace characters with underscores. The normalized
52
+ * names are used for tool calls while preserving the original names for reference.
53
+ *
54
+ * @param name - The original tool name to normalize
55
+ * @returns A promise that resolves to the normalized tool name
56
+ */
57
+ protected normalizeToolName(name: string): Promise<string>;
47
58
  /**
48
59
  * Performs preprocessing operations before handling input
49
60
  *
@@ -53,7 +64,7 @@ export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelO
53
64
  * @param context Execution context
54
65
  * @throws Error if token usage exceeds maximum limit
55
66
  */
56
- protected preprocess(input: ChatModelInput, context: Context): void;
67
+ protected preprocess(input: ChatModelInput, context: Context): Promise<void>;
57
68
  /**
58
69
  * Performs postprocessing operations after handling output
59
70
  *
@@ -94,11 +105,11 @@ export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelO
94
105
  *
95
106
  * @example
96
107
  * Here's a basic ChatModel input example:
97
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model}
108
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model}
98
109
  *
99
110
  * @example
100
111
  * Here's an example with tool calling:
101
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
112
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
102
113
  */
103
114
  export interface ChatModelInput extends Message {
104
115
  /**
@@ -213,7 +224,7 @@ export type ChatModelInputResponseFormat = {
213
224
  *
214
225
  * @example
215
226
  * Here's an example showing how to use tools:
216
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
227
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
217
228
  */
218
229
  export interface ChatModelInputTool {
219
230
  /**
@@ -249,7 +260,7 @@ export interface ChatModelInputTool {
249
260
  *
250
261
  * @example
251
262
  * Here's an example showing how to use tools:
252
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
263
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
253
264
  */
254
265
  export type ChatModelInputToolChoice = "auto" | "none" | "required" | {
255
266
  type: "function";
@@ -296,11 +307,11 @@ export interface ChatModelOptions {
296
307
  *
297
308
  * @example
298
309
  * Here's a basic output example:
299
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model}
310
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model}
300
311
  *
301
312
  * @example
302
313
  * Here's an example with tool calls:
303
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
314
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
304
315
  */
305
316
  export interface ChatModelOutput extends Message {
306
317
  /**
@@ -331,7 +342,7 @@ export interface ChatModelOutput extends Message {
331
342
  *
332
343
  * @example
333
344
  * Here's an example with tool calls:
334
- * {@includeCode ../../test/models/chat-model.test.ts#example-chat-model-tools}
345
+ * {@includeCode ../../test/agents/chat-model.test.ts#example-chat-model-tools}
335
346
  */
336
347
  export interface ChatModelOutputToolCall {
337
348
  /**
@@ -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>;
@@ -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 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,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;