@aigne/core 1.13.0 → 1.14.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 (195) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +13 -26
  3. package/README.zh.md +24 -37
  4. package/lib/cjs/agents/agent.d.ts +522 -15
  5. package/lib/cjs/agents/agent.js +357 -36
  6. package/lib/cjs/agents/ai-agent.d.ts +210 -52
  7. package/lib/cjs/agents/ai-agent.js +182 -24
  8. package/lib/cjs/agents/mcp-agent.d.ts +112 -0
  9. package/lib/cjs/agents/mcp-agent.js +79 -1
  10. package/lib/cjs/agents/team-agent.d.ts +99 -0
  11. package/lib/cjs/agents/team-agent.js +94 -0
  12. package/lib/cjs/agents/user-agent.d.ts +6 -4
  13. package/lib/cjs/agents/user-agent.js +16 -5
  14. package/lib/cjs/aigne/aigne.d.ts +263 -16
  15. package/lib/cjs/aigne/aigne.js +130 -20
  16. package/lib/cjs/aigne/context.d.ts +24 -8
  17. package/lib/cjs/aigne/context.js +8 -22
  18. package/lib/cjs/aigne/message-queue.d.ts +26 -4
  19. package/lib/cjs/aigne/message-queue.js +42 -7
  20. package/lib/cjs/aigne/usage.d.ts +9 -0
  21. package/lib/cjs/aigne/usage.js +3 -0
  22. package/lib/cjs/client/client.d.ts +81 -3
  23. package/lib/cjs/client/client.js +38 -0
  24. package/lib/cjs/client/index.d.ts +1 -0
  25. package/lib/cjs/client/index.js +17 -0
  26. package/lib/cjs/index.d.ts +0 -1
  27. package/lib/cjs/index.js +0 -1
  28. package/lib/cjs/loader/agent-js.d.ts +1 -1
  29. package/lib/cjs/loader/agent-js.js +2 -2
  30. package/lib/cjs/loader/agent-yaml.d.ts +3 -2
  31. package/lib/cjs/loader/agent-yaml.js +2 -1
  32. package/lib/cjs/loader/index.d.ts +4 -4
  33. package/lib/cjs/memory/default-memory.d.ts +16 -0
  34. package/lib/cjs/memory/default-memory.js +70 -0
  35. package/lib/cjs/memory/index.d.ts +3 -0
  36. package/lib/cjs/memory/index.js +19 -0
  37. package/lib/cjs/memory/memory.d.ts +89 -0
  38. package/lib/cjs/memory/memory.js +132 -0
  39. package/lib/cjs/memory/recorder.d.ts +86 -0
  40. package/lib/cjs/memory/recorder.js +50 -0
  41. package/lib/cjs/memory/retriever.d.ts +99 -0
  42. package/lib/cjs/memory/retriever.js +51 -0
  43. package/lib/cjs/models/bedrock-chat-model.d.ts +12 -3
  44. package/lib/cjs/models/bedrock-chat-model.js +54 -24
  45. package/lib/cjs/models/chat-model.d.ts +278 -1
  46. package/lib/cjs/models/chat-model.js +54 -0
  47. package/lib/cjs/models/claude-chat-model.d.ts +49 -3
  48. package/lib/cjs/models/claude-chat-model.js +34 -2
  49. package/lib/cjs/models/deepseek-chat-model.d.ts +16 -0
  50. package/lib/cjs/models/deepseek-chat-model.js +16 -0
  51. package/lib/cjs/models/gemini-chat-model.d.ts +14 -0
  52. package/lib/cjs/models/gemini-chat-model.js +14 -0
  53. package/lib/cjs/models/ollama-chat-model.d.ts +16 -0
  54. package/lib/cjs/models/ollama-chat-model.js +16 -0
  55. package/lib/cjs/models/open-router-chat-model.d.ts +16 -0
  56. package/lib/cjs/models/open-router-chat-model.js +16 -0
  57. package/lib/cjs/models/openai-chat-model.d.ts +67 -3
  58. package/lib/cjs/models/openai-chat-model.js +47 -2
  59. package/lib/cjs/models/xai-chat-model.d.ts +16 -0
  60. package/lib/cjs/models/xai-chat-model.js +16 -0
  61. package/lib/cjs/prompt/prompt-builder.d.ts +4 -4
  62. package/lib/cjs/prompt/prompt-builder.js +19 -18
  63. package/lib/cjs/prompt/prompts/memory-message-template.d.ts +1 -0
  64. package/lib/cjs/prompt/prompts/memory-message-template.js +10 -0
  65. package/lib/cjs/prompt/template.js +5 -1
  66. package/lib/cjs/server/error.d.ts +11 -0
  67. package/lib/cjs/server/error.js +11 -0
  68. package/lib/cjs/server/index.d.ts +2 -0
  69. package/lib/cjs/server/index.js +18 -0
  70. package/lib/cjs/server/server.d.ts +89 -8
  71. package/lib/cjs/server/server.js +58 -0
  72. package/lib/cjs/utils/fs.d.ts +2 -0
  73. package/lib/cjs/utils/fs.js +25 -0
  74. package/lib/cjs/utils/prompts.d.ts +1 -0
  75. package/lib/cjs/utils/prompts.js +11 -2
  76. package/lib/cjs/utils/type-utils.d.ts +1 -0
  77. package/lib/cjs/utils/type-utils.js +14 -0
  78. package/lib/dts/agents/agent.d.ts +522 -15
  79. package/lib/dts/agents/ai-agent.d.ts +210 -52
  80. package/lib/dts/agents/mcp-agent.d.ts +112 -0
  81. package/lib/dts/agents/team-agent.d.ts +99 -0
  82. package/lib/dts/agents/user-agent.d.ts +6 -4
  83. package/lib/dts/aigne/aigne.d.ts +263 -16
  84. package/lib/dts/aigne/context.d.ts +24 -8
  85. package/lib/dts/aigne/message-queue.d.ts +26 -4
  86. package/lib/dts/aigne/usage.d.ts +9 -0
  87. package/lib/dts/client/client.d.ts +81 -3
  88. package/lib/dts/client/index.d.ts +1 -0
  89. package/lib/dts/index.d.ts +0 -1
  90. package/lib/dts/loader/agent-js.d.ts +1 -1
  91. package/lib/dts/loader/agent-yaml.d.ts +3 -2
  92. package/lib/dts/loader/index.d.ts +4 -4
  93. package/lib/dts/memory/default-memory.d.ts +16 -0
  94. package/lib/dts/memory/index.d.ts +3 -0
  95. package/lib/dts/memory/memory.d.ts +89 -0
  96. package/lib/dts/memory/recorder.d.ts +86 -0
  97. package/lib/dts/memory/retriever.d.ts +99 -0
  98. package/lib/dts/models/bedrock-chat-model.d.ts +12 -3
  99. package/lib/dts/models/chat-model.d.ts +278 -1
  100. package/lib/dts/models/claude-chat-model.d.ts +49 -3
  101. package/lib/dts/models/deepseek-chat-model.d.ts +16 -0
  102. package/lib/dts/models/gemini-chat-model.d.ts +14 -0
  103. package/lib/dts/models/ollama-chat-model.d.ts +16 -0
  104. package/lib/dts/models/open-router-chat-model.d.ts +16 -0
  105. package/lib/dts/models/openai-chat-model.d.ts +67 -3
  106. package/lib/dts/models/xai-chat-model.d.ts +16 -0
  107. package/lib/dts/prompt/prompt-builder.d.ts +4 -4
  108. package/lib/dts/prompt/prompts/memory-message-template.d.ts +1 -0
  109. package/lib/dts/server/error.d.ts +11 -0
  110. package/lib/dts/server/index.d.ts +2 -0
  111. package/lib/dts/server/server.d.ts +89 -8
  112. package/lib/dts/utils/fs.d.ts +2 -0
  113. package/lib/dts/utils/prompts.d.ts +1 -0
  114. package/lib/dts/utils/type-utils.d.ts +1 -0
  115. package/lib/esm/agents/agent.d.ts +522 -15
  116. package/lib/esm/agents/agent.js +351 -35
  117. package/lib/esm/agents/ai-agent.d.ts +210 -52
  118. package/lib/esm/agents/ai-agent.js +183 -25
  119. package/lib/esm/agents/mcp-agent.d.ts +112 -0
  120. package/lib/esm/agents/mcp-agent.js +79 -1
  121. package/lib/esm/agents/team-agent.d.ts +99 -0
  122. package/lib/esm/agents/team-agent.js +94 -0
  123. package/lib/esm/agents/user-agent.d.ts +6 -4
  124. package/lib/esm/agents/user-agent.js +17 -6
  125. package/lib/esm/aigne/aigne.d.ts +263 -16
  126. package/lib/esm/aigne/aigne.js +132 -22
  127. package/lib/esm/aigne/context.d.ts +24 -8
  128. package/lib/esm/aigne/context.js +9 -22
  129. package/lib/esm/aigne/message-queue.d.ts +26 -4
  130. package/lib/esm/aigne/message-queue.js +42 -8
  131. package/lib/esm/aigne/usage.d.ts +9 -0
  132. package/lib/esm/aigne/usage.js +3 -0
  133. package/lib/esm/client/client.d.ts +81 -3
  134. package/lib/esm/client/client.js +38 -0
  135. package/lib/esm/client/index.d.ts +1 -0
  136. package/lib/esm/client/index.js +1 -0
  137. package/lib/esm/index.d.ts +0 -1
  138. package/lib/esm/index.js +0 -1
  139. package/lib/esm/loader/agent-js.d.ts +1 -1
  140. package/lib/esm/loader/agent-js.js +2 -2
  141. package/lib/esm/loader/agent-yaml.d.ts +3 -2
  142. package/lib/esm/loader/agent-yaml.js +2 -1
  143. package/lib/esm/loader/index.d.ts +4 -4
  144. package/lib/esm/memory/default-memory.d.ts +16 -0
  145. package/lib/esm/memory/default-memory.js +63 -0
  146. package/lib/esm/memory/index.d.ts +3 -0
  147. package/lib/esm/memory/index.js +3 -0
  148. package/lib/esm/memory/memory.d.ts +89 -0
  149. package/lib/esm/memory/memory.js +127 -0
  150. package/lib/esm/memory/recorder.d.ts +86 -0
  151. package/lib/esm/memory/recorder.js +46 -0
  152. package/lib/esm/memory/retriever.d.ts +99 -0
  153. package/lib/esm/memory/retriever.js +47 -0
  154. package/lib/esm/models/bedrock-chat-model.d.ts +12 -3
  155. package/lib/esm/models/bedrock-chat-model.js +56 -26
  156. package/lib/esm/models/chat-model.d.ts +278 -1
  157. package/lib/esm/models/chat-model.js +54 -0
  158. package/lib/esm/models/claude-chat-model.d.ts +49 -3
  159. package/lib/esm/models/claude-chat-model.js +35 -3
  160. package/lib/esm/models/deepseek-chat-model.d.ts +16 -0
  161. package/lib/esm/models/deepseek-chat-model.js +16 -0
  162. package/lib/esm/models/gemini-chat-model.d.ts +14 -0
  163. package/lib/esm/models/gemini-chat-model.js +14 -0
  164. package/lib/esm/models/ollama-chat-model.d.ts +16 -0
  165. package/lib/esm/models/ollama-chat-model.js +16 -0
  166. package/lib/esm/models/open-router-chat-model.d.ts +16 -0
  167. package/lib/esm/models/open-router-chat-model.js +16 -0
  168. package/lib/esm/models/openai-chat-model.d.ts +67 -3
  169. package/lib/esm/models/openai-chat-model.js +47 -2
  170. package/lib/esm/models/xai-chat-model.d.ts +16 -0
  171. package/lib/esm/models/xai-chat-model.js +16 -0
  172. package/lib/esm/prompt/prompt-builder.d.ts +4 -4
  173. package/lib/esm/prompt/prompt-builder.js +20 -19
  174. package/lib/esm/prompt/prompts/memory-message-template.d.ts +1 -0
  175. package/lib/esm/prompt/prompts/memory-message-template.js +7 -0
  176. package/lib/esm/prompt/template.js +5 -1
  177. package/lib/esm/server/error.d.ts +11 -0
  178. package/lib/esm/server/error.js +11 -0
  179. package/lib/esm/server/index.d.ts +2 -0
  180. package/lib/esm/server/index.js +2 -0
  181. package/lib/esm/server/server.d.ts +89 -8
  182. package/lib/esm/server/server.js +58 -0
  183. package/lib/esm/utils/fs.d.ts +2 -0
  184. package/lib/esm/utils/fs.js +21 -0
  185. package/lib/esm/utils/prompts.d.ts +1 -0
  186. package/lib/esm/utils/prompts.js +10 -2
  187. package/lib/esm/utils/type-utils.d.ts +1 -0
  188. package/lib/esm/utils/type-utils.js +13 -0
  189. package/package.json +14 -11
  190. package/lib/cjs/agents/memory.d.ts +0 -26
  191. package/lib/cjs/agents/memory.js +0 -45
  192. package/lib/dts/agents/memory.d.ts +0 -26
  193. package/lib/esm/agents/memory.d.ts +0 -26
  194. package/lib/esm/agents/memory.js +0 -41
  195. /package/{LICENSE → LICENSE.md} +0 -0
