@aigne/core 1.19.0 → 1.20.1

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 (54) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/lib/cjs/agents/agent.d.ts +11 -6
  3. package/lib/cjs/agents/agent.js +8 -10
  4. package/lib/cjs/agents/ai-agent.d.ts +18 -6
  5. package/lib/cjs/agents/ai-agent.js +14 -4
  6. package/lib/cjs/agents/guide-rail-agent.d.ts +1 -1
  7. package/lib/cjs/agents/mcp-agent.d.ts +1 -1
  8. package/lib/cjs/aigne/aigne.d.ts +10 -10
  9. package/lib/cjs/aigne/context.d.ts +8 -6
  10. package/lib/cjs/aigne/context.js +62 -42
  11. package/lib/cjs/aigne/message-queue.d.ts +1 -1
  12. package/lib/cjs/aigne/message-queue.js +2 -3
  13. package/lib/cjs/aigne/usage.d.ts +1 -0
  14. package/lib/cjs/aigne/usage.js +1 -0
  15. package/lib/cjs/loader/agent-yaml.d.ts +2 -1
  16. package/lib/cjs/loader/agent-yaml.js +4 -0
  17. package/lib/cjs/prompt/prompt-builder.d.ts +2 -16
  18. package/lib/cjs/prompt/prompt-builder.js +12 -25
  19. package/lib/cjs/utils/stream-utils.d.ts +1 -2
  20. package/lib/cjs/utils/type-utils.d.ts +1 -0
  21. package/lib/cjs/utils/type-utils.js +13 -0
  22. package/lib/dts/agents/agent.d.ts +11 -6
  23. package/lib/dts/agents/ai-agent.d.ts +18 -6
  24. package/lib/dts/agents/guide-rail-agent.d.ts +1 -1
  25. package/lib/dts/agents/mcp-agent.d.ts +1 -1
  26. package/lib/dts/aigne/aigne.d.ts +10 -10
  27. package/lib/dts/aigne/context.d.ts +8 -6
  28. package/lib/dts/aigne/message-queue.d.ts +1 -1
  29. package/lib/dts/aigne/usage.d.ts +1 -0
  30. package/lib/dts/loader/agent-yaml.d.ts +2 -1
  31. package/lib/dts/prompt/prompt-builder.d.ts +2 -16
  32. package/lib/dts/utils/stream-utils.d.ts +1 -2
  33. package/lib/dts/utils/type-utils.d.ts +1 -0
  34. package/lib/esm/agents/agent.d.ts +11 -6
  35. package/lib/esm/agents/agent.js +8 -10
  36. package/lib/esm/agents/ai-agent.d.ts +18 -6
  37. package/lib/esm/agents/ai-agent.js +15 -5
  38. package/lib/esm/agents/guide-rail-agent.d.ts +1 -1
  39. package/lib/esm/agents/mcp-agent.d.ts +1 -1
  40. package/lib/esm/aigne/aigne.d.ts +10 -10
  41. package/lib/esm/aigne/context.d.ts +8 -6
  42. package/lib/esm/aigne/context.js +63 -43
  43. package/lib/esm/aigne/message-queue.d.ts +1 -1
  44. package/lib/esm/aigne/message-queue.js +2 -3
  45. package/lib/esm/aigne/usage.d.ts +1 -0
  46. package/lib/esm/aigne/usage.js +1 -0
  47. package/lib/esm/loader/agent-yaml.d.ts +2 -1
  48. package/lib/esm/loader/agent-yaml.js +4 -0
  49. package/lib/esm/prompt/prompt-builder.d.ts +2 -16
  50. package/lib/esm/prompt/prompt-builder.js +12 -23
  51. package/lib/esm/utils/stream-utils.d.ts +1 -2
  52. package/lib/esm/utils/type-utils.d.ts +1 -0
  53. package/lib/esm/utils/type-utils.js +12 -0
  54. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@
5
5
 
