@aigne/core 1.19.0 → 1.21.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 (64) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/lib/cjs/agents/agent.d.ts +12 -7
  3. package/lib/cjs/agents/agent.js +8 -10
  4. package/lib/cjs/agents/ai-agent.d.ts +11 -2
  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 +9 -7
  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-js.d.ts +2 -2
  16. package/lib/cjs/loader/agent-js.js +3 -0
  17. package/lib/cjs/loader/agent-yaml.d.ts +24 -6
  18. package/lib/cjs/loader/agent-yaml.js +41 -1
  19. package/lib/cjs/loader/index.d.ts +1 -1
  20. package/lib/cjs/loader/index.js +16 -4
  21. package/lib/cjs/prompt/prompt-builder.d.ts +1 -15
  22. package/lib/cjs/prompt/prompt-builder.js +12 -25
  23. package/lib/cjs/utils/stream-utils.d.ts +1 -2
  24. package/lib/cjs/utils/type-utils.d.ts +1 -0
  25. package/lib/cjs/utils/type-utils.js +13 -0
  26. package/lib/dts/agents/agent.d.ts +12 -7
  27. package/lib/dts/agents/ai-agent.d.ts +11 -2
  28. package/lib/dts/agents/guide-rail-agent.d.ts +1 -1
  29. package/lib/dts/agents/mcp-agent.d.ts +1 -1
  30. package/lib/dts/aigne/aigne.d.ts +10 -10
  31. package/lib/dts/aigne/context.d.ts +9 -7
  32. package/lib/dts/aigne/message-queue.d.ts +1 -1
  33. package/lib/dts/aigne/usage.d.ts +1 -0
  34. package/lib/dts/loader/agent-js.d.ts +2 -2
  35. package/lib/dts/loader/agent-yaml.d.ts +24 -6
  36. package/lib/dts/loader/index.d.ts +1 -1
  37. package/lib/dts/prompt/prompt-builder.d.ts +1 -15
  38. package/lib/dts/utils/stream-utils.d.ts +1 -2
  39. package/lib/dts/utils/type-utils.d.ts +1 -0
  40. package/lib/esm/agents/agent.d.ts +12 -7
  41. package/lib/esm/agents/agent.js +8 -10
  42. package/lib/esm/agents/ai-agent.d.ts +11 -2
  43. package/lib/esm/agents/ai-agent.js +14 -4
  44. package/lib/esm/agents/guide-rail-agent.d.ts +1 -1
  45. package/lib/esm/agents/mcp-agent.d.ts +1 -1
  46. package/lib/esm/aigne/aigne.d.ts +10 -10
  47. package/lib/esm/aigne/context.d.ts +9 -7
  48. package/lib/esm/aigne/context.js +63 -43
  49. package/lib/esm/aigne/message-queue.d.ts +1 -1
  50. package/lib/esm/aigne/message-queue.js +2 -3
  51. package/lib/esm/aigne/usage.d.ts +1 -0
  52. package/lib/esm/aigne/usage.js +1 -0
  53. package/lib/esm/loader/agent-js.d.ts +2 -2
  54. package/lib/esm/loader/agent-js.js +3 -0
  55. package/lib/esm/loader/agent-yaml.d.ts +24 -6
  56. package/lib/esm/loader/agent-yaml.js +41 -1
  57. package/lib/esm/loader/index.d.ts +1 -1
  58. package/lib/esm/loader/index.js +17 -5
  59. package/lib/esm/prompt/prompt-builder.d.ts +1 -15
  60. package/lib/esm/prompt/prompt-builder.js +12 -23
  61. package/lib/esm/utils/stream-utils.d.ts +1 -2
  62. package/lib/esm/utils/type-utils.d.ts +1 -0
  63. package/lib/esm/utils/type-utils.js +12 -0
  64. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,34 @@
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.21.0](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.20.1...core-v1.21.0) (2025-06-20)
9
+
10
+
11
+ ### Features
12
+
13
+ * **cli:** support pass named input to agent by --input-xxx ([#167](https://github.com/AIGNE-io/aigne-framework/issues/167)) ([cda5bb6](https://github.com/AIGNE-io/aigne-framework/commit/cda5bb6baab680787de1a042664fe34c17a84bb1))
14
+
15
+ ## [1.20.1](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.20.0...core-v1.20.1) (2025-06-19)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * 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))
21
+
22
+
23
+ ### Dependencies
24
+
25
+ * The following workspace dependencies were updated
26
+ * dependencies
27
+ * @aigne/platform-helpers bumped to 0.1.2
28
+
29
+ ## [1.20.0](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.19.0...core-v1.20.0) (2025-06-17)
30
+
31
+
32
+ ### Features
33
+
34
+ * 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))
35
+
8
36
  ## [1.19.0](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.18.6...core-v1.19.0) (2025-06-16)