@@ -4,10 +4,47 @@ import { createMessage } from "../prompt/prompt-builder.js";
4
4
  import { logger } from "../utils/logger.js";
5
5
  import { agentResponseStreamToObject, asyncGeneratorToReadableStream, isAsyncGenerator, objectToAgentResponseStream, onAgentResponseStreamEnd, } from "../utils/stream-utils.js";
6
6
  import { checkArguments, createAccessorArray, isEmpty, orArrayToArray, } from "../utils/type-utils.js";
7
- import { AgentMemory } from "./memory.js";
8
7
  import { replaceTransferAgentToName, transferToAgentOutput, } from "./types.js";
8
+ export * from "./types.js";
9
+ export const agentOptionsSchema = z.object({
10
+ subscribeTopic: z.union([z.string(), z.array(z.string())]).optional(),
11
+ publishTopic: z
12
+ .union([z.string(), z.array(z.string()), z.custom()])
13
+ .optional(),
14
+ name: z.string().optional(),
15
+ description: z.string().optional(),
16
+ inputSchema: z.custom().optional(),
17
+ outputSchema: z.custom().optional(),
18
+ includeInputInOutput: z.boolean().optional(),
19
+ skills: z.array(z.union([z.custom(), z.custom()])).optional(),
20
+ disableEvents: z.boolean().optional(),
21
+ memory: z.union([z.custom(), z.array(z.custom())]).optional(),
22
+ });
23
+ /**
24
+ * Agent is the base class for all agents.
25
+ * It provides a mechanism for defining input/output schemas and implementing processing logic,
26
+ * serving as the foundation of the entire agent system.
27
+ *
28
+ * By extending the Agent class and implementing the process method, you can create custom agents
29
+ * with various capabilities:
30
+ * - Process structured input and output data
31
+ * - Validate data formats using schemas
32
+ * - Communicate between agents through contexts
33
+ * - Support streaming or non-streaming responses
34
+ * - Maintain memory of past interactions
35
+ * - Output in multiple formats (JSON/text)
36
+ * - Forward tasks to other agents
37
+ *
38
+ * @template I The input message type the agent accepts
39
+ * @template O The output message type the agent returns
40
+ *
41
+ * @example
42
+ * Here's an example of how to create a custom agent:
43
+ * {@includeCode ../../test/agents/agent.test.ts#example-custom-agent}
44
+ */
9
45
  export class Agent {
10
- constructor({ inputSchema, outputSchema, ...options }) {
46
+ constructor(options = {}) {
47
+ const { inputSchema, outputSchema } = options;
11
48
  this.name = options.name || this.constructor.name;
12
49
  this.description = options.description;
13
50
  if (inputSchema)
@@ -22,68 +59,159 @@ export class Agent {
22
59
  if (options.skills?.length)
23
60
  this.skills.push(...options.skills.map(functionToAgent));
24
61
  this.disableEvents = options.disableEvents;
25
- if (options.memory) {
26
- this.memory =
27
- options.memory instanceof AgentMemory
28
- ? options.memory
29
- : typeof options.memory === "boolean"
30
- ? new AgentMemory({ enabled: options.memory })
31
- : new AgentMemory(options.memory);
62
+ if (Array.isArray(options.memory)) {
63
+ this.memories.push(...options.memory);
64
+ }
65
+ else if (options.memory) {
66
+ this.memories.push(options.memory);
32
67
  }
33
68
  }
34
- memory;
69
+ /**
70
+ * List of memories this agent can use
71
+ */
72
+ memories = [];
73
+ /**
74
+ * Name of the agent, used for identification and logging
75
+ *
76
+ * Defaults to the class constructor name if not specified in options
77
+ */
35
78
  name;
36
79
  /**
37
- * Default topic this agent will subscribe to
80
+ * Default topic this agent subscribes to
81
+ *
82
+ * Each agent has a default topic in the format "$agent_[agent name]"
83
+ * The agent automatically subscribes to this topic to receive messages
84
+ *
85
+ * @returns The default topic string
38
86
  */
39
87
  get topic() {
40
88
  return `$agent_${this.name}`;
41
89
  }
90
+ /**
91
+ * Description of the agent's purpose and capabilities
92
+ *
93
+ * Useful for documentation and when agents need to understand
94
+ * each other's roles in a multi-agent system
95
+ */
42
96
  description;
43
97
  _inputSchema;
44
98
  _outputSchema;
99
+ /**
100
+ * Get the input data schema for this agent
101
+ *
102
+ * Used to validate that input messages conform to required format
103
+ * If no input schema is set, returns an empty object schema by default
104
+ *
105
+ * @returns The Zod type definition for input data
106
+ */
45
107
  get inputSchema() {
46
108
  const s = this._inputSchema;
47
109
  const schema = typeof s === "function" ? s(this) : s || z.object({});
48
110
  checkAgentInputOutputSchema(schema);
49
111
  return schema.passthrough();
50
112
  }
113
+ /**
114
+ * Get the output data schema for this agent
115
+ *
116
+ * Used to validate that output messages conform to required format
117
+ * If no output schema is set, returns an empty object schema by default
118
+ *
119
+ * @returns The Zod type definition for output data
120
+ */
51
121
  get outputSchema() {
52
122
  const s = this._outputSchema;
53
123
  const schema = typeof s === "function" ? s(this) : s || z.object({});
54
124
  checkAgentInputOutputSchema(schema);
55
125
  return schema.passthrough();
56
126
  }
127
+ /**
128
+ * Whether to include the original input in the output
129
+ *
130
+ * When true, the agent will merge input fields into the output object
131
+ */
57
132
  includeInputInOutput;
133
+ /**
134
+ * Topics the agent subscribes to for receiving messages
135
+ *
136
+ * Can be a single topic string or an array of topic strings
137
+ */
58
138
  subscribeTopic;
139
+ /**
140
+ * Topics the agent publishes to for sending messages
141
+ *
142
+ * Can be a string, array of strings, or a function that determines
143
+ * topics based on the output
144
+ */
59
145
  publishTopic;
146
+ /**
147
+ * Collection of skills (other agents) this agent can use
148
+ *
149
+ * Skills can be accessed by name or by array index, allowing
150
+ * the agent to delegate tasks to specialized sub-agents
151
+ */
60
152
  skills = createAccessorArray([], (arr, name) => arr.find((t) => t.name === name));
153
+ /**
154
+ * Whether to disable emitting events for agent actions
155
+ *
156
+ * When true, the agent won't emit events like agentStarted,
157
+ * agentSucceed, or agentFailed
158
+ */
61
159
  disableEvents;
160
+ subscriptions = [];
62
161
  /**
63
162
  * Attach agent to context:
64
- * - subscribe to topic and invoke process method when message received
65
- * - subscribe to memory topic if memory is enabled
66
- * @param context Context to attach
163
+ * - Subscribe to topics and invoke process method when messages are received
164
+ * - Subscribe to memory topics if memory is enabled
165
+ *
166
+ * Agents can receive messages and respond through the topic subscription system,
167
+ * enabling inter-agent communication.
168
+ *
169
+ * @param context Context to attach to
67
170
  */
68
171
  attach(context) {
69
- this.memory?.attach(context);
172
+ for (const memory of this.memories) {
173
+ memory.attach(context);
174
+ }
175
+ this.subscribeToTopics(context);
176
+ }
177
+ subscribeToTopics(context) {
70
178
  for (const topic of orArrayToArray(this.subscribeTopic).concat(this.topic)) {
71
- context.subscribe(topic, async ({ message, context }) => {
72
- try {
73
- await context.invoke(this, message);
74
- }
75
- catch (error) {
76
- context.emit("agentFailed", { agent: this, error });
77
- }
78
- });
179
+ this.subscriptions.push(context.subscribe(topic, (payload) => this.onMessage(payload)));
79
180
  }
80
181
  }
182
+ async onMessage({ message, context }) {
183
+ try {
184
+ await context.invoke(this, message);
185
+ }
186
+ catch (error) {
187
+ context.emit("agentFailed", { agent: this, error });
188
+ }
189
+ }
190
+ /**
191
+ * Add skills (other agents or functions) to this agent
192
+ *
193
+ * Skills allow agents to reuse functionality from other agents,
194
+ * building more complex behaviors.
195
+ *
196
+ * @param skills List of skills to add, can be Agent instances or functions
197
+ */
81
198
  addSkill(...skills) {
82
199
  this.skills.push(...skills.map((skill) => (typeof skill === "function" ? functionToAgent(skill) : skill)));
83
200
  }
201
+ /**
202
+ * Check if the agent is invokable
203
+ *
204
+ * An agent is invokable if it has implemented the process method
205
+ */
84
206
  get isInvokable() {
85
207
  return !!this.process;
86
208
  }
209
+ /**
210
+ * Check context status to ensure it hasn't timed out
211
+ *
212
+ * @param context The context to check
213
+ * @throws Error if the context has timed out
214
+ */
87
215
  checkContextStatus(context) {
88
216
  if (context) {
89
217
  const { status } = context;
@@ -105,7 +233,7 @@ export class Agent {
105
233
  const parsedInput = checkArguments(`Agent ${this.name} input`, this.inputSchema, message);
106
234
  this.preprocess(parsedInput, ctx);
107
235
  this.checkContextStatus(ctx);
108
- let response = await this.process(parsedInput, ctx, options);
236
+ let response = await this.process(parsedInput, ctx);
109
237
  if (response instanceof Agent) {
110
238
  response = transferToAgentOutput(response);
111
239
  }
@@ -138,6 +266,16 @@ export class Agent {
138
266
  this.processAgentError(error, ctx);
139
267
  }
140
268
  }
269
+ /**
270
+ * Process agent output
271
+ *
272
+ * Validates output format, applies post-processing operations, and triggers success events
273
+ *
274
+ * @param input Original input message
275
+ * @param output Raw output produced by the agent
276
+ * @param context Execution context
277
+ * @returns Final processed output
278
+ */
141
279
  async processAgentOutput(input, output, context) {
142
280
  const parsedOutput = checkArguments(`Agent ${this.name} output`, this.outputSchema, output);
143
281
  const finalOutput = this.includeInputInOutput ? { ...input, ...parsedOutput } : parsedOutput;
@@ -147,12 +285,30 @@ export class Agent {
147
285
  context.emit("agentSucceed", { agent: this, output: finalOutput });
148
286
  return finalOutput;
149
287
  }
288
+ /**
289
+ * Process errors that occur during agent execution
290
+ *
291
+ * Logs error information, triggers failure events, and re-throws the error
292
+ *
293
+ * @param error Caught error
294
+ * @param context Execution context
295
+ * @throws Always throws the received error
296
+ */
150
297
  processAgentError(error, context) {
151
298
  logger.core("Invoke agent %s failed with error: %O", this.name, error);
152
299
  if (!this.disableEvents)
153
300
  context.emit("agentFailed", { agent: this, error });
154
301
  throw error;
155
302
  }
303
+ /**
304
+ * Check agent invocation usage to prevent exceeding limits
305
+ *
306
+ * If the context has a maximum invocation limit set, checks if the limit
307
+ * has been exceeded and increments the invocation counter
308
+ *
309
+ * @param context Execution context
310
+ * @throws Error if maximum invocation limit is exceeded
311
+ */
156
312
  checkAgentInvokesUsage(context) {
157
313
  const { limits, usage } = context;
158
314
  if (limits?.maxAgentInvokes && usage.agentCalls >= limits.maxAgentInvokes) {
@@ -160,50 +316,210 @@ export class Agent {
160
316
  }
161
317
  usage.agentCalls++;
162
318
  }
319
+ /**
320
+ * Pre-processing operations before handling input
321
+ *
322
+ * Preparatory work done before executing the agent's main processing logic, including:
323
+ * - Checking context status
324
+ * - Verifying invocation limits
325
+ *
326
+ * @param _ Input message (unused)
327
+ * @param context Execution context
328
+ */
163
329
  preprocess(_, context) {
164
330
  this.checkContextStatus(context);
165
331
  this.checkAgentInvokesUsage(context);
166
332
  }
333
+ /**
334
+ * Post-processing operations after handling output
335
+ *
336
+ * Operations performed after the agent produces output, including:
337
+ * - Checking context status
338
+ * - Adding interaction records to memory
339
+ *
340
+ * @param input Input message
341
+ * @param output Output message
342
+ * @param context Execution context
343
+ */
167
344
  postprocess(input, output, context) {
168
345
  this.checkContextStatus(context);
169
- this.memory?.addMemory({ role: "user", content: input });
170
- this.memory?.addMemory({
171
- role: "agent",
172
- content: replaceTransferAgentToName(output),
173
- source: this.name,
174
- });
346
+ this.publishToTopics(output, context);
347
+ for (const memory of this.memories) {
348
+ if (memory.autoUpdate) {
349
+ memory.record({
350
+ content: [
351
+ { role: "user", content: input },
352
+ { role: "agent", content: replaceTransferAgentToName(output), source: this.name },
353
+ ],
354
+ }, context);
355
+ }
356
+ }
175
357
  }
358
+ async publishToTopics(output, context) {
359
+ const publishTopics = typeof this.publishTopic === "function" ? await this.publishTopic(output) : this.publishTopic;
360
+ if (publishTopics?.length) {
361
+ context.publish(publishTopics, {
362
+ role: this.constructor.name === "UserAgent" ? "user" : "agent",
363
+ source: this.name,
364
+ message: output,
365
+ });
366
+ }
367
+ }
368
+ /**
369
+ * Shut down the agent and clean up resources
370
+ *
371
+ * Primarily used to clean up memory and other resources to prevent memory leaks
372
+ *
373
+ * @example
374
+ * Here's an example of shutting down an agent:
375
+ * {@includeCode ../../test/agents/agent.test.ts#example-agent-shutdown}
376
+ *
377
+ * @example
378
+ * Here's an example of shutting down an agent by using statement:
379
+ * {@includeCode ../../test/agents/agent.test.ts#example-agent-shutdown-by-using}
380
+ */
176
381
  async shutdown() {
177
- this.memory?.detach();
382
+ for (const sub of this.subscriptions) {
383
+ sub();
384
+ }
385
+ this.subscriptions = [];
386
+ for (const m of this.memories) {
387
+ m.shutdown();
388
+ }
178
389
  }
390
+ /**
391
+ * Custom object inspection behavior
392
+ *
393
+ * When using Node.js's util.inspect function to inspect an agent,
394
+ * only the agent's name will be shown, making output more concise
395
+ *
396
+ * @returns Agent name
397
+ */
179
398
  [inspect.custom]() {
180
399
  return this.name;
181
400
  }
401
+ /**
402
+ * Async dispose method for shutdown the agent
403
+ *
404
+ * @example
405
+ * Here's an example of shutting down an agent by using statement:
406
+ * {@includeCode ../../test/agents/agent.test.ts#example-agent-shutdown-by-using}
407
+ */
408
+ async [Symbol.asyncDispose]() {
409
+ await this.shutdown();
410
+ }
182
411
  }
412
+ /**
413
+ * Check if a response chunk is empty
414
+ *
415
+ * @template T Response data type
416
+ * @param chunk The response chunk to check
417
+ * @returns True if the chunk is empty
418
+ */
183
419
  export function isEmptyChunk(chunk) {
184
420
  return isEmpty(chunk.delta.json) && isEmpty(chunk.delta.text);
185
421
  }
422
+ /**
423
+ * Creates a text delta for streaming responses
424
+ *
425
+ * This utility function creates an AgentResponseDelta object with only the text part,
426
+ * useful for incrementally building streaming text responses in agents.
427
+ *
428
+ * @template T Agent message type extending Message
429
+ * @param textDelta The text content to include in the delta update
430
+ * @returns An AgentResponseDelta with the text delta wrapped in the expected structure
431
+ */
432
+ export function textDelta(textDelta) {
433
+ return { delta: { text: textDelta } };
434
+ }
435
+ /**
436
+ * Creates a JSON delta for streaming responses
437
+ *
438
+ * This utility function creates an AgentResponseDelta object with only the JSON part,
439
+ * useful for incrementally building structured data responses in streaming mode.
440
+ *
441
+ * @template T Agent message type extending Message
442
+ * @param jsonDelta The JSON data to include in the delta update
443
+ * @returns An AgentResponseDelta with the JSON delta wrapped in the expected structure
444
+ */
445
+ export function jsonDelta(jsonDelta) {
446
+ return { delta: { json: jsonDelta } };
447
+ }
186
448
  function checkAgentInputOutputSchema(schema) {
187
449
  if (!(schema instanceof ZodObject) && typeof schema !== "function") {
188
450
  throw new Error(`schema must be a zod object or function return a zod object, got: ${typeof schema}`);
189
451
  }
190
452
  }
453
+ /**
454
+ * Function agent class, implements agent logic through a function
455
+ *
456
+ * Provides a convenient way to create agents using functions without
457
+ * needing to extend the Agent class
458
+ *
459
+ * @template I Agent input message type
460
+ * @template O Agent output message type
461
+ *
462
+ * @example
463
+ * Here's an example of creating a function agent:
464
+ * {@includeCode ../../test/agents/agent.test.ts#example-function-agent}
465
+ */
191
466
  export class FunctionAgent extends Agent {
467
+ /**
468
+ * Create a function agent from a function or options
469
+ *
470
+ * Provides a convenient factory method to create an agent directly from a function
471
+ *
472
+ * @param options Function agent options or function
473
+ * @returns New function agent instance
474
+ *
475
+ * @example
476
+ * Here's an example of creating a function agent from a function:
477
+ * {@includeCode ../../test/agents/agent.test.ts#example-function-agent-from-function}
478
+ *
479
+ * @example
480
+ * Here's an example of creating a function agent without basic agent options:
481
+ * {@includeCode ../../test/agents/agent.test.ts#example-function-agent}
482
+ *
483
+ * @example
484
+ * Here's an example of creating a function agent from a function returning a stream:
485
+ * {@includeCode ../../test/agents/agent.test.ts#example-function-agent-stream}
486
+ *
487
+ * @example
488
+ * Here's an example of creating a function agent from a function returning an async generator:
489
+ * {@includeCode ../../test/agents/agent.test.ts#example-function-agent-async-generator}
490
+ */
192
491
  static from(options) {
193
492
  return typeof options === "function" ? functionToAgent(options) : new FunctionAgent(options);
194
493
  }
494
+ /**
495
+ * Create a function agent instance
496
+ *
497
+ * @param options Function agent configuration options
498
+ */
195
499
  constructor(options) {
196
500
  super(options);
197
- this.fn = options.fn ?? (() => ({}));
501
+ this._process = options.process;
198
502
  }
199
- fn;
503
+ /**
504
+ * Stores the function used to process agent input and generate output
505
+ *
506
+ * @private
507
+ */
508
+ _process;
509
+ /**
510
+ * Process input implementation, calls the configured processing function
511
+ *
512
+ * @param input Input message
513
+ * @param context Execution context
514
+ * @returns Processing result
515
+ */
200
516
  process(input, context) {
201
- return this.fn(input, context);
517
+ return this._process(input, context);
202
518
  }
203
519
  }
204
520
  function functionToAgent(agent) {
205
521
  if (typeof agent === "function") {
206
- return FunctionAgent.from({ name: agent.name, fn: agent });
522
+ return FunctionAgent.from({ name: agent.name, process: agent });
207
523
  }
208
524
  return agent;
209
525
  }