@aigne/core 1.18.6 → 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 (63) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/lib/cjs/agents/agent.d.ts +31 -8
  3. package/lib/cjs/agents/agent.js +31 -22
  4. package/lib/cjs/agents/ai-agent.d.ts +18 -6
  5. package/lib/cjs/agents/ai-agent.js +23 -12
  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/agents/team-agent.js +1 -1
  9. package/lib/cjs/aigne/aigne.d.ts +10 -10
  10. package/lib/cjs/aigne/context.d.ts +11 -6
  11. package/lib/cjs/aigne/context.js +73 -48
  12. package/lib/cjs/aigne/message-queue.d.ts +1 -1
  13. package/lib/cjs/aigne/message-queue.js +2 -3
  14. package/lib/cjs/aigne/usage.d.ts +1 -0
  15. package/lib/cjs/aigne/usage.js +1 -0
  16. package/lib/cjs/loader/agent-yaml.d.ts +2 -1
  17. package/lib/cjs/loader/agent-yaml.js +4 -0
  18. package/lib/cjs/prompt/prompt-builder.d.ts +2 -16
  19. package/lib/cjs/prompt/prompt-builder.js +12 -25
  20. package/lib/cjs/utils/event-stream.d.ts +5 -1
  21. package/lib/cjs/utils/event-stream.js +88 -23
  22. package/lib/cjs/utils/stream-utils.d.ts +9 -7
  23. package/lib/cjs/utils/stream-utils.js +48 -15
  24. package/lib/cjs/utils/type-utils.d.ts +2 -0
  25. package/lib/cjs/utils/type-utils.js +18 -0
  26. package/lib/dts/agents/agent.d.ts +31 -8
  27. package/lib/dts/agents/ai-agent.d.ts +18 -6
  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 +11 -6
  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-yaml.d.ts +2 -1
  35. package/lib/dts/prompt/prompt-builder.d.ts +2 -16
  36. package/lib/dts/utils/event-stream.d.ts +5 -1
  37. package/lib/dts/utils/stream-utils.d.ts +9 -7
  38. package/lib/dts/utils/type-utils.d.ts +2 -0
  39. package/lib/esm/agents/agent.d.ts +31 -8
  40. package/lib/esm/agents/agent.js +29 -22
  41. package/lib/esm/agents/ai-agent.d.ts +18 -6
  42. package/lib/esm/agents/ai-agent.js +25 -14
  43. package/lib/esm/agents/guide-rail-agent.d.ts +1 -1
  44. package/lib/esm/agents/mcp-agent.d.ts +1 -1
  45. package/lib/esm/agents/team-agent.js +2 -2
  46. package/lib/esm/aigne/aigne.d.ts +10 -10
  47. package/lib/esm/aigne/context.d.ts +11 -6
  48. package/lib/esm/aigne/context.js +76 -51
  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-yaml.d.ts +2 -1
  54. package/lib/esm/loader/agent-yaml.js +4 -0
  55. package/lib/esm/prompt/prompt-builder.d.ts +2 -16
  56. package/lib/esm/prompt/prompt-builder.js +12 -23
  57. package/lib/esm/utils/event-stream.d.ts +5 -1
  58. package/lib/esm/utils/event-stream.js +86 -22
  59. package/lib/esm/utils/stream-utils.d.ts +9 -7
  60. package/lib/esm/utils/stream-utils.js +48 -16
  61. package/lib/esm/utils/type-utils.d.ts +2 -0
  62. package/lib/esm/utils/type-utils.js +16 -0
  63. 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.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
