@aigne/core 1.16.0 → 1.18.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 (100) hide show
  1. package/CHANGELOG.md +37 -16
  2. package/lib/cjs/agents/agent.d.ts +69 -37
  3. package/lib/cjs/agents/agent.js +93 -65
  4. package/lib/cjs/agents/ai-agent.d.ts +4 -7
  5. package/lib/cjs/agents/ai-agent.js +10 -19
  6. package/lib/cjs/agents/chat-model.d.ts +7 -8
  7. package/lib/cjs/agents/chat-model.js +9 -9
  8. package/lib/cjs/agents/mcp-agent.d.ts +4 -5
  9. package/lib/cjs/agents/mcp-agent.js +7 -13
  10. package/lib/cjs/agents/team-agent.d.ts +7 -8
  11. package/lib/cjs/agents/team-agent.js +10 -10
  12. package/lib/cjs/agents/user-agent.d.ts +4 -5
  13. package/lib/cjs/agents/user-agent.js +11 -12
  14. package/lib/cjs/aigne/aigne.d.ts +10 -9
  15. package/lib/cjs/aigne/aigne.js +5 -4
  16. package/lib/cjs/aigne/context.d.ts +18 -9
  17. package/lib/cjs/aigne/context.js +23 -12
  18. package/lib/cjs/aigne/message-queue.d.ts +6 -2
  19. package/lib/cjs/aigne/message-queue.js +2 -2
  20. package/lib/cjs/index.d.ts +3 -1
  21. package/lib/cjs/index.js +3 -1
  22. package/lib/cjs/loader/agent-js.d.ts +1 -1
  23. package/lib/cjs/loader/agent-yaml.d.ts +3 -2
  24. package/lib/cjs/loader/agent-yaml.js +3 -2
  25. package/lib/cjs/loader/index.d.ts +5 -1
  26. package/lib/cjs/loader/index.js +25 -16
  27. package/lib/cjs/memory/memory.d.ts +3 -2
  28. package/lib/cjs/memory/memory.js +1 -1
  29. package/lib/cjs/memory/retriever.d.ts +2 -2
  30. package/lib/cjs/prompt/prompt-builder.d.ts +9 -7
  31. package/lib/cjs/prompt/prompt-builder.js +14 -10
  32. package/lib/cjs/prompt/template.js +1 -3
  33. package/lib/cjs/utils/logger.js +3 -3
  34. package/lib/cjs/utils/nodejs.d.ts +8 -0
  35. package/lib/cjs/utils/nodejs.js +24 -0
  36. package/lib/cjs/utils/type-utils.d.ts +2 -2
  37. package/lib/dts/agents/agent.d.ts +69 -37
  38. package/lib/dts/agents/ai-agent.d.ts +4 -7
  39. package/lib/dts/agents/chat-model.d.ts +7 -8
  40. package/lib/dts/agents/mcp-agent.d.ts +4 -5
  41. package/lib/dts/agents/team-agent.d.ts +7 -8
  42. package/lib/dts/agents/user-agent.d.ts +4 -5
  43. package/lib/dts/aigne/aigne.d.ts +10 -9
  44. package/lib/dts/aigne/context.d.ts +18 -9
  45. package/lib/dts/aigne/message-queue.d.ts +6 -2
  46. package/lib/dts/index.d.ts +3 -1
  47. package/lib/dts/loader/agent-js.d.ts +1 -1
  48. package/lib/dts/loader/agent-yaml.d.ts +3 -2
  49. package/lib/dts/loader/index.d.ts +5 -1
  50. package/lib/dts/memory/memory.d.ts +3 -2
  51. package/lib/dts/memory/retriever.d.ts +2 -2
  52. package/lib/dts/prompt/prompt-builder.d.ts +9 -7
  53. package/lib/dts/utils/nodejs.d.ts +8 -0
  54. package/lib/dts/utils/type-utils.d.ts +2 -2
  55. package/lib/esm/agents/agent.d.ts +69 -37
  56. package/lib/esm/agents/agent.js +94 -66
  57. package/lib/esm/agents/ai-agent.d.ts +4 -7
  58. package/lib/esm/agents/ai-agent.js +10 -19
  59. package/lib/esm/agents/chat-model.d.ts +7 -8
  60. package/lib/esm/agents/chat-model.js +9 -9
  61. package/lib/esm/agents/mcp-agent.d.ts +4 -5
  62. package/lib/esm/agents/mcp-agent.js +7 -13
  63. package/lib/esm/agents/team-agent.d.ts +7 -8
  64. package/lib/esm/agents/team-agent.js +10 -10
  65. package/lib/esm/agents/user-agent.d.ts +4 -5
  66. package/lib/esm/agents/user-agent.js +10 -11
  67. package/lib/esm/aigne/aigne.d.ts +10 -9
  68. package/lib/esm/aigne/aigne.js +5 -4
  69. package/lib/esm/aigne/context.d.ts +18 -9
  70. package/lib/esm/aigne/context.js +24 -10
  71. package/lib/esm/aigne/message-queue.d.ts +6 -2
  72. package/lib/esm/aigne/message-queue.js +2 -2
  73. package/lib/esm/index.d.ts +3 -1
  74. package/lib/esm/index.js +3 -1
  75. package/lib/esm/loader/agent-js.d.ts +1 -1
  76. package/lib/esm/loader/agent-yaml.d.ts +3 -2
  77. package/lib/esm/loader/agent-yaml.js +3 -2
  78. package/lib/esm/loader/index.d.ts +5 -1
  79. package/lib/esm/loader/index.js +25 -16
  80. package/lib/esm/memory/memory.d.ts +3 -2
  81. package/lib/esm/memory/memory.js +2 -2
  82. package/lib/esm/memory/retriever.d.ts +2 -2
  83. package/lib/esm/prompt/prompt-builder.d.ts +9 -7
  84. package/lib/esm/prompt/prompt-builder.js +15 -11
  85. package/lib/esm/prompt/template.js +1 -3
  86. package/lib/esm/utils/logger.js +3 -3
  87. package/lib/esm/utils/nodejs.d.ts +8 -0
  88. package/lib/esm/utils/nodejs.js +21 -0
  89. package/lib/esm/utils/type-utils.d.ts +2 -2
  90. package/package.json +4 -3
  91. package/lib/cjs/memory/default-memory.d.ts +0 -16
  92. package/lib/cjs/memory/default-memory.js +0 -70
  93. package/lib/cjs/utils/fs.d.ts +0 -2
  94. package/lib/cjs/utils/fs.js +0 -25
  95. package/lib/dts/memory/default-memory.d.ts +0 -16
  96. package/lib/dts/utils/fs.d.ts +0 -2
  97. package/lib/esm/memory/default-memory.d.ts +0 -16
  98. package/lib/esm/memory/default-memory.js +0 -63
  99. package/lib/esm/utils/fs.d.ts +0 -2
  100. package/lib/esm/utils/fs.js +0 -21