6
6
  * add user context support ([#131](https://github.com/AIGNE-io/aigne-framework/issues/131)) ([4dd9d20](https://github.com/AIGNE-io/aigne-framework/commit/4dd9d20953f6ac33933723db56efd9b44bafeb02))
7
7
 
8
+ ## [1.20.1](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.20.0...core-v1.20.1) (2025-06-19)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * use `inputKey` instead of implicit $message for AIAgent ([#165](https://github.com/AIGNE-io/aigne-framework/issues/165)) ([8b6e589](https://github.com/AIGNE-io/aigne-framework/commit/8b6e5896bba8209fd2eecb0f5b9263618bffdaf8))
14
+
15
+
16
+ ### Dependencies
17
+
18
+ * The following workspace dependencies were updated
19
+ * dependencies
20
+ * @aigne/platform-helpers bumped to 0.1.2
21
+
22
+ ## [1.20.0](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.19.0...core-v1.20.0) (2025-06-17)
23
+
24
+
25
+ ### Features
26
+
27
+ * support return $meta output by enable returnMetadata option ([#163](https://github.com/AIGNE-io/aigne-framework/issues/163)) ([ac73759](https://github.com/AIGNE-io/aigne-framework/commit/ac73759615d44a09fa71b3bfbd3e9356ffe1d2ed))
28
+
8
29
  ## [1.19.0](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.18.6...core-v1.19.0) (2025-06-16)
9
30
 
10
31
 
@@ -2,6 +2,7 @@ import { nodejs } from "@aigne/platform-helpers/nodejs/index.js";
2
2
  import { ZodObject, type ZodType } from "zod";
3
3
  import type { AgentEvent, Context, UserContext } from "../aigne/context.js";
4
4
  import type { MessagePayload } from "../aigne/message-queue.js";
5
+ import type { ContextUsage } from "../aigne/usage.js";
5
6
  import type { Memory, MemoryAgent } from "../memory/memory.js";
6
7
  import type { MemoryRecorderInput } from "../memory/recorder.js";
7
8
  import type { MemoryRetrieverInput } from "../memory/retriever.js";
@@ -12,7 +13,11 @@ export * from "./types.js";
12
13
  /**
13
14
  * Basic message type that can contain any key-value pairs
14
15
  */
15
- export type Message = Record<string, unknown>;
16
+ export interface Message extends Record<string, unknown> {
17
+ $meta?: {
18
+ usage: ContextUsage;
19
+ };
20
+ }
16
21
  /**
17
22
  * Topics the agent subscribes to, can be a single topic string or an array of topic strings
18
23
  */
@@ -328,7 +333,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
328
333
  * Regular mode waits for the agent to complete processing and return the final result,
329
334
  * suitable for scenarios where a complete result is needed at once.
330
335
  *
331
- * @param input Input message to the agent, can be a string or structured object
336
+ * @param input Input message to the agent
332
337
  * @param options Invocation options, must set streaming to false or leave unset
333
338
  * @returns Final JSON response
334
339
  *
@@ -336,7 +341,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
336
341
  * Here's an example of invoking an agent with regular mode:
337
342
  * {@includeCode ../../test/agents/agent.test.ts#example-invoke}
338
343
  */
339
- invoke(input: I | string, options?: Partial<AgentInvokeOptions> & {
344
+ invoke(input: I, options?: Partial<AgentInvokeOptions> & {
340
345
  streaming?: false;
341
346
  }): Promise<O>;
342
347
  /**
@@ -346,7 +351,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
346
351
  * suitable for scenarios requiring real-time progress updates, such as
347
352
  * chat bot typing effects.
348
353
  *
349
- * @param input Input message to the agent, can be a string or structured object
354
+ * @param input Input message to the agent
350
355
  * @param options Invocation options, must set streaming to true for this overload
351
356
  * @returns Streaming response object
352
357
  *
@@ -354,7 +359,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
354
359
  * Here's an example of invoking an agent with streaming response:
355
360
  * {@includeCode ../../test/agents/agent.test.ts#example-invoke-streaming}
356
361
  */
357
- invoke(input: I | string, options: Partial<AgentInvokeOptions> & {
362
+ invoke(input: I, options: Partial<AgentInvokeOptions> & {
358
363
  streaming: true;
359
364
  }): Promise<AgentResponseStream<O>>;
360
365
  /**
@@ -366,7 +371,7 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
366
371
  * @param options Invocation options
367
372
  * @returns Agent response (streaming or regular)
368
373
  */
369
- invoke(input: I | string, options?: Partial<AgentInvokeOptions>): Promise<AgentResponse<O>>;
374
+ invoke(input: I, options?: Partial<AgentInvokeOptions>): Promise<AgentResponse<O>>;
370
375
  protected invokeSkill<I extends Message, O extends Message>(skill: Agent<I, O>, input: I, options: AgentInvokeOptions): Promise<O>;
371
376
  /**
372
377
  * Process agent output
@@ -44,7 +44,6 @@ exports.textDelta = textDelta;
44
44
  exports.jsonDelta = jsonDelta;
45
45
  const index_js_1 = require("@aigne/platform-helpers/nodejs/index.js");
46
46
  const zod_1 = require("zod");
47
- const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
48
47
  const logger_js_1 = require("../utils/logger.js");
49
48
  const stream_utils_js_1 = require("../utils/stream-utils.js");
50
49
  const type_utils_js_1 = require("../utils/type-utils.js");
@@ -317,7 +316,7 @@ class Agent {
317
316
  for (const memory of this.memories) {
318
317
  const ms = (await memory.retrieve({
319
318
  ...input,
320
- search: typeof input === "string" ? input : input && (0, prompt_builder_js_1.getMessage)(input),
319
+ search: typeof input.search === "string" ? input.search : JSON.stringify(input.search),
321
320
  limit: input.limit ?? this.maxRetrieveMemoryCount,
322
321
  }, options.context)).memories;
323
322
  memories.push(...ms);
@@ -344,13 +343,12 @@ class Agent {
344
343
  opts.context.memories.push(...options.memories);
345
344
  options.memories = undefined;
346
345
  }
347
- const message = typeof input === "string" ? (0, prompt_builder_js_1.createMessage)(input) : input;
348
346
  logger_js_1.logger.debug("Invoke agent %s started with input: %O", this.name, input);
349
347
  if (!this.disableEvents)
350
- opts.context.emit("agentStarted", { agent: this, input: message });
348
+ opts.context.emit("agentStarted", { agent: this, input });
351
349
  try {
352
- await this.hooks.onStart?.({ context: opts.context, input: message });
353
- const parsedInput = (0, type_utils_js_1.checkArguments)(`Agent ${this.name} input`, this.inputSchema, message);
350
+ await this.hooks.onStart?.({ context: opts.context, input });
351
+ const parsedInput = (0, type_utils_js_1.checkArguments)(`Agent ${this.name} input`, this.inputSchema, input);
354
352
  await this.preprocess(parsedInput, opts);
355
353
  this.checkContextStatus(opts);
356
354
  let response = await this.process(parsedInput, opts);
@@ -363,23 +361,23 @@ class Agent {
363
361
  : (0, stream_utils_js_1.isAsyncGenerator)(response)
364
362
  ? (0, stream_utils_js_1.asyncGeneratorToReadableStream)(response)
365
363
  : (0, stream_utils_js_1.objectToAgentResponseStream)(response);
366
- return this.checkResponseByGuideRails(message, (0, stream_utils_js_1.onAgentResponseStreamEnd)(stream, {
364
+ return this.checkResponseByGuideRails(input, (0, stream_utils_js_1.onAgentResponseStreamEnd)(stream, {
367
365
  onResult: async (result) => {
368
366
  return await this.processAgentOutput(parsedInput, result, opts);
369
367
  },
370
368
  onError: async (error) => {
371
- return await this.processAgentError(message, error, opts);
369
+ return await this.processAgentError(input, error, opts);
372
370
  },
373
371
  }), opts);
374
372
  }
375
- return await this.checkResponseByGuideRails(message, this.processAgentOutput(parsedInput, response instanceof ReadableStream
373
+ return await this.checkResponseByGuideRails(input, this.processAgentOutput(parsedInput, response instanceof ReadableStream
376
374
  ? await (0, stream_utils_js_1.agentResponseStreamToObject)(response)
377
375
  : (0, stream_utils_js_1.isAsyncGenerator)(response)
378
376
  ? await (0, stream_utils_js_1.agentResponseStreamToObject)(response)
379
377
  : response, opts), opts);
380
378
  }
381
379
  catch (error) {
382
- throw await this.processAgentError(message, error, opts);
380
+ throw await this.processAgentError(input, error, opts);
383
381
  }
384
382
  }
385
383
  async invokeSkill(skill, input, options) {
@@ -12,7 +12,7 @@ import type { GuideRailAgentOutput } from "./guide-rail-agent.js";
12
12
  * @template I The input message type the agent accepts
13
13
  * @template O The output message type the agent returns
14
14
  */
15
- export interface AIAgentOptions<I extends Message = Message, O extends Message = Message> extends AgentOptions<I, O> {
15
+ export interface AIAgentOptions<InputKey extends string = string, I extends Message & InputMessage<InputKey> = Message & InputMessage<InputKey>, O extends Message = Message> extends AgentOptions<Omit<I, InputKey> & Partial<InputMessage<InputKey>>, O> {
16
16
  /**
17
17
  * The language model to use for this agent
18
18
  *
@@ -26,10 +26,14 @@ export interface AIAgentOptions<I extends Message = Message, O extends Message =
26
26
  * more complex prompt templates
27
27
  */
28
28
  instructions?: string | PromptBuilder;
29
+ /**
30
+ * Pick a message from input to use as the user's message
31
+ */
32
+ inputKey?: InputKey;
29
33
  /**
30
34
  * Custom key to use for text output in the response
31
35
  *
32
- * Defaults to $message if not specified
36
+ * Defaults to `message` if not specified
33
37
  */
34
38
  outputKey?: string;
35
39
  /**
@@ -106,6 +110,9 @@ export declare const aiAgentToolChoiceSchema: z.ZodUnion<[z.ZodNativeEnum<typeof
106
110
  export declare const aiAgentOptionsSchema: ZodObject<{
107
111
  [key in keyof AIAgentOptions]: ZodType<AIAgentOptions[key]>;
108
112
  }>;
113
+ type InputMessage<K> = K extends string ? {
114
+ [key in K]: string;
115
+ } : Message;
109
116
  /**
110
117
  * AI-powered agent that leverages language models
111
118
  *
@@ -126,7 +133,7 @@ export declare const aiAgentOptionsSchema: ZodObject<{
126
133
  * Basic AIAgent creation:
127
134
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-basic}
128
135
  */
129
- export declare class AIAgent<I extends Message = Message, O extends Message = Message> extends Agent<I, O> {
136
+ export declare class AIAgent<InputKey extends string = string, I extends Message & InputMessage<InputKey> = Message & InputMessage<InputKey>, O extends Message = Message> extends Agent<I, O> {
130
137
  /**
131
138
  * Create an AIAgent with the specified options
132
139
  *
@@ -139,13 +146,13 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
139
146
  * AI agent with custom instructions:
140
147
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-instructions}
141
148
  */
142
- static from<I extends Message, O extends Message>(options: AIAgentOptions<I, O>): AIAgent<I, O>;
149
+ static from<InputKey extends string, I extends Message & InputMessage<InputKey>, O extends Message>(options: AIAgentOptions<InputKey, I, O>): AIAgent<InputKey, I, O>;
143
150
  /**
144
151
  * Create an AIAgent instance
145
152
  *
146
153
  * @param options Configuration options for the AI agent
147
154
  */
148
- constructor(options: AIAgentOptions<I, O>);
155
+ constructor(options: AIAgentOptions<InputKey, I, O>);
149
156
  /**
150
157
  * The language model used by this agent
151
158
  *
@@ -163,6 +170,10 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
163
170
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
164
171
  */
165
172
  instructions: PromptBuilder;
173
+ /**
174
+ * Pick a message from input to use as the user's message
175
+ */
176
+ inputKey?: InputKey;
166
177
  /**
167
178
  * Custom key to use for text output in the response
168
179
  *
@@ -170,7 +181,7 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
170
181
  * Setting a custom output key:
171
182
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-custom-output-key}
172
183
  */
173
- outputKey?: string;
184
+ outputKey: string;
174
185
  /**
175
186
  * Controls how the agent uses tools during execution
176
187
  *
@@ -224,3 +235,4 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
224
235
  */
225
236
  _processRouter(input: I, model: ChatModel, modelInput: ChatModelInput, options: AgentInvokeOptions, toolsMap: Map<string, Agent>): AgentProcessAsyncGenerator<O>;
226
237
  }
238
+ export {};
@@ -8,6 +8,7 @@ const type_utils_js_1 = require("../utils/type-utils.js");
8
8
  const agent_js_1 = require("./agent.js");
9
9
  const chat_model_js_1 = require("./chat-model.js");
10
10
  const types_js_1 = require("./types.js");
11
+ const DEFAULT_OUTPUT_KEY = "message";
11
12
  /**
12
13
  * Tool choice options for AI agents
13
14
  *
@@ -52,6 +53,7 @@ exports.aiAgentToolChoiceSchema = zod_1.z.union([zod_1.z.nativeEnum(AIAgentToolC
52
53
  exports.aiAgentOptionsSchema = agent_js_1.agentOptionsSchema.extend({
53
54
  model: zod_1.z.instanceof(chat_model_js_1.ChatModel).optional(),
54
55
  instructions: zod_1.z.union([zod_1.z.string(), zod_1.z.instanceof(prompt_builder_js_1.PromptBuilder)]).optional(),
56
+ inputKey: zod_1.z.string().optional(),
55
57
  outputKey: zod_1.z.string().optional(),
56
58
  toolChoice: exports.aiAgentToolChoiceSchema.optional(),
57
59
  memoryAgentsAsTools: zod_1.z.boolean().optional(),
@@ -99,19 +101,23 @@ class AIAgent extends agent_js_1.Agent {
99
101
  * @param options Configuration options for the AI agent
100
102
  */
101
103
  constructor(options) {
102
- super(options);
104
+ super({ ...options, inputSchema: options.inputSchema });
103
105
  (0, type_utils_js_1.checkArguments)("AIAgent", exports.aiAgentOptionsSchema, options);
104
106
  this.model = options.model;
105
107
  this.instructions =
106
108
  typeof options.instructions === "string"
107
109
  ? prompt_builder_js_1.PromptBuilder.from(options.instructions)
108
110
  : (options.instructions ?? new prompt_builder_js_1.PromptBuilder());
109
- this.outputKey = options.outputKey;
111
+ this.inputKey = options.inputKey;
112
+ this.outputKey = options.outputKey || DEFAULT_OUTPUT_KEY;
110
113
  this.toolChoice = options.toolChoice;
111
114
  this.memoryAgentsAsTools = options.memoryAgentsAsTools;
112
115
  this.memoryPromptTemplate = options.memoryPromptTemplate;
113
116
  if (typeof options.catchToolsError === "boolean")
114
117
  this.catchToolsError = options.catchToolsError;
118
+ if (!this.inputKey && !this.instructions) {
119
+ throw new Error("AIAgent requires either inputKey or instructions to be set");
120
+ }
115
121
  }
116
122
  /**
117
123
  * The language model used by this agent
@@ -130,6 +136,10 @@ class AIAgent extends agent_js_1.Agent {
130
136
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
131
137
  */
132
138
  instructions;
139
+ /**
140
+ * Pick a message from input to use as the user's message
141
+ */
142
+ inputKey;
133
143
  /**
134
144
  * Custom key to use for text output in the response
135
145
  *
@@ -194,7 +204,7 @@ class AIAgent extends agent_js_1.Agent {
194
204
  return yield* this._processRouter(input, model, modelInput, options, toolsMap);
195
205
  }
196
206
  const toolCallMessages = [];
197
- const outputKey = this.outputKey || prompt_builder_js_1.MESSAGE_KEY;
207
+ const outputKey = this.outputKey;
198
208
  for (;;) {
199
209
  const modelOutput = {};
200
210
  const stream = await options.context.invoke(model, { ...modelInput, messages: modelInput.messages.concat(toolCallMessages) }, { streaming: true });
@@ -254,7 +264,7 @@ class AIAgent extends agent_js_1.Agent {
254
264
  }
255
265
  }
256
266
  async onGuideRailError(error) {
257
- const outputKey = this.outputKey || prompt_builder_js_1.MESSAGE_KEY;
267
+ const outputKey = this.outputKey || DEFAULT_OUTPUT_KEY;
258
268
  return {
259
269
  [outputKey]: error.reason,
260
270
  };
@@ -59,4 +59,4 @@ export interface GuideRailAgentOutput extends Message {
59
59
  * - Monitor and audit agent behavior
60
60
  */
61
61
  export type GuideRailAgent = Agent<GuideRailAgentInput, GuideRailAgentOutput>;
62
- export declare const guideRailAgentOptions: AgentOptions<GuideRailAgentInput, GuideRailAgentOutput>;
62
+ export declare const guideRailAgentOptions: AgentOptions<any, GuideRailAgentOutput>;
@@ -192,7 +192,7 @@ export declare abstract class MCPBase<I extends Message, O extends Message> exte
192
192
  export declare class MCPTool extends MCPBase<Message, CallToolResult> {
193
193
  process(input: Message): Promise<CallToolResult>;
194
194
  }
195
- export interface MCPPromptInput extends Message {
195
+ export interface MCPPromptInput extends Record<string, unknown> {
196
196
  [key: string]: string;
197
197
  }
198
198
  export declare class MCPPrompt extends MCPBase<MCPPromptInput, GetPromptResult> {
@@ -129,12 +129,12 @@ export declare class AIGNE<U extends UserContext = UserContext> {
129
129
  * This overload is useful when you need to track which agent was ultimately responsible for generating the response.
130
130
  *
131
131
  * @param agent - Target agent to invoke
132
- * @param message - Input message to send to the agent (can be a string or a structured message object)
132
+ * @param message - Input message to send to the agent
133
133
  * @param options.returnActiveAgent - Must be true to return the final active agent
134
134
  * @param options.streaming - Must be false to return a response stream
135
135
  * @returns A promise resolving to a tuple containing the agent's response and the final active agent
136
136
  */
137
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions<U> & {
137
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
138
138
  returnActiveAgent: true;
139
139
  streaming?: false;
140
140
  }): Promise<[O, Agent]>;
@@ -143,12 +143,12 @@ export declare class AIGNE<U extends UserContext = UserContext> {
143
143
  * This overload is useful when you need streaming responses while also tracking which agent provided them.
144
144
  *
145
145
  * @param agent - Target agent to invoke
146
- * @param message - Input message to send to the agent (can be a string or a structured message object)
146
+ * @param message - Input message to send to the agent
147
147
  * @param options.returnActiveAgent - Must be true to return the final active agent
148
148
  * @param options.streaming - Must be true to return a response stream
149
149
  * @returns A promise resolving to a tuple containing the agent's response stream and a promise for the final agent
150
150
  */
151
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions<U> & {
151
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
152
152
  returnActiveAgent: true;
153
153
  streaming: true;
154
154
  }): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
@@ -157,7 +157,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
157
157
  * This is the standard way to invoke an agent when you only need the response.
158
158
  *
159
159
  * @param agent - Target agent to invoke
160
- * @param message - Input message to send to the agent (can be a string or a structured message object)
160
+ * @param message - Input message to send to the agent
161
161
  * @param options - Optional configuration parameters for the invocation
162
162
  * @returns A promise resolving to the agent's complete response
163
163
  *
@@ -165,7 +165,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
165
165
  * Here's a simple example of how to invoke an agent:
166
166
  * {@includeCode ../../test/aigne/aigne.test.ts#example-simple}
167
167
  */
168
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options?: InvokeOptions<U> & {
168
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options?: InvokeOptions<U> & {
169
169
  returnActiveAgent?: false;
170
170
  streaming?: false;
171
171
  }): Promise<O>;
@@ -174,7 +174,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
174
174
  * This allows processing the response incrementally as it's being generated.
175
175
  *
176
176
  * @param agent - Target agent to invoke
177
- * @param message - Input message to send to the agent (can be a string or a structured message object)
177
+ * @param message - Input message to send to the agent
178
178
  * @param options - Configuration with streaming enabled to receive incremental response chunks
179
179
  * @returns A promise resolving to a stream of the agent's response that can be consumed incrementally
180
180
  *
@@ -182,7 +182,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
182
182
  * Here's an example of how to invoke an agent with streaming response:
183
183
  * {@includeCode ../../test/aigne/aigne.test.ts#example-streaming}
184
184
  */
185
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions<U> & {
185
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
186
186
  returnActiveAgent?: false;
187
187
  streaming: true;
188
188
  }): Promise<AgentResponseStream<O>>;
@@ -196,7 +196,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
196
196
  * @returns Either a UserAgent (when no message provided) or a promise resolving to the agent's response
197
197
  * with optional active agent information based on the provided options
198
198
  */
199
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I | string, options?: InvokeOptions<U>): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
199
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I, options?: InvokeOptions<U>): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
200
200
  /**
201
201
  * Publishes a message to the message queue for inter-agent communication.
202
202
  * This method broadcasts a message to all subscribers of the specified topic(s).
@@ -210,7 +210,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
210
210
  * Here's an example of how to publish a message:
211
211
  * {@includeCode ../../test/aigne/aigne.test.ts#example-publish-message}
212
212
  */
213
- publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message | string, options?: InvokeOptions<U>): void;
213
+ publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message, options?: InvokeOptions<U>): void;
214
214
  /**
215
215
  * Subscribes to receive the next message on a specific topic.
216
216
  * This overload returns a Promise that resolves with the next message published to the topic.
@@ -42,6 +42,7 @@ export type ContextEmitEventMap = {
42
42
  export interface InvokeOptions<U extends UserContext = UserContext> extends Partial<Omit<AgentInvokeOptions<U>, "context">> {
43
43
  returnActiveAgent?: boolean;
44
44
  returnProgressChunks?: boolean;
45
+ returnMetadata?: boolean;
45
46
  disableTransfer?: boolean;
46
47
  sourceAgent?: Agent;
47
48
  }
@@ -77,11 +78,11 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
77
78
  * @param options.streaming return a stream of the output
78
79
  * @returns the output of the agent and the final active agent
79
80
  */
80
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions & {
81
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
81
82
  returnActiveAgent: true;
82
83
  streaming?: false;
83
84
  }): Promise<[O, Agent]>;
84
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions & {
85
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
85
86
  returnActiveAgent: true;
86
87
  streaming: true;
87
88
  }): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
@@ -91,19 +92,19 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
91
92
  * @param message Message to pass to the agent
92
93
  * @returns the output of the agent
93
94
  */
94
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options?: InvokeOptions & {
95
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options?: InvokeOptions & {
95
96
  streaming?: false;
96
97
  }): Promise<O>;
97
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I | string, options: InvokeOptions & {
98
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
98
99
  streaming: true;
99
100
  }): Promise<AgentResponseStream<O>>;
100
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I | string, options?: InvokeOptions): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
101
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message?: I, options?: InvokeOptions): UserAgent<I, O> | Promise<AgentResponse<O> | [AgentResponse<O>, Agent]>;
101
102
  /**
102
103
  * Publish a message to a topic, the aigne will invoke the listeners of the topic
103
104
  * @param topic topic name, or an array of topic names
104
105
  * @param payload message to publish
105
106
  */
106
- publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message | string, options?: InvokeOptions): void;
107
+ publish(topic: string | string[], payload: Omit<MessagePayload, "context"> | Message, options?: InvokeOptions): void;
107
108
  subscribe(topic: string | string[], listener?: undefined): Promise<MessagePayload>;
108
109
  subscribe(topic: string | string[], listener: MessageQueueListener): Unsubscribe;
109
110
  subscribe(topic: string | string[], listener?: MessageQueueListener): Unsubscribe | Promise<MessagePayload>;
@@ -142,6 +143,7 @@ export declare class AIGNEContext implements Context {
142
143
  reset?: boolean;
143
144
  }): AIGNEContext;
144
145
  invoke: Context["invoke"];
146
+ private onInvocationResult;
145
147
  publish: Context["publish"];
146
148
  subscribe: Context["subscribe"];
147
149
  unsubscribe: Context["unsubscribe"];
@@ -11,7 +11,6 @@ const zod_1 = require("zod");
11
11
  const agent_js_1 = require("../agents/agent.js");
12
12
  const types_js_1 = require("../agents/types.js");
13
13
  const user_agent_js_1 = require("../agents/user-agent.js");
14
- const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
15
14
  const event_stream_js_1 = require("../utils/event-stream.js");
16
15
  const promise_js_1 = require("../utils/promise.js");
17
16
  const stream_utils_js_1 = require("../utils/stream-utils.js");
@@ -87,10 +86,10 @@ class AIGNEContext {
87
86
  });
88
87
  }
89
88
  const newContext = this.newContext();
90
- const msg = (0, prompt_builder_js_1.createMessage)(message);
91
- return Promise.resolve(newContext.internal.invoke(agent, msg, newContext, options)).then(async (response) => {
89
+ return Promise.resolve(newContext.internal.invoke(agent, message, newContext, options)).then(async (response) => {
92
90
  if (!options?.streaming) {
93
- const { __activeAgent__: activeAgent, ...output } = await (0, stream_utils_js_1.agentResponseStreamToObject)(response);
91
+ let { __activeAgent__: activeAgent, ...output } = await (0, stream_utils_js_1.agentResponseStreamToObject)(response);
92
+ output = await this.onInvocationResult(output, options);
94
93
  if (options?.returnActiveAgent) {
95
94
  return [output, activeAgent];
96
95
  }
@@ -104,13 +103,14 @@ class AIGNEContext {
104
103
  ...chunk,
105
104
  delta: {
106
105
  ...chunk.delta,
107
- json: (0, type_utils_js_1.omitBy)(chunk.delta.json, (_, k) => k === "__activeAgent__"),
106
+ json: (0, type_utils_js_1.omit)(chunk.delta.json, "__activeAgent__"),
108
107
  },
109
108
  };
110
109
  }
111
110
  },
112
- onResult({ __activeAgent__: activeAgent }) {
113
- activeAgentPromise.resolve(activeAgent);
111
+ onResult: async (output) => {
112
+ activeAgentPromise.resolve(output.__activeAgent__);
113
+ return await this.onInvocationResult(output, options);
114
114
  },
115
115
  });
116
116
  const finalStream = !options.returnProgressChunks
@@ -122,6 +122,18 @@ class AIGNEContext {
122
122
  return finalStream;
123
123
  });
124
124
  });
125
+ async onInvocationResult(output, options) {
126
+ if (!options?.returnMetadata) {
127
+ return output;
128
+ }
129
+ return {
130
+ ...output,
131
+ $meta: {
132
+ ...output.$meta,
133
+ usage: this.usage,
134
+ },
135
+ };
136
+ }
125
137
  publish = ((topic, payload, options) => {
126
138
  if (options?.userContext) {
127
139
  Object.assign(this.userContext, options.userContext);
@@ -208,46 +220,54 @@ class AIGNEContextShared {
208
220
  return withAbortSignal(this.abortController.signal, new Error("AIGNEContext is timeout"), () => this.invokeAgent(agent, input, context, options));
209
221
  }
210
222
  async *invokeAgent(agent, input, context, options) {
211
- let activeAgent = agent;
212
- for (;;) {
213
- const result = {};
214
- if (options?.sourceAgent && activeAgent !== options.sourceAgent) {
215
- options.sourceAgent.hooks.onHandoff?.({
216
- context,
217
- source: options.sourceAgent,
218
- target: activeAgent,
219
- input,
220
- });
221
- }
222
- const stream = await activeAgent.invoke(input, { ...options, context, streaming: true });
223
- for await (const value of stream) {
224
- if ((0, agent_js_1.isAgentResponseDelta)(value)) {
225
- if (value.delta.json) {
226
- value.delta.json = omitExistsProperties(result, value.delta.json);
227
- Object.assign(result, value.delta.json);
223
+ const startedAt = Date.now();
224
+ try {
225
+ let activeAgent = agent;
226
+ for (;;) {
227
+ const result = {};
228
+ if (options?.sourceAgent && activeAgent !== options.sourceAgent) {
229
+ options.sourceAgent.hooks.onHandoff?.({
230
+ context,
231
+ source: options.sourceAgent,
232
+ target: activeAgent,
233
+ input,
234
+ });
235
+ }
236
+ const stream = await activeAgent.invoke(input, { ...options, context, streaming: true });
237
+ for await (const value of stream) {
238
+ if ((0, agent_js_1.isAgentResponseDelta)(value)) {
239
+ if (value.delta.json) {
240
+ value.delta.json = omitExistsProperties(result, value.delta.json);
241
+ Object.assign(result, value.delta.json);
242
+ }
243
+ delete value.delta.json?.[types_js_1.transferAgentOutputKey];
228
244
  }
229
- delete value.delta.json?.[types_js_1.transferAgentOutputKey];
245
+ if ((0, agent_js_1.isEmptyChunk)(value))
246
+ continue;
247
+ yield value;
230
248
  }
231
- if ((0, agent_js_1.isEmptyChunk)(value))
232
- continue;
233
- yield value;
234
- }
235
- if (!options?.disableTransfer) {
236
- const transferToAgent = (0, types_js_1.isTransferAgentOutput)(result)
237
- ? result[types_js_1.transferAgentOutputKey].agent
238
- : undefined;
239
- if (transferToAgent) {
240
- activeAgent = transferToAgent;
241
- continue;
249
+ if (!options?.disableTransfer) {
250
+ const transferToAgent = (0, types_js_1.isTransferAgentOutput)(result)
251
+ ? result[types_js_1.transferAgentOutputKey].agent
252
+ : undefined;
253
+ if (transferToAgent) {
254
+ activeAgent = transferToAgent;
255
+ continue;
256
+ }
242
257
  }
258
+ break;
243
259
  }
244
- break;
260
+ yield {
261
+ delta: {
262
+ json: { __activeAgent__: activeAgent },
263
+ },
264
+ };
265
+ }
266
+ finally {
267
+ const endedAt = Date.now();
268
+ const duration = endedAt - startedAt;
269
+ this.usage.duration += duration;
245
270
  }
246
- yield {
247
- delta: {
248
- json: { __activeAgent__: activeAgent },
249
- },
250
- };
251
271
  }
252
272
  }
253
273
  function omitExistsProperties(result, { ...delta }) {
@@ -21,7 +21,7 @@ export interface MessagePayload {
21
21
  /**
22
22
  * @hidden
23
23
  */
24
- export declare function toMessagePayload(payload: Omit<MessagePayload, "context"> | string | Message, options?: Partial<Pick<MessagePayload, "role" | "source">>): Omit<MessagePayload, "context">;
24
+ export declare function toMessagePayload(payload: Omit<MessagePayload, "context"> | Message, options?: Partial<Pick<MessagePayload, "role" | "source">>): Omit<MessagePayload, "context">;
25
25
  /**
26
26
  * @hidden
27
27
  */
@@ -4,7 +4,6 @@ exports.MessageQueue = exports.UserOutputTopic = exports.UserInputTopic = void 0
4
4
  exports.toMessagePayload = toMessagePayload;
5
5
  const strict_event_emitter_1 = require("strict-event-emitter");
6
6
  const zod_1 = require("zod");
7
- const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
8
7
  const type_utils_js_1 = require("../utils/type-utils.js");
9
8
  /**
10
9
  * @hidden
@@ -28,12 +27,12 @@ function isMessagePayload(payload) {
28
27
  */
29
28
  function toMessagePayload(payload, options) {
30
29
  if (isMessagePayload(payload)) {
31
- return { ...payload, message: (0, prompt_builder_js_1.createMessage)(payload.message), ...options };
30
+ return { ...payload, ...options };
32
31
  }
33
32
  return {
34
33
  role: options?.role || "user",
35
34
  source: options?.source,
36
- message: (0, prompt_builder_js_1.createMessage)(payload),
35
+ message: payload,
37
36
  };
38
37
  }
39
38
  /**