+
29
+ ## [1.19.0](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.18.6...core-v1.19.0) (2025-06-16)
30
+
31
+
32
+ ### Features
33
+
34
+ * support respond progressing chunks by enable `returnProgressChunks` option for aigne.invoke ([cf4c313](https://github.com/AIGNE-io/aigne-framework/commit/cf4c313ee69f255be799ac196da675b79f69bf76))
35
+
8
36
  ## [1.18.6](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.18.5...core-v1.18.6) (2025-06-11)
9
37
 
10
38
 
@@ -1,7 +1,8 @@
1
1
  import { nodejs } from "@aigne/platform-helpers/nodejs/index.js";
2
2
  import { ZodObject, type ZodType } from "zod";
3
- import type { Context, UserContext } from "../aigne/context.js";
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
@@ -594,7 +599,7 @@ export type AgentResponseStream<T> = ReadableStream<AgentResponseChunk<T>>;
594
599
  *
595
600
  * @template T Response data type
596
601
  */
597
- export type AgentResponseChunk<T> = AgentResponseDelta<T>;
602
+ export type AgentResponseChunk<T> = AgentResponseDelta<T> | AgentResponseProgress;
598
603
  /**
599
604
  * Check if a response chunk is empty
600
605
  *
@@ -622,6 +627,24 @@ export interface AgentResponseDelta<T> {
622
627
  json?: Partial<T> | TransferAgentOutput;
623
628
  };
624
629
  }
630
+ export declare function isAgentResponseDelta<T>(chunk: AgentResponseChunk<T>): chunk is AgentResponseDelta<T>;
631
+ export interface AgentResponseProgress {
632
+ progress: ({
633
+ event: "agentStarted";
634
+ input: Message;
635
+ } | {
636
+ event: "agentSucceed";
637
+ output: Message;
638
+ } | {
639
+ event: "agentFailed";
640
+ error: Error;
641
+ }) & Omit<AgentEvent, "agent"> & {
642
+ agent: {
643
+ name: string;
644
+ };
645
+ };
646
+ }
647
+ export declare function isAgentResponseProgress<T>(chunk: AgentResponseChunk<T>): chunk is AgentResponseProgress;
625
648
  /**
626
649
  * Creates a text delta for streaming responses
627
650
  *
@@ -38,11 +38,12 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.FunctionAgent = exports.Agent = exports.agentOptionsSchema = void 0;
40
40
  exports.isEmptyChunk = isEmptyChunk;
41
+ exports.isAgentResponseDelta = isAgentResponseDelta;
42
+ exports.isAgentResponseProgress = isAgentResponseProgress;
41
43
  exports.textDelta = textDelta;
42
44
  exports.jsonDelta = jsonDelta;
43
45
  const index_js_1 = require("@aigne/platform-helpers/nodejs/index.js");
44
46
  const zod_1 = require("zod");
45
- const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
46
47
  const logger_js_1 = require("../utils/logger.js");
47
48
  const stream_utils_js_1 = require("../utils/stream-utils.js");
48
49
  const type_utils_js_1 = require("../utils/type-utils.js");
@@ -315,7 +316,7 @@ class Agent {
315
316
  for (const memory of this.memories) {
316
317
  const ms = (await memory.retrieve({
317
318
  ...input,
318
- 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),
319
320
  limit: input.limit ?? this.maxRetrieveMemoryCount,
320
321
  }, options.context)).memories;
321
322
  memories.push(...ms);
@@ -342,13 +343,12 @@ class Agent {
342
343
  opts.context.memories.push(...options.memories);
343
344
  options.memories = undefined;
344
345
  }
345
- const message = typeof input === "string" ? (0, prompt_builder_js_1.createMessage)(input) : input;
346
346
  logger_js_1.logger.debug("Invoke agent %s started with input: %O", this.name, input);
347
347
  if (!this.disableEvents)
348
- opts.context.emit("agentStarted", { agent: this, input: message });
348
+ opts.context.emit("agentStarted", { agent: this, input });
349
349
  try {
350
- await this.hooks.onStart?.({ context: opts.context, input: message });
351
- 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);
352
352
  await this.preprocess(parsedInput, opts);
353
353
  this.checkContextStatus(opts);
354
354
  let response = await this.process(parsedInput, opts);
@@ -361,22 +361,23 @@ class Agent {
361
361
  : (0, stream_utils_js_1.isAsyncGenerator)(response)
362
362
  ? (0, stream_utils_js_1.asyncGeneratorToReadableStream)(response)
363
363
  : (0, stream_utils_js_1.objectToAgentResponseStream)(response);
364
- return this.checkResponseByGuideRails(message, (0, stream_utils_js_1.onAgentResponseStreamEnd)(stream, async (result) => {
365
- return await this.processAgentOutput(parsedInput, result, opts);
366
- }, {
367
- errorCallback: async (error) => {
368
- return await this.processAgentError(message, error, opts);
364
+ return this.checkResponseByGuideRails(input, (0, stream_utils_js_1.onAgentResponseStreamEnd)(stream, {
365
+ onResult: async (result) => {
366
+ return await this.processAgentOutput(parsedInput, result, opts);
367
+ },
368
+ onError: async (error) => {
369
+ return await this.processAgentError(input, error, opts);
369
370
  },
370
371
  }), opts);
371
372
  }
372
- return await this.checkResponseByGuideRails(message, this.processAgentOutput(parsedInput, response instanceof ReadableStream
373
+ return await this.checkResponseByGuideRails(input, this.processAgentOutput(parsedInput, response instanceof ReadableStream
373
374
  ? await (0, stream_utils_js_1.agentResponseStreamToObject)(response)
374
375
  : (0, stream_utils_js_1.isAsyncGenerator)(response)
375
376
  ? await (0, stream_utils_js_1.agentResponseStreamToObject)(response)
376
377
  : response, opts), opts);
377
378
  }
378
379
  catch (error) {
379
- throw await this.processAgentError(message, error, opts);
380
+ throw await this.processAgentError(input, error, opts);
380
381
  }
381
382
  }
382
383
  async invokeSkill(skill, input, options) {
@@ -464,14 +465,16 @@ class Agent {
464
465
  return output;
465
466
  const result = await output;
466
467
  if (result instanceof ReadableStream) {
467
- return (0, stream_utils_js_1.onAgentResponseStreamEnd)(result, async (result) => {
468
- const error = await this.runGuideRails(input, result, options);
469
- if (error) {
470
- return {
471
- ...(await this.onGuideRailError(error)),
472
- $status: "GuideRailError",
473
- };
474
- }
468
+ return (0, stream_utils_js_1.onAgentResponseStreamEnd)(result, {
469
+ onResult: async (result) => {
470
+ const error = await this.runGuideRails(input, result, options);
471
+ if (error) {
472
+ return {
473
+ ...(await this.onGuideRailError(error)),
474
+ $status: "GuideRailError",
475
+ };
476
+ }
477
+ },
475
478
  });
476
479
  }
477
480
  const error = await this.runGuideRails(input, result, options);
@@ -585,7 +588,13 @@ exports.Agent = Agent;
585
588
  * @returns True if the chunk is empty
586
589
  */
587
590
  function isEmptyChunk(chunk) {
588
- return (0, type_utils_js_1.isEmpty)(chunk.delta.json) && (0, type_utils_js_1.isEmpty)(chunk.delta.text);
591
+ return isAgentResponseDelta(chunk) && (0, type_utils_js_1.isEmpty)(chunk.delta.json) && (0, type_utils_js_1.isEmpty)(chunk.delta.text);
592
+ }
593
+ function isAgentResponseDelta(chunk) {
594
+ return "delta" in chunk;
595
+ }
596
+ function isAgentResponseProgress(chunk) {
597
+ return "progress" in chunk;
589
598
  }
590
599
  /**
591
600
  * Creates a text delta for streaming responses
@@ -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
  *
@@ -191,20 +201,21 @@ class AIAgent extends agent_js_1.Agent {
191
201
  });
192
202
  const toolsMap = new Map(toolAgents?.map((i) => [i.name, i]));
193
203
  if (this.toolChoice === "router") {
194
- yield* this._processRouter(input, model, modelInput, options, toolsMap);
195
- return;
204
+ return yield* this._processRouter(input, model, modelInput, options, toolsMap);
196
205
  }
197
206
  const toolCallMessages = [];
198
- const outputKey = this.outputKey || prompt_builder_js_1.MESSAGE_KEY;
207
+ const outputKey = this.outputKey;
199
208
  for (;;) {
200
209
  const modelOutput = {};
201
210
  const stream = await options.context.invoke(model, { ...modelInput, messages: modelInput.messages.concat(toolCallMessages) }, { streaming: true });
202
211
  for await (const value of stream) {
203
- if (value.delta.text?.text) {
204
- yield { delta: { text: { [outputKey]: value.delta.text.text } } };
205
- }
206
- if (value.delta.json) {
207
- Object.assign(modelOutput, value.delta.json);
212
+ if ((0, agent_js_1.isAgentResponseDelta)(value)) {
213
+ if (value.delta.text?.text) {
214
+ yield { delta: { text: { [outputKey]: value.delta.text.text } } };
215
+ }
216
+ if (value.delta.json) {
217
+ Object.assign(modelOutput, value.delta.json);
218
+ }
208
219
  }
209
220
  }
210
221
  const { toolCalls, json, text } = modelOutput;
@@ -253,7 +264,7 @@ class AIAgent extends agent_js_1.Agent {
253
264
  }
254
265
  }
255
266
  async onGuideRailError(error) {
256
- const outputKey = this.outputKey || prompt_builder_js_1.MESSAGE_KEY;
267
+ const outputKey = this.outputKey || DEFAULT_OUTPUT_KEY;
257
268
  return {
258
269
  [outputKey]: error.reason,
259
270
  };
@@ -275,7 +286,7 @@ class AIAgent extends agent_js_1.Agent {
275
286
  if (!tool)
276
287
  throw new Error(`Tool not found: ${call.function.name}`);
277
288
  const stream = await options.context.invoke(tool, { ...call.function.arguments, ...input }, { streaming: true, sourceAgent: this });
278
- yield* stream;
289
+ return yield* stream;
279
290
  }
280
291
  }
281
292
  exports.AIAgent = AIAgent;
@@ -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> {
@@ -158,7 +158,7 @@ class TeamAgent extends agent_js_1.Agent {
158
158
  if (!done) {
159
159
  tasks.set(index, read(index, reader));
160
160
  }
161
- if (value) {
161
+ if (value && (0, agent_js_1.isAgentResponseDelta)(value)) {
162
162
  let { delta: { text, ...delta }, } = value;
163
163
  if (text) {
164
164
  for (const key of Object.keys(text)) {
@@ -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.
@@ -41,6 +41,8 @@ export type ContextEmitEventMap = {
41
41
  */
42
42
  export interface InvokeOptions<U extends UserContext = UserContext> extends Partial<Omit<AgentInvokeOptions<U>, "context">> {
43
43
  returnActiveAgent?: boolean;
44
+ returnProgressChunks?: boolean;
45
+ returnMetadata?: boolean;
44
46
  disableTransfer?: boolean;
45
47
  sourceAgent?: Agent;
46
48
  }
@@ -53,6 +55,8 @@ export interface UserContext extends Record<string, unknown> {
53
55
  * @hidden
54
56
  */
55
57
  export interface Context<U extends UserContext = UserContext> extends TypedEventEmitter<ContextEventMap, ContextEmitEventMap> {
58
+ id: string;
59
+ parentId?: string;
56
60
  model?: ChatModel;
57
61
  skills?: Agent[];
58
62
  usage: ContextUsage;
@@ -74,11 +78,11 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
74
78
  * @param options.streaming return a stream of the output
75
79
  * @returns the output of the agent and the final active agent
76
80
  */
77
- 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 & {
78
82
  returnActiveAgent: true;
79
83
  streaming?: false;
80
84
  }): Promise<[O, Agent]>;
81
- 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 & {
82
86
  returnActiveAgent: true;
83
87
  streaming: true;
84
88
  }): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
@@ -88,19 +92,19 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
88
92
  * @param message Message to pass to the agent
89
93
  * @returns the output of the agent
90
94
  */
91
- 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 & {
92
96
  streaming?: false;
93
97
  }): Promise<O>;
94
- 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 & {
95
99
  streaming: true;
96
100
  }): Promise<AgentResponseStream<O>>;
97
- 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]>;
98
102
  /**
99
103
  * Publish a message to a topic, the aigne will invoke the listeners of the topic
100
104
  * @param topic topic name, or an array of topic names
101
105
  * @param payload message to publish
102
106
  */
103
- 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;
104
108
  subscribe(topic: string | string[], listener?: undefined): Promise<MessagePayload>;
105
109
  subscribe(topic: string | string[], listener: MessageQueueListener): Unsubscribe;
106
110
  subscribe(topic: string | string[], listener?: MessageQueueListener): Unsubscribe | Promise<MessagePayload>;
@@ -139,6 +143,7 @@ export declare class AIGNEContext implements Context {
139
143
  reset?: boolean;
140
144
  }): AIGNEContext;
141
145
  invoke: Context["invoke"];
146
+ private onInvocationResult;
142
147
  publish: Context["publish"];
143
148
  subscribe: Context["subscribe"];
144
149
  unsubscribe: Context["unsubscribe"];