@@ -2,6 +2,7 @@ import type { Camelize } from "camelize-ts";
2
2
  import { z } from "zod";
3
3
  import { type Agent } from "../agents/agent.js";
4
4
  import type { ChatModel, ChatModelOptions } from "../agents/chat-model.js";
5
+ import type { MemoryAgent, MemoryAgentOptions } from "../memory/memory.js";
5
6
  export interface LoadOptions {
6
7
  models: {
7
8
  new (parameters: {
@@ -9,6 +10,9 @@ export interface LoadOptions {
9
10
  modelOptions?: ChatModelOptions;
10
11
  }): ChatModel;
11
12
  }[];
13
+ memories?: {
14
+ new (parameters?: MemoryAgentOptions): MemoryAgent;
15
+ }[];
12
16
  path: string;
13
17
  }
14
18
  export declare function load(options: LoadOptions): Promise<{
@@ -26,7 +30,7 @@ export declare function load(options: LoadOptions): Promise<{
26
30
  presence_penalty?: number | null | undefined;
27
31
  } | null | undefined;
28
32
  }>;
29
- export declare function loadAgent(path: string): Promise<Agent>;
33
+ export declare function loadAgent(path: string, options?: LoadOptions): Promise<Agent>;
30
34
  export declare function loadModel(models: LoadOptions["models"], model?: Camelize<z.infer<typeof aigneFileSchema>["chat_model"]>, modelOptions?: ChatModelOptions): Promise<ChatModel | undefined>;
31
35
  declare const aigneFileSchema: z.ZodObject<{
32
36
  name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -4,24 +4,22 @@ exports.load = load;
4
4
  exports.loadAgent = loadAgent;
5
5
  exports.loadModel = loadModel;
6
6
  exports.loadAIGNEFile = loadAIGNEFile;
7
- const promises_1 = require("node:fs/promises");
8
- const node_path_1 = require("node:path");
9
7
  const yaml_1 = require("yaml");
10
8
  const zod_1 = require("zod");
11
9
  const agent_js_1 = require("../agents/agent.js");
12
10
  const ai_agent_js_1 = require("../agents/ai-agent.js");
13
11
  const mcp_agent_js_1 = require("../agents/mcp-agent.js");
12
+ const nodejs_js_1 = require("../utils/nodejs.js");
14
13
  const type_utils_js_1 = require("../utils/type-utils.js");
15
14
  const agent_js_js_1 = require("./agent-js.js");
16
15
  const agent_yaml_js_1 = require("./agent-yaml.js");
17
16
  const AIGNE_FILE_NAME = ["aigne.yaml", "aigne.yml"];
18
17
  async function load(options) {
19
- const { path } = options;
20
- const aigneFilePath = await getAIGNEFilePath(path);
21
- const rootDir = (0, node_path_1.dirname)(aigneFilePath);
18
+ const aigneFilePath = await getAIGNEFilePath(options.path);
19
+ const rootDir = nodejs_js_1.nodejs.path.dirname(aigneFilePath);
22
20
  const aigne = await loadAIGNEFile(aigneFilePath);
23
- const agents = await Promise.all((aigne.agents ?? []).map((filename) => loadAgent((0, node_path_1.join)(rootDir, filename))));
24
- const skills = await Promise.all((aigne.skills ?? []).map((filename) => loadAgent((0, node_path_1.join)(rootDir, filename))));
21
+ const agents = await Promise.all((aigne.agents ?? []).map((filename) => loadAgent(nodejs_js_1.nodejs.path.join(rootDir, filename))));
22
+ const skills = await Promise.all((aigne.skills ?? []).map((filename) => loadAgent(nodejs_js_1.nodejs.path.join(rootDir, filename))));
25
23
  return {
26
24
  ...aigne,
27
25
  model: await loadModel(options.models, aigne.chat_model),
@@ -29,18 +27,21 @@ async function load(options) {
29
27
  skills,
30
28
  };
31
29
  }
32
- async function loadAgent(path) {
33
- if ((0, node_path_1.extname)(path) === ".js") {
30
+ async function loadAgent(path, options) {
31
+ if (nodejs_js_1.nodejs.path.extname(path) === ".js") {
34
32
  const agent = await (0, agent_js_js_1.loadAgentFromJsFile)(path);
35
33
  return agent_js_1.FunctionAgent.from(agent);
36
34
  }
37
- if ((0, node_path_1.extname)(path) === ".yaml" || (0, node_path_1.extname)(path) === ".yml") {
35
+ if (nodejs_js_1.nodejs.path.extname(path) === ".yaml" || nodejs_js_1.nodejs.path.extname(path) === ".yml") {
38
36
  const agent = await (0, agent_yaml_js_1.loadAgentFromYamlFile)(path);
39
37
  if (agent.type === "ai") {
40
38
  return ai_agent_js_1.AIAgent.from({
41
39
  ...agent,
40
+ memory: !options?.memories?.length || !agent.memory
41
+ ? undefined
42
+ : await loadMemory(options.memories, typeof agent.memory === "object" ? agent.memory.provider : undefined, typeof agent.memory === "object" ? agent.memory : {}),
42
43
  skills: agent.skills &&
43
- (await Promise.all(agent.skills.map((filename) => loadAgent((0, node_path_1.join)((0, node_path_1.dirname)(path), filename))))),
44
+ (await Promise.all(agent.skills.map((filename) => loadAgent(nodejs_js_1.nodejs.path.join(nodejs_js_1.nodejs.path.dirname(path), filename))))),
44
45
  });
45
46
  }
46
47
  if (agent.type === "mcp") {
@@ -60,7 +61,15 @@ async function loadAgent(path) {
60
61
  }
61
62
  throw new Error(`Unsupported agent file type: ${path}`);
62
63
  }
63
- const { MODEL_PROVIDER, MODEL_NAME } = process.env;
64
+ async function loadMemory(memories, provider, options) {
65
+ const M = !provider
66
+ ? memories[0]
67
+ : memories.find((i) => i.name.toLowerCase().includes(provider.toLowerCase()));
68
+ if (!M)
69
+ throw new Error(`Unsupported memory: ${provider}`);
70
+ return new M(options);
71
+ }
72
+ const { MODEL_PROVIDER, MODEL_NAME } = nodejs_js_1.nodejs.env;
64
73
  const DEFAULT_MODEL_PROVIDER = "openai";
65
74
  async function loadModel(models, model, modelOptions) {
66
75
  const params = {
@@ -98,17 +107,17 @@ const aigneFileSchema = zod_1.z.object({
98
107
  skills: zod_1.z.array(zod_1.z.string()).nullish(),
99
108
  });
100
109
  async function loadAIGNEFile(path) {
101
- const raw = await (0, type_utils_js_1.tryOrThrow)(() => (0, promises_1.readFile)(path, "utf8"), (error) => new Error(`Failed to load aigne.yaml from ${path}: ${error.message}`));
110
+ const raw = await (0, type_utils_js_1.tryOrThrow)(() => nodejs_js_1.nodejs.fs.readFile(path, "utf8"), (error) => new Error(`Failed to load aigne.yaml from ${path}: ${error.message}`));
102
111
  const json = await (0, type_utils_js_1.tryOrThrow)(() => (0, yaml_1.parse)(raw), (error) => new Error(`Failed to parse aigne.yaml from ${path}: ${error.message}`));
103
112
  const agent = (0, type_utils_js_1.tryOrThrow)(() => aigneFileSchema.parse({ ...json, skills: json.skills ?? json.tools }), (error) => new Error(`Failed to validate aigne.yaml from ${path}: ${error.message}`));
104
113
  return agent;
105
114
  }
106
115
  async function getAIGNEFilePath(path) {
107
- const s = await (0, promises_1.stat)(path);
116
+ const s = await nodejs_js_1.nodejs.fs.stat(path);
108
117
  if (s.isDirectory()) {
109
118
  for (const file of AIGNE_FILE_NAME) {
110
- const filePath = (0, node_path_1.join)(path, file);
111
- if ((await (0, promises_1.stat)(filePath)).isFile())
119
+ const filePath = nodejs_js_1.nodejs.path.join(path, file);
120
+ if ((await nodejs_js_1.nodejs.fs.stat(filePath)).isFile())
112
121
  return filePath;
113
122
  }
114
123
  }
@@ -1,10 +1,11 @@
1
- import { Agent, type AgentOptions, type Message } from "../agents/agent.js";
1
+ import { Agent, type AgentInvokeOptions, type AgentOptions, type Message } from "../agents/agent.js";
2
2
  import type { Context } from "../aigne/context.js";
3
3
  import type { MessagePayload } from "../aigne/message-queue.js";
4
4
  import type { MemoryRecorder, MemoryRecorderInput, MemoryRecorderOutput } from "./recorder.js";
5
5
  import type { MemoryRetriever, MemoryRetrieverInput, MemoryRetrieverOutput } from "./retriever.js";
6
6
  export interface Memory {
7
7
  id: string;
8
+ sessionId?: string | null;
8
9
  content: unknown;
9
10
  createdAt: string;
10
11
  }
@@ -62,7 +63,7 @@ export declare class MemoryAgent extends Agent {
62
63
  * MemoryAgent doesn't directly process messages like other agents, so this method
63
64
  * throws an error when called. Use the specialized retrieve() and record() methods instead.
64
65
  */
65
- process(_input: Message, _context: Context): Promise<Message>;
66
+ process(_input: Message, _options: AgentInvokeOptions): Promise<Message>;
66
67
  /**
67
68
  * Retrieves memories based on the provided input criteria.
68
69
  *
@@ -85,7 +85,7 @@ class MemoryAgent extends agent_js_1.Agent {
85
85
  * MemoryAgent doesn't directly process messages like other agents, so this method
86
86
  * throws an error when called. Use the specialized retrieve() and record() methods instead.
87
87
  */
88
- async process(_input, _context) {
88
+ async process(_input, _options) {
89
89
  throw new Error("Method not implemented.");
90
90
  }
91
91
  /**
@@ -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
- search?: string | undefined;
43
42
  limit?: number | undefined;
44
- }, {
45
43
  search?: string | undefined;
44
+ }, {
46
45
  limit?: number | undefined;
46
+ search?: string | undefined;
47
47
  }>;
48
48
  /**
49
49
  * @hidden
@@ -1,19 +1,21 @@
1
1
  import type { GetPromptResult } from "@modelcontextprotocol/sdk/types.js";
2
- import { Agent, type Message } from "../agents/agent.js";
2
+ import { Agent, type AgentInvokeOptions, type Message } from "../agents/agent.js";
3
3
  import type { AIAgent } from "../agents/ai-agent.js";
4
4
  import type { ChatModel, ChatModelInput } from "../agents/chat-model.js";
5
- import type { Context } from "../aigne/context.js";
6
- import type { MemoryAgent } from "../memory/memory.js";
7
5
  import { ChatMessagesTemplate } from "./template.js";
8
6
  export declare const MESSAGE_KEY = "$message";
9
- export declare function createMessage<I extends Message>(message: string | I): I;
7
+ export declare function createMessage<V extends Message>(message: string, variables?: V): {
8
+ [MESSAGE_KEY]: string;
9
+ } & typeof variables;
10
+ export declare function createMessage<I extends Message, V extends Message>(message: I, variables?: V): I & typeof variables;
11
+ export declare function createMessage<I extends Message, V extends Message>(message: string | I, variables?: V): ({
12
+ [MESSAGE_KEY]: string;
13
+ } | I) & typeof variables;
10
14
  export declare function getMessage(input: Message): string | undefined;
11
15
  export interface PromptBuilderOptions {
12
16
  instructions?: string | ChatMessagesTemplate;
13
17
  }
14
- export interface PromptBuildOptions {
15
- memory?: MemoryAgent | MemoryAgent[];
16
- context: Context;
18
+ export interface PromptBuildOptions extends AgentInvokeOptions {
17
19
  agent?: AIAgent;
18
20
  input?: Message;
19
21
  model?: ChatModel;
@@ -3,19 +3,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PromptBuilder = exports.MESSAGE_KEY = void 0;
4
4
  exports.createMessage = createMessage;
5
5
  exports.getMessage = getMessage;
6
- const promises_1 = require("node:fs/promises");
7
6
  const yaml_1 = require("yaml");
8
7
  const zod_1 = require("zod");
9
8
  const agent_js_1 = require("../agents/agent.js");
10
9
  const json_schema_js_1 = require("../utils/json-schema.js");
10
+ const nodejs_js_1 = require("../utils/nodejs.js");
11
11
  const type_utils_js_1 = require("../utils/type-utils.js");
12
12
  const memory_message_template_js_1 = require("./prompts/memory-message-template.js");
13
13
  const template_js_1 = require("./template.js");
14
14
  exports.MESSAGE_KEY = "$message";
15
- function createMessage(message) {
16
- return typeof message === "string"
17
- ? { [exports.MESSAGE_KEY]: message }
18
- : { ...message };
15
+ function createMessage(message, variables) {
16
+ return (typeof message === "string"
17
+ ? { [exports.MESSAGE_KEY]: message, ...variables }
18
+ : { ...message, ...variables });
19
19
  }
20
20
  function getMessage(input) {
21
21
  const userInputMessage = input[exports.MESSAGE_KEY];
@@ -36,7 +36,7 @@ class PromptBuilder {
36
36
  throw new Error(`Invalid instructions ${instructions}`);
37
37
  }
38
38
  static async fromFile(path) {
39
- const text = await (0, promises_1.readFile)(path, "utf-8");
39
+ const text = await nodejs_js_1.nodejs.fs.readFile(path, "utf-8");
40
40
  return PromptBuilder.from(text);
41
41
  }
42
42
  static fromMCPPromptResult(result) {
@@ -83,11 +83,15 @@ class PromptBuilder {
83
83
  const messages = (typeof this.instructions === "string"
84
84
  ? template_js_1.ChatMessagesTemplate.from([template_js_1.SystemMessageTemplate.from(this.instructions)])
85
85
  : this.instructions)?.format(options.input) ?? [];
86
- for (const memory of (0, type_utils_js_1.orArrayToArray)(options.memory ?? options.agent?.memories)) {
87
- const memories = (await memory.retrieve({ search: input && getMessage(input) }, options.context))?.memories;
88
- if (memories?.length)
89
- messages.push(...this.convertMemoriesToMessages(memories, options));
86
+ const memories = [];
87
+ if (options.agent) {
88
+ memories.push(...(await options.agent.retrieveMemories({ search: options.input }, options)));
90
89
  }
90
+ if (options.memories?.length) {
91
+ memories.push(...options.memories);
92
+ }
93
+ if (memories.length)
94
+ messages.push(...this.convertMemoriesToMessages(memories, options));
91
95
  const content = input && getMessage(input);
92
96
  // add user input if it's not the same as the last message
93
97
  if (content && messages.at(-1)?.content !== content) {
@@ -5,10 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ChatMessagesTemplate = exports.ToolMessageTemplate = exports.AgentMessageTemplate = exports.UserMessageTemplate = exports.SystemMessageTemplate = exports.ChatMessageTemplate = exports.PromptTemplate = void 0;
7
7
  exports.parseChatMessages = parseChatMessages;
8
- const node_util_1 = require("node:util");
9
8
  const mustache_1 = __importDefault(require("mustache"));
10
9
  const zod_1 = require("zod");
11
- const type_utils_js_1 = require("../utils/type-utils.js");
12
10
  class PromptTemplate {
13
11
  template;
14
12
  static from(template) {
@@ -92,7 +90,7 @@ class ToolMessageTemplate extends ChatMessageTemplate {
92
90
  constructor(content, toolCallId, name) {
93
91
  super("tool", typeof content === "string"
94
92
  ? content
95
- : (0, type_utils_js_1.tryOrThrow)(() => JSON.stringify(content, (_, value) => typeof value === "bigint" ? value.toString() : value), `Failed to stringify tool content. toolCallId: ${toolCallId}, content: ${(0, node_util_1.inspect)(content)}`), name);
93
+ : JSON.stringify(content, (_, value) => typeof value === "bigint" ? value.toString() : value), name);
96
94
  this.toolCallId = toolCallId;
97
95
  }
98
96
  format(variables) {
@@ -4,8 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.logger = exports.Logger = exports.LogLevel = void 0;
7
- const node_tty_1 = require("node:tty");
8
7
  const debug_1 = __importDefault(require("debug"));
8
+ const nodejs_js_1 = require("./nodejs.js");
9
9
  var LogLevel;
10
10
  (function (LogLevel) {
11
11
  LogLevel["ERROR"] = "error";
@@ -23,13 +23,13 @@ class Logger {
23
23
  this.errorLogger = (0, debug_1.default)(`${options.ns}:error`);
24
24
  for (const logger of [this.debugLogger, this.infoLogger, this.warnLogger]) {
25
25
  // @ts-ignore
26
- logger.useColors = (0, node_tty_1.isatty)(process.stdout.fd);
26
+ logger.useColors = nodejs_js_1.nodejs.isStdoutATTY;
27
27
  logger.enabled = true;
28
28
  logger.log = (...args) => this.logMessage(...args);
29
29
  }
30
30
  this.errorLogger.log = (...args) => this.logError(...args);
31
31
  // @ts-ignore
32
- this.errorLogger.useColors = (0, node_tty_1.isatty)(process.stderr.fd);
32
+ this.errorLogger.useColors = nodejs_js_1.nodejs.isStderrATTY;
33
33
  this.errorLogger.enabled = true;
34
34
  }
35
35
  level;
@@ -0,0 +1,8 @@
1
+ export declare const nodejs: {
2
+ customInspect: any;
3
+ isStdoutATTY: boolean;
4
+ isStderrATTY: boolean;
5
+ env: NodeJS.ProcessEnv;
6
+ readonly fs: typeof import("node:fs/promises");
7
+ readonly path: typeof import("node:path");
8
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.nodejs = void 0;
4
+ exports.nodejs = {
5
+ customInspect: isNodejsEnvironment() ? require("node:util").inspect.custom : Symbol("inspect"),
6
+ isStdoutATTY: isNodejsEnvironment() && process.stdout?.isTTY,
7
+ isStderrATTY: isNodejsEnvironment() && process.stderr?.isTTY,
8
+ env: isNodejsEnvironment() ? process.env : {},
9
+ get fs() {
10
+ ensureNodejsEnvironment();
11
+ return require("node:fs/promises");
12
+ },
13
+ get path() {
14
+ ensureNodejsEnvironment();
15
+ return require("node:path");
16
+ },
17
+ };
18
+ function isNodejsEnvironment() {
19
+ return typeof process !== "undefined";
20
+ }
21
+ function ensureNodejsEnvironment() {
22
+ if (!isNodejsEnvironment())
23
+ throw new Error("This code must run in a Node.js environment.");
24
+ }
@@ -1,4 +1,4 @@
1
- import { type ZodType } from "zod";
1
+ import { type ZodType, z } 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;
@@ -20,6 +20,6 @@ export declare function orArrayToArray<T>(value?: T | T[]): T[];
20
20
  export declare function createAccessorArray<T>(array: T[], accessor: (array: T[], name: string) => T | undefined): T[] & {
21
21
  [key: string]: T;
22
22
  };
23
- export declare function checkArguments<T>(prefix: string, schema: ZodType<T>, args: T | unknown): T;
23
+ export declare function checkArguments<T extends ZodType>(prefix: string, schema: T, args: unknown): z.infer<T>;
24
24
  export declare function tryOrThrow<P extends PromiseOrValue<unknown>>(fn: () => P, error: string | Error | ((error: Error) => Error)): P;
25
25
  export declare function tryOrThrow<P extends PromiseOrValue<unknown>>(fn: () => P, error?: Nullish<string | Error | ((error: Error) => Nullish<Error>)>): P | undefined;
@@ -1,8 +1,10 @@
1
- import { inspect } from "node:util";
2
1
  import { ZodObject, type ZodType } from "zod";
3
- import type { Context } from "../aigne/context.js";
2
+ import type { Context, UserContext } from "../aigne/context.js";
4
3
  import type { MessagePayload } from "../aigne/message-queue.js";
5
- import type { MemoryAgent } from "../memory/memory.js";
4
+ import type { Memory, MemoryAgent } from "../memory/memory.js";
5
+ import type { MemoryRecorderInput } from "../memory/recorder.js";
6
+ import type { MemoryRetrieverInput } from "../memory/retriever.js";
7
+ import { nodejs } from "../utils/nodejs.js";
6
8
  import { type Nullish, type PromiseOrValue, type XOr } from "../utils/type-utils.js";
7
9
  import type { GuideRailAgent, GuideRailAgentOutput } from "./guide-rail-agent.js";
8
10
  import { type TransferAgentOutput } from "./types.js";
@@ -95,11 +97,29 @@ export interface AgentOptions<I extends Message = Message, O extends Message = M
95
97
  * One or more memory agents this agent can use
96
98
  */
97
99
  memory?: MemoryAgent | MemoryAgent[];
100
+ /**
101
+ * Maximum number of memory items to retrieve
102
+ */
103
+ maxRetrieveMemoryCount?: number;
98
104
  }
99
105
  export declare const agentOptionsSchema: ZodObject<{
100
106
  [key in keyof AgentOptions]: ZodType<AgentOptions[key]>;
101
107
  }>;
102
- export interface AgentInvokeOptions {
108
+ export interface AgentInvokeOptions<U extends UserContext = UserContext> {
109
+ /**
110
+ * The execution context for the agent
111
+ *
112
+ * The context provides the runtime environment for agent execution, including:
113
+ * - Event emission and subscription management
114
+ * - Inter-agent communication and message passing
115
+ * - Resource usage tracking and limits enforcement
116
+ * - Timeout and status management
117
+ * - Memory and state management across agent invocations
118
+ *
119
+ * Each agent invocation requires a context to coordinate with the broader
120
+ * agent system and maintain proper isolation and resource control.
121
+ */
122
+ context: Context<U>;
103
123
  /**
104
124
  * Whether to enable streaming response
105
125
  *
@@ -111,6 +131,8 @@ export interface AgentInvokeOptions {
111
131
  * and returns the final JSON result
112
132
  */
113
133
  streaming?: boolean;
134
+ userContext?: U;
135
+ memories?: Pick<Memory, "content">[];
114
136
  }
115
137
  /**
116
138
  * Agent is the base class for all agents.
@@ -135,11 +157,24 @@ export interface AgentInvokeOptions {
135
157
  * {@includeCode ../../test/agents/agent.test.ts#example-custom-agent}
136
158
  */
137
159
  export declare abstract class Agent<I extends Message = Message, O extends Message = Message> {
160
+ /**
161
+ * Custom object inspection behavior
162
+ *
163
+ * When using Node.js's util.inspect function to inspect an agent,
164
+ * only the agent's name will be shown, making output more concise
165
+ *
166
+ * @returns Agent name
167
+ */
168
+ [nodejs.customInspect]: () => string;
138
169
  constructor(options?: AgentOptions<I, O>);
139
170
  /**
140
171
  * List of memories this agent can use
141
172
  */
142
173
  readonly memories: MemoryAgent[];
174
+ /**
175
+ * Maximum number of memory items to retrieve
176
+ */
177
+ maxRetrieveMemoryCount?: number;
143
178
  /**
144
179
  * Lifecycle hooks for agent processing.
145
180
  *
@@ -278,11 +313,15 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
278
313
  /**
279
314
  * Check context status to ensure it hasn't timed out
280
315
  *
281
- * @param context The context to check
316
+ * @param options Invocation options containing context
282
317
  * @throws Error if the context has timed out
283
318
  */
284
319
  private checkContextStatus;
285
320
  private newDefaultContext;
321
+ retrieveMemories(input: Pick<MemoryRetrieverInput, "limit"> & {
322
+ search?: Message | string;
323
+ }, options: Pick<AgentInvokeOptions, "context">): Promise<Pick<Memory, "content">[]>;
324
+ recordMemories(input: MemoryRecorderInput, options: Pick<AgentInvokeOptions, "context">): Promise<void>;
286
325
  /**
287
326
  * Invoke the agent with regular (non-streaming) response
288
327
  *
@@ -290,7 +329,6 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
290
329
  * suitable for scenarios where a complete result is needed at once.
291
330
  *
292
331
  * @param input Input message to the agent, can be a string or structured object
293
- * @param context Execution context, providing environment and resource access
294
332
  * @param options Invocation options, must set streaming to false or leave unset
295
333
  * @returns Final JSON response
296
334
  *
@@ -298,7 +336,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
298
336
  * Here's an example of invoking an agent with regular mode:
299
337
  * {@includeCode ../../test/agents/agent.test.ts#example-invoke}
300
338
  */
301
- invoke(input: I | string, context?: Context, options?: AgentInvokeOptions & {
339
+ invoke(input: I | string, options?: Partial<AgentInvokeOptions> & {
302
340
  streaming?: false;
303
341
  }): Promise<O>;
304
342
  /**
@@ -309,7 +347,6 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
309
347
  * chat bot typing effects.
310
348
  *
311
349
  * @param input Input message to the agent, can be a string or structured object
312
- * @param context Execution context, providing environment and resource access
313
350
  * @param options Invocation options, must set streaming to true for this overload
314
351
  * @returns Streaming response object
315
352
  *
@@ -317,7 +354,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
317
354
  * Here's an example of invoking an agent with streaming response:
318
355
  * {@includeCode ../../test/agents/agent.test.ts#example-invoke-streaming}
319
356
  */
320
- invoke(input: I | string, context: Context | undefined, options: {
357
+ invoke(input: I | string, options: Partial<AgentInvokeOptions> & {
321
358
  streaming: true;
322
359
  }): Promise<AgentResponseStream<O>>;
323
360
  /**
@@ -326,12 +363,11 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
326
363
  * Returns either streaming or regular response based on the streaming parameter in options
327
364
  *
328
365
  * @param input Input message to the agent
329
- * @param context Execution context
330
366
  * @param options Invocation options
331
367
  * @returns Agent response (streaming or regular)
332
368
  */
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>;
369
+ invoke(input: I | string, options?: Partial<AgentInvokeOptions>): Promise<AgentResponse<O>>;
370
+ protected invokeSkill<I extends Message, O extends Message>(skill: Agent<I, O>, input: I, options: AgentInvokeOptions): Promise<O>;
335
371
  /**
336
372
  * Process agent output
337
373
  *
@@ -339,7 +375,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
339
375
  *
340
376
  * @param input Original input message
341
377
  * @param output Raw output produced by the agent
342
- * @param context Execution context
378
+ * @param options Invocation options
343
379
  * @returns Final processed output
344
380
  */
345
381
  private processAgentOutput;
@@ -349,7 +385,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
349
385
  * Logs error information, triggers failure events, and re-throws the error
350
386
  *
351
387
  * @param error Caught error
352
- * @param context Execution context
388
+ * @param options Invocation options
353
389
  */
354
390
  private processAgentError;
355
391
  /**
@@ -358,10 +394,10 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
358
394
  * If the context has a maximum invocation limit set, checks if the limit
359
395
  * has been exceeded and increments the invocation counter
360
396
  *
361
- * @param context Execution context
397
+ * @param options Invocation options containing context and limits
362
398
  * @throws Error if maximum invocation limit is exceeded
363
399
  */
364
- protected checkAgentInvokesUsage(context: Context): void;
400
+ protected checkAgentInvokesUsage(options: AgentInvokeOptions): void;
365
401
  /**
366
402
  * Pre-processing operations before handling input
367
403
  *
@@ -370,9 +406,9 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
370
406
  * - Verifying invocation limits
371
407
  *
372
408
  * @param _ Input message (unused)
373
- * @param context Execution context
409
+ * @param options Options for agent invocation
374
410
  */
375
- protected preprocess(_: I, context: Context): PromiseOrValue<void>;
411
+ protected preprocess(_: I, options: AgentInvokeOptions): Promise<void>;
376
412
  private checkResponseByGuideRails;
377
413
  private runGuideRails;
378
414
  /**
@@ -400,10 +436,10 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
400
436
  *
401
437
  * @param input Input message
402
438
  * @param output Output message
403
- * @param context Execution context
439
+ * @param options Options for agent invocation
404
440
  */
405
- protected postprocess(input: I, output: O, context: Context): PromiseOrValue<void>;
406
- protected publishToTopics(output: Message, context: Context): Promise<void>;
441
+ protected postprocess(input: I, output: O, options: AgentInvokeOptions): Promise<void>;
442
+ protected publishToTopics(output: Message, options: AgentInvokeOptions): Promise<void>;
407
443
  /**
408
444
  * Core processing method of the agent, must be implemented in subclasses
409
445
  *
@@ -415,7 +451,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
415
451
  * - Another agent instance (transfer agent)
416
452
  *
417
453
  * @param input Input message
418
- * @param context Execution context
454
+ * @param options Options for agent invocation
419
455
  * @returns Processing result
420
456
  *
421
457
  * @example
@@ -434,7 +470,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
434
470
  * Example of transfer to another agent:
435
471
  * {@includeCode ../../test/agents/agent.test.ts#example-process-transfer}
436
472
  */
437
- abstract process(input: I, context: Context): PromiseOrValue<AgentProcessResult<O>>;
473
+ abstract process(input: I, options: AgentInvokeOptions): PromiseOrValue<AgentProcessResult<O>>;
438
474
  /**
439
475
  * Shut down the agent and clean up resources
440
476
  *
@@ -449,15 +485,6 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
449
485
  * {@includeCode ../../test/agents/agent.test.ts#example-agent-shutdown-by-using}
450
486
  */
451
487
  shutdown(): Promise<void>;
452
- /**
453
- * Custom object inspection behavior
454
- *
455
- * When using Node.js's util.inspect function to inspect an agent,
456
- * only the agent's name will be shown, making output more concise
457
- *
458
- * @returns Agent name
459
- */
460
- [inspect.custom](): string;
461
488
  /**
462
489
  * Async dispose method for shutdown the agent
463
490
  *
@@ -484,6 +511,7 @@ export interface AgentHooks<I extends Message = Message, O extends Message = Mes
484
511
  * @param event Object containing the input message
485
512
  */
486
513
  onStart?: (event: {
514
+ context: Context;
487
515
  input: I;
488
516
  }) => PromiseOrValue<void>;
489
517
  /**
@@ -496,6 +524,7 @@ export interface AgentHooks<I extends Message = Message, O extends Message = Mes
496
524
  * @param event Object containing the input message and either output or error
497
525
  */
498
526
  onEnd?: (event: XOr<{
527
+ context: Context;
499
528
  input: I;
500
529
  output: O;
501
530
  error: Error;
@@ -509,6 +538,7 @@ export interface AgentHooks<I extends Message = Message, O extends Message = Mes
509
538
  * @param event Object containing the skill being used and input message
510
539
  */
511
540
  onSkillStart?: (event: {
541
+ context: Context;
512
542
  skill: Agent;
513
543
  input: I;
514
544
  }) => PromiseOrValue<void>;
@@ -522,6 +552,7 @@ export interface AgentHooks<I extends Message = Message, O extends Message = Mes
522
552
  * @param event Object containing the skill used, input message, and either output or error
523
553
  */
524
554
  onSkillEnd?: (event: XOr<{
555
+ context: Context;
525
556
  skill: Agent;
526
557
  input: I;
527
558
  output: O;
@@ -537,6 +568,7 @@ export interface AgentHooks<I extends Message = Message, O extends Message = Mes
537
568
  * @param event Object containing the source agent, target agent, and input message
538
569
  */
539
570
  onHandoff?: (event: {
571
+ context: Context;
540
572
  source: Agent;
541
573
  target: Agent;
542
574
  input: I;
@@ -587,7 +619,7 @@ export interface AgentResponseDelta<T> {
587
619
  }> | Partial<{
588
620
  [key: string]: string;
589
621
  }>;
590
- json?: Partial<T | TransferAgentOutput>;
622
+ json?: Partial<T> | TransferAgentOutput;
591
623
  };
592
624
  }
593
625
  /**
@@ -619,7 +651,7 @@ export declare function jsonDelta<T extends Message>(jsonDelta: NonNullable<Agen
619
651
  *
620
652
  * @template O Agent output message type
621
653
  */
622
- export type AgentProcessAsyncGenerator<O extends Message> = AsyncGenerator<AgentResponseChunk<O>, Partial<O | TransferAgentOutput> | undefined | void>;
654
+ export type AgentProcessAsyncGenerator<O extends Message> = AsyncGenerator<AgentResponseChunk<O>, Partial<O> | TransferAgentOutput | undefined | void>;
623
655
  /**
624
656
  * Result type for agent processing method, can be:
625
657
  * - Direct or streaming response
@@ -709,10 +741,10 @@ export declare class FunctionAgent<I extends Message = Message, O extends Messag
709
741
  * Process input implementation, calls the configured processing function
710
742
  *
711
743
  * @param input Input message
712
- * @param context Execution context
744
+ * @param options Invocation options
713
745
  * @returns Processing result
714
746
  */
715
- process(input: I, context: Context): PromiseOrValue<AgentProcessResult<O>>;
747
+ process(input: I, options: AgentInvokeOptions): PromiseOrValue<AgentProcessResult<O>>;
716
748
  }
717
749
  /**
718
750
  * Function type for function agents
@@ -725,4 +757,4 @@ export declare class FunctionAgent<I extends Message = Message, O extends Messag
725
757
  * @param context Execution context
726
758
  * @returns Processing result, can be synchronous or asynchronous
727
759
  */
728
- export type FunctionAgentFn<I extends Message = any, O extends Message = any> = (input: I, context: Context) => PromiseOrValue<AgentProcessResult<O>>;
760
+ export type FunctionAgentFn<I extends Message = any, O extends Message = any> = (input: I, options: AgentInvokeOptions) => PromiseOrValue<AgentProcessResult<O>>;