9
37
 
10
38
 
@@ -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 & Message, 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 & Message, options: Partial<AgentInvokeOptions> & {
358
363
  streaming: true;
359
364
  }): Promise<AgentResponseStream<O>>;
360
365
  /**
@@ -366,8 +371,8 @@ 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>>;
370
- protected invokeSkill<I extends Message, O extends Message>(skill: Agent<I, O>, input: I, options: AgentInvokeOptions): Promise<O>;
374
+ invoke(input: I & Message, options?: Partial<AgentInvokeOptions>): Promise<AgentResponse<O>>;
375
+ protected invokeSkill<I extends Message, O extends Message>(skill: Agent<I, O>, input: I & Message, options: AgentInvokeOptions): Promise<O>;
371
376
  /**
372
377
  * Process agent output
373
378
  *
@@ -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) {
@@ -3,6 +3,7 @@ import { PromptBuilder } from "../prompt/prompt-builder.js";
3
3
  import { Agent, type AgentInvokeOptions, type AgentOptions, type AgentProcessAsyncGenerator, type Message } from "./agent.js";
4
4
  import { ChatModel, type ChatModelInput } from "./chat-model.js";
5
5
  import type { GuideRailAgentOutput } from "./guide-rail-agent.js";
6
+ export declare const DEFAULT_OUTPUT_KEY = "message";
6
7
  /**
7
8
  * Configuration options for an AI Agent
8
9
  *
@@ -26,10 +27,14 @@ export interface AIAgentOptions<I extends Message = Message, O extends Message =
26
27
  * more complex prompt templates
27
28
  */
28
29
  instructions?: string | PromptBuilder;
30
+ /**
31
+ * Pick a message from input to use as the user's message
32
+ */
33
+ inputKey?: string;
29
34
  /**
30
35
  * Custom key to use for text output in the response
31
36
  *
32
- * Defaults to $message if not specified
37
+ * Defaults to `message` if not specified
33
38
  */
34
39
  outputKey?: string;
35
40
  /**
@@ -163,6 +168,10 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
163
168
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
164
169
  */
165
170
  instructions: PromptBuilder;
171
+ /**
172
+ * Pick a message from input to use as the user's message
173
+ */
174
+ inputKey?: string;
166
175
  /**
167
176
  * Custom key to use for text output in the response
168
177
  *
@@ -170,7 +179,7 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
170
179
  * Setting a custom output key:
171
180
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-custom-output-key}
172
181
  */
173
- outputKey?: string;
182
+ outputKey: string;
174
183
  /**
175
184
  * Controls how the agent uses tools during execution
176
185
  *
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AIAgent = exports.aiAgentOptionsSchema = exports.aiAgentToolChoiceSchema = exports.AIAgentToolChoice = void 0;
3
+ exports.AIAgent = exports.aiAgentOptionsSchema = exports.aiAgentToolChoiceSchema = exports.AIAgentToolChoice = exports.DEFAULT_OUTPUT_KEY = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
6
6
  const template_js_1 = require("../prompt/template.js");
@@ -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
+ exports.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(),
@@ -106,12 +108,16 @@ class AIAgent extends agent_js_1.Agent {
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 || exports.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 || exports.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 & Message, 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 & Message, 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 & Message, 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 & Message, 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 & Message, 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 & Message, 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 & Message, 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 & Message, 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 & Message, 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 & Message, 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"];
@@ -167,7 +169,7 @@ declare class AIGNEContextShared {
167
169
  private timer?;
168
170
  private initTimeout;
169
171
  get status(): "normal" | "timeout";
170
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, input: I, context: Context, options?: InvokeOptions): AgentProcessAsyncGenerator<O & {
172
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, input: I & Message, context: Context, options?: InvokeOptions): AgentProcessAsyncGenerator<O & {
171
173
  __activeAgent__: Agent;
172
174
  }>;
173
175
  private invokeAgent;
@@ -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
  /**
@@ -5,6 +5,7 @@ export interface ContextUsage {
5
5
  inputTokens: number;
6
6
  outputTokens: number;
7
7
  agentCalls: number;
8
+ duration: number;
8
9
  }
9
10
  /**
10
11
  * @hidden
@@ -9,5 +9,6 @@ function newEmptyContextUsage() {
9
9
  inputTokens: 0,
10
10
  outputTokens: 0,
11
11
  agentCalls: 0,
12
+ duration: 0,
12
13
  };
13
14
  }