@aigne/core 1.5.0 → 1.5.1-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 (73) hide show
  1. package/lib/cjs/agents/agent.d.ts +8 -4
  2. package/lib/cjs/agents/agent.js +69 -8
  3. package/lib/cjs/agents/ai-agent.d.ts +5 -5
  4. package/lib/cjs/agents/ai-agent.js +1 -3
  5. package/lib/cjs/agents/memory.d.ts +1 -1
  6. package/lib/cjs/agents/user-agent.d.ts +4 -3
  7. package/lib/cjs/agents/user-agent.js +5 -5
  8. package/lib/cjs/execution-engine/context.d.ts +58 -5
  9. package/lib/cjs/execution-engine/context.js +169 -0
  10. package/lib/cjs/execution-engine/execution-engine.d.ts +10 -13
  11. package/lib/cjs/execution-engine/execution-engine.js +7 -96
  12. package/lib/cjs/execution-engine/message-queue.d.ts +2 -0
  13. package/lib/cjs/execution-engine/utils.d.ts +2 -2
  14. package/lib/cjs/execution-engine/utils.js +11 -15
  15. package/lib/cjs/models/chat-model.d.ts +8 -0
  16. package/lib/cjs/models/chat-model.js +21 -0
  17. package/lib/cjs/models/claude-chat-model.js +24 -4
  18. package/lib/cjs/models/openai-chat-model.d.ts +2 -1
  19. package/lib/cjs/models/openai-chat-model.js +13 -1
  20. package/lib/cjs/models/xai-chat-model.d.ts +1 -2
  21. package/lib/cjs/models/xai-chat-model.js +0 -2
  22. package/lib/cjs/prompt/prompt-builder.js +3 -3
  23. package/lib/cjs/utils/json-schema.js +1 -2
  24. package/lib/cjs/utils/logger.d.ts +1 -1
  25. package/lib/cjs/utils/logger.js +1 -1
  26. package/lib/cjs/utils/model-utils.d.ts +3 -0
  27. package/lib/cjs/utils/model-utils.js +9 -0
  28. package/lib/cjs/utils/type-utils.d.ts +2 -3
  29. package/lib/cjs/utils/type-utils.js +16 -11
  30. package/lib/dts/agents/agent.d.ts +8 -4
  31. package/lib/dts/agents/ai-agent.d.ts +5 -5
  32. package/lib/dts/agents/memory.d.ts +1 -1
  33. package/lib/dts/agents/user-agent.d.ts +4 -3
  34. package/lib/dts/execution-engine/context.d.ts +58 -5
  35. package/lib/dts/execution-engine/execution-engine.d.ts +10 -13
  36. package/lib/dts/execution-engine/message-queue.d.ts +2 -0
  37. package/lib/dts/execution-engine/utils.d.ts +2 -2
  38. package/lib/dts/models/chat-model.d.ts +8 -0
  39. package/lib/dts/models/openai-chat-model.d.ts +2 -1
  40. package/lib/dts/models/xai-chat-model.d.ts +1 -2
  41. package/lib/dts/utils/logger.d.ts +1 -1
  42. package/lib/dts/utils/model-utils.d.ts +3 -0
  43. package/lib/dts/utils/type-utils.d.ts +2 -3
  44. package/lib/esm/agents/agent.d.ts +8 -4
  45. package/lib/esm/agents/agent.js +36 -8
  46. package/lib/esm/agents/ai-agent.d.ts +5 -5
  47. package/lib/esm/agents/ai-agent.js +1 -3
  48. package/lib/esm/agents/memory.d.ts +1 -1
  49. package/lib/esm/agents/user-agent.d.ts +4 -3
  50. package/lib/esm/agents/user-agent.js +5 -5
  51. package/lib/esm/execution-engine/context.d.ts +58 -5
  52. package/lib/esm/execution-engine/context.js +164 -1
  53. package/lib/esm/execution-engine/execution-engine.d.ts +10 -13
  54. package/lib/esm/execution-engine/execution-engine.js +7 -96
  55. package/lib/esm/execution-engine/message-queue.d.ts +2 -0
  56. package/lib/esm/execution-engine/utils.d.ts +2 -2
  57. package/lib/esm/execution-engine/utils.js +11 -15
  58. package/lib/esm/models/chat-model.d.ts +8 -0
  59. package/lib/esm/models/chat-model.js +21 -0
  60. package/lib/esm/models/claude-chat-model.js +24 -4
  61. package/lib/esm/models/openai-chat-model.d.ts +2 -1
  62. package/lib/esm/models/openai-chat-model.js +13 -1
  63. package/lib/esm/models/xai-chat-model.d.ts +1 -2
  64. package/lib/esm/models/xai-chat-model.js +0 -2
  65. package/lib/esm/prompt/prompt-builder.js +1 -1
  66. package/lib/esm/utils/json-schema.js +1 -2
  67. package/lib/esm/utils/logger.d.ts +1 -1
  68. package/lib/esm/utils/logger.js +1 -1
  69. package/lib/esm/utils/model-utils.d.ts +3 -0
  70. package/lib/esm/utils/model-utils.js +6 -0
  71. package/lib/esm/utils/type-utils.d.ts +2 -3
  72. package/lib/esm/utils/type-utils.js +12 -8
  73. package/package.json +4 -5
@@ -3,16 +3,17 @@ import type { MessagePayload, MessageQueueListener, Unsubscribe } from "../execu
3
3
  import { type PromiseOrValue } from "../utils/type-utils.js";
4
4
  import { Agent, type AgentOptions, type Message } from "./agent.js";
5
5
  export interface UserAgentOptions<I extends Message = Message, O extends Message = Message> extends AgentOptions<I, O> {
6
- context?: Context;
6
+ context: Context;
7
7
  process?: (input: I, context: Context) => PromiseOrValue<O>;
8
8
  }
9
9
  export declare class UserAgent<I extends Message = Message, O extends Message = Message> extends Agent<I, O> {
10
10
  static from<I extends Message, O extends Message>(options: UserAgentOptions<I, O>): UserAgent<I, O>;
11
11
  constructor(options: UserAgentOptions<I, O>);
12
- private context?;
12
+ readonly context: Context;
13
13
  private get ctx();
14
14
  private _process?;
15
- process(input: I, context?: Context): Promise<O>;
15
+ call(input: string | I, context?: Context): Promise<O>;
16
+ process(input: I, context: Context): Promise<O>;
16
17
  publish(topic: string | string[], message: Message | string): void;
17
18
  subscribe(topic: string, listener?: undefined): Promise<MessagePayload>;
18
19
  subscribe(topic: string, listener: MessageQueueListener): Unsubscribe;
@@ -1,11 +1,31 @@
1
- import type EventEmitter from "node:events";
2
- import type { Agent, FunctionAgentFn, Message } from "../agents/agent.js";
1
+ import EventEmitter from "node:events";
2
+ import { Agent, type FunctionAgentFn, type Message } from "../agents/agent.js";
3
+ import { UserAgent } from "../agents/user-agent.js";
3
4
  import type { ChatModel } from "../models/chat-model.js";
4
- import type { MessagePayload, MessageQueueListener, Unsubscribe } from "./message-queue.js";
5
+ import { type MessagePayload, MessageQueue, type MessageQueueListener, type Unsubscribe } from "./message-queue.js";
5
6
  export type Runnable<I extends Message = Message, O extends Message = Message> = Agent<I, O> | FunctionAgentFn;
7
+ export interface ContextUsage {
8
+ promptTokens: number;
9
+ completionTokens: number;
10
+ agentCalls: number;
11
+ }
12
+ export interface ContextLimits {
13
+ maxTokens?: number;
14
+ maxAgentCalls?: number;
15
+ timeout?: number;
16
+ }
6
17
  export interface Context extends EventEmitter {
7
18
  model?: ChatModel;
8
19
  tools?: Agent[];
20
+ usage: ContextUsage;
21
+ limits?: ContextLimits;
22
+ status?: "normal" | "timeout";
23
+ /**
24
+ * Create a user agent to consistently call an agent
25
+ * @param agent Agent to call
26
+ * @returns User agent
27
+ */
28
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>): UserAgent<I, O>;
9
29
  /**
10
30
  * Call an agent with a message
11
31
  * @param agent Agent to call
@@ -21,11 +41,11 @@ export interface Context extends EventEmitter {
21
41
  * @returns the output of the agent and the final active agent
22
42
  */
23
43
  call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string, options: {
24
- returnActiveAgent?: true;
44
+ returnActiveAgent: true;
25
45
  }): Promise<[O, Runnable]>;
26
46
  call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string, options?: {
27
47
  returnActiveAgent?: boolean;
28
- }): Promise<O | [O, Runnable]>;
48
+ }): UserAgent<I, O> | Promise<O | [O, Runnable]>;
29
49
  /**
30
50
  * Publish a message to a topic, the engine will call the listeners of the topic
31
51
  * @param topic topic name, or an array of topic names
@@ -38,3 +58,36 @@ export interface Context extends EventEmitter {
38
58
  subscribe(topic: string, listener?: MessageQueueListener): Unsubscribe | Promise<MessagePayload>;
39
59
  unsubscribe(topic: string, listener: MessageQueueListener): void;
40
60
  }
61
+ export declare class ExecutionContext extends EventEmitter implements Context {
62
+ private readonly engine?;
63
+ constructor(engine?: {
64
+ model?: ChatModel;
65
+ tools?: Agent[];
66
+ limits?: ContextLimits;
67
+ messageQueue?: MessageQueue;
68
+ emit?: EventEmitter["emit"];
69
+ } | undefined);
70
+ private messageQueue;
71
+ get model(): ChatModel | undefined;
72
+ get tools(): Agent<Message, Message>[] | undefined;
73
+ usage: ContextUsage;
74
+ limits?: ContextLimits | undefined;
75
+ private abortController;
76
+ private timer?;
77
+ private initTimeout;
78
+ get status(): "normal" | "timeout";
79
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>): UserAgent<I, O>;
80
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string): Promise<O>;
81
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string, options: {
82
+ returnActiveAgent: true;
83
+ }): Promise<[O, Runnable]>;
84
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>, message?: I | string, options?: {
85
+ returnActiveAgent?: boolean;
86
+ }): UserAgent<I, O> | Promise<O | [O, Runnable]>;
87
+ publish(topic: string | string[], message: Message | string, from?: Agent): void;
88
+ subscribe(topic: string, listener?: undefined): Promise<MessagePayload>;
89
+ subscribe(topic: string, listener: MessageQueueListener): Unsubscribe;
90
+ unsubscribe(topic: string, listener: MessageQueueListener): void;
91
+ emit(eventName: string | symbol, ...args: unknown[]): boolean;
92
+ private callAgent;
93
+ }
@@ -1,22 +1,24 @@
1
1
  import EventEmitter from "node:events";
2
2
  import { Agent, type Message } from "../agents/agent.js";
3
- import { UserAgent } from "../agents/user-agent.js";
3
+ import type { UserAgent } from "../agents/user-agent.js";
4
4
  import { ChatModel } from "../models/chat-model.js";
5
- import type { Context, Runnable } from "./context.js";
5
+ import { type ContextLimits, ExecutionContext, type Runnable } from "./context.js";
6
6
  import { type MessagePayload, MessageQueue, type MessageQueueListener, type Unsubscribe } from "./message-queue.js";
7
7
  export interface ExecutionEngineOptions {
8
8
  model?: ChatModel;
9
9
  tools?: Agent[];
10
10
  agents?: Agent[];
11
+ limits?: ContextLimits;
11
12
  }
12
- export declare class ExecutionEngine extends EventEmitter implements Context {
13
+ export declare class ExecutionEngine extends EventEmitter {
13
14
  constructor(options?: ExecutionEngineOptions);
14
15
  readonly messageQueue: MessageQueue;
15
16
  model?: ChatModel;
16
17
  tools: Agent[];
17
18
  private agents;
19
+ limits?: ContextLimits;
18
20
  addAgent(...agents: Agent[]): void;
19
- private createMessageFromInput;
21
+ newContext(): ExecutionContext;
20
22
  /**
21
23
  * Publish a message to a topic, the engine will call the listeners of the topic
22
24
  * @param topic topic name, or an array of topic names
@@ -45,20 +47,15 @@ export declare class ExecutionEngine extends EventEmitter implements Context {
45
47
  * @returns the output of the agent and the final active agent
46
48
  */
47
49
  call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string, options: {
48
- returnActiveAgent?: true;
50
+ returnActiveAgent: true;
49
51
  }): Promise<[O, Runnable]>;
50
- /**
51
- * Call an agent with a message and return the output and the active agent
52
- * @param agent Agent to call
53
- * @param message Message to pass to the agent
54
- * @returns the output of the agent and the final active agent
55
- */
56
- private _call;
52
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>, message?: I | string, options?: {
53
+ returnActiveAgent?: boolean;
54
+ }): UserAgent<I, O> | Promise<O | [O, Runnable]>;
57
55
  subscribe(topic: string, listener?: undefined): Promise<MessagePayload>;
58
56
  subscribe(topic: string, listener: MessageQueueListener): Unsubscribe;
59
57
  subscribe(topic: string, listener?: MessageQueueListener): Unsubscribe | Promise<MessagePayload>;
60
58
  unsubscribe(topic: string, listener: MessageQueueListener): void;
61
- private callAgent;
62
59
  shutdown(): Promise<void>;
63
60
  private initProcessExitHandler;
64
61
  }
@@ -1,10 +1,12 @@
1
1
  import type { Message } from "../agents/agent.js";
2
+ import type { Context } from "./context.js";
2
3
  export declare const UserInputTopic = "UserInputTopic";
3
4
  export declare const UserOutputTopic = "UserOutputTopic";
4
5
  export interface MessagePayload {
5
6
  role: "user" | "agent";
6
7
  source?: string;
7
8
  message: Message;
9
+ context: Context;
8
10
  }
9
11
  export type MessageQueueListener = (message: MessagePayload) => void;
10
12
  export type MessageRequest = MessagePayload;
@@ -1,4 +1,4 @@
1
1
  import { type FunctionAgentFn } from "../agents/agent.js";
2
2
  import type { Runnable } from "./context.js";
3
- export declare function sequential(..._agents: [Runnable, ...Runnable[]]): FunctionAgentFn;
4
- export declare function parallel(..._agents: [Runnable, ...Runnable[]]): FunctionAgentFn;
3
+ export declare function sequential(...agents: [Runnable, ...Runnable[]]): FunctionAgentFn;
4
+ export declare function parallel(...agents: [Runnable, ...Runnable[]]): FunctionAgentFn;
@@ -1,6 +1,9 @@
1
1
  import { Agent, type Message } from "../agents/agent.js";
2
+ import type { Context } from "../execution-engine/context.js";
2
3
  export declare abstract class ChatModel extends Agent<ChatModelInput, ChatModelOutput> {
3
4
  constructor();
5
+ protected preprocess(input: ChatModelInput, context: Context): void;
6
+ protected postprocess(input: ChatModelInput, output: ChatModelOutput, context: Context): void;
4
7
  }
5
8
  export interface ChatModelInput extends Message {
6
9
  messages: ChatModelInputMessage[];
@@ -71,6 +74,7 @@ export interface ChatModelOutput extends Message {
71
74
  text?: string;
72
75
  json?: object;
73
76
  toolCalls?: ChatModelOutputToolCall[];
77
+ usage?: ChatModelOutputUsage;
74
78
  }
75
79
  export interface ChatModelOutputToolCall {
76
80
  id: string;
@@ -80,3 +84,7 @@ export interface ChatModelOutputToolCall {
80
84
  arguments: Message;
81
85
  };
82
86
  }
87
+ export interface ChatModelOutputUsage {
88
+ promptTokens: number;
89
+ completionTokens: number;
90
+ }
@@ -1,3 +1,4 @@
1
+ import OpenAI from "openai";
1
2
  import { z } from "zod";
2
3
  import { ChatModel, type ChatModelInput, type ChatModelOptions, type ChatModelOutput } from "./chat-model.js";
3
4
  export interface OpenAIChatModelOptions {
@@ -61,7 +62,7 @@ export declare class OpenAIChatModel extends ChatModel {
61
62
  options?: OpenAIChatModelOptions | undefined;
62
63
  constructor(options?: OpenAIChatModelOptions | undefined);
63
64
  private _client?;
64
- private get client();
65
+ get client(): OpenAI;
65
66
  get modelOptions(): ChatModelOptions | undefined;
66
67
  process(input: ChatModelInput): Promise<ChatModelOutput>;
67
68
  }
@@ -7,6 +7,5 @@ export interface XAIChatModelOptions {
7
7
  baseURL?: string;
8
8
  }
9
9
  export declare class XAIChatModel extends OpenAIChatModel {
10
- options?: XAIChatModelOptions | undefined;
11
- constructor(options?: XAIChatModelOptions | undefined);
10
+ constructor(options?: XAIChatModelOptions);
12
11
  }
@@ -10,7 +10,7 @@ export declare const logger: debug.Debug & {
10
10
  debug: debug.Debug;
11
11
  default: debug.Debug;
12
12
  } & {
13
- globalSpinner: import("ora").Ora;
13
+ globalSpinner: import("@aigne/ora").Ora;
14
14
  base: DebugWithSpinner;
15
15
  debug: DebugWithSpinner;
16
16
  spinner: typeof spinner;
@@ -0,0 +1,3 @@
1
+ import type { ChatModelOutputUsage } from "../models/chat-model.js";
2
+ import type { Nullish } from "./type-utils.js";
3
+ export declare function mergeUsage(...usages: Nullish<ChatModelOutputUsage>[]): ChatModelOutputUsage;
@@ -1,12 +1,11 @@
1
1
  import { type ZodType } from "zod";
2
2
  export type PromiseOrValue<T> = T | Promise<T>;
3
3
  export type Nullish<T> = T | null | undefined;
4
+ export declare function isNil(value: unknown): value is null | undefined;
5
+ export declare function isEmpty(obj: unknown): boolean;
4
6
  export declare function isNonNullable<T>(value: T): value is NonNullable<T>;
5
7
  export declare function isNotEmpty<T>(arr: T[]): arr is [T, ...T[]];
6
8
  export declare function orArrayToArray<T>(value?: T | T[]): T[];
7
- export declare function get(obj: unknown, path: string | string[], type?: undefined): unknown | undefined;
8
- export declare function get(obj: unknown, path: string | string[], type: "string"): string | undefined;
9
- export declare function get(obj: unknown, path: string | string[], type: "number"): number | undefined;
10
9
  export declare function createAccessorArray<T>(array: T[], accessor: (array: T[], name: string) => T | undefined): T[] & {
11
10
  [key: string]: T;
12
11
  };
@@ -44,11 +44,15 @@ export declare abstract class Agent<I extends Message = Message, O extends Messa
44
44
  * - subscribe to memory topic if memory is enabled
45
45
  * @param context Context to attach
46
46
  */
47
- attach(context: Context): void;
47
+ attach(context: Pick<Context, "subscribe">): void;
48
48
  addTool<I extends Message, O extends Message>(tool: Agent<I, O> | FunctionAgentFn<I, O>): void;
49
49
  get isCallable(): boolean;
50
+ private checkContextStatus;
51
+ private newDefaultContext;
50
52
  call(input: I | string, context?: Context): Promise<O>;
51
- abstract process(input: I, context?: Context): Promise<O | TransferAgentOutput>;
53
+ protected preprocess(_: I, context: Context): void;
54
+ protected postprocess(input: I, output: O, context: Context): void;
55
+ abstract process(input: I, context: Context): Promise<O | TransferAgentOutput>;
52
56
  shutdown(): Promise<void>;
53
57
  }
54
58
  export type AgentInputOutputSchema<I extends Message = Message> = ZodType<I> | ((agent: Agent) => ZodType<I>);
@@ -59,6 +63,6 @@ export declare class FunctionAgent<I extends Message = Message, O extends Messag
59
63
  static from<I extends Message, O extends Message>(options: FunctionAgentOptions<I, O> | FunctionAgentFn<I, O>): FunctionAgent<I, O>;
60
64
  constructor(options: FunctionAgentOptions<I, O>);
61
65
  fn: FunctionAgentFn<I, O>;
62
- process(input: I, context?: Context): Promise<TransferAgentOutput | O>;
66
+ process(input: I, context: Context): Promise<TransferAgentOutput | O>;
63
67
  }
64
- export type FunctionAgentFn<I extends Message = Message, O extends Message = Message> = (input: I, context?: Context) => O | Promise<O> | Agent | Promise<Agent>;
68
+ export type FunctionAgentFn<I extends Message = Message, O extends Message = Message> = (input: I, context: Context) => O | Promise<O> | Agent | Promise<Agent>;
@@ -66,7 +66,7 @@ export class Agent {
66
66
  attach(context) {
67
67
  this.memory?.attach(context);
68
68
  for (const topic of orArrayToArray(this.subscribeTopic).concat(this.topic)) {
69
- context.subscribe(topic, async ({ message }) => {
69
+ context.subscribe(topic, async ({ message, context }) => {
70
70
  try {
71
71
  await context.call(this, message);
72
72
  }
@@ -82,26 +82,54 @@ export class Agent {
82
82
  get isCallable() {
83
83
  return !!this.process;
84
84
  }
85
+ checkContextStatus(context) {
86
+ if (context) {
87
+ const { status } = context;
88
+ if (status === "timeout") {
89
+ throw new Error(`ExecutionEngine for agent ${this.name} has timed out`);
90
+ }
91
+ }
92
+ }
93
+ async newDefaultContext() {
94
+ return import("../execution-engine/context.js").then((m) => new m.ExecutionContext());
95
+ }
85
96
  async call(input, context) {
97
+ const ctx = context ?? (await this.newDefaultContext());
86
98
  const _input = typeof input === "string" ? createMessage(input) : input;
87
99
  const parsedInput = this.inputSchema.parse(_input);
88
100
  logger.debug("Call agent %s start with input: %O", this.name, input);
89
- const result = this.process(parsedInput, context)
101
+ this.preprocess(parsedInput, ctx);
102
+ this.checkContextStatus(ctx);
103
+ const result = this.process(parsedInput, ctx)
90
104
  .then((output) => {
91
105
  const parsedOutput = this.outputSchema.parse(output);
92
106
  return this.includeInputInOutput ? { ...parsedInput, ...parsedOutput } : parsedOutput;
93
107
  })
94
108
  .then((output) => {
95
- this.memory?.addMemory({ role: "user", content: _input });
96
- this.memory?.addMemory({
97
- role: "agent",
98
- content: replaceTransferAgentToName(output),
99
- source: this.name,
100
- });
109
+ this.postprocess(parsedInput, output, ctx);
101
110
  return output;
102
111
  });
103
112
  return logger.debug.spinner(result, `Call agent ${this.name}`, (output) => logger.debug("Call agent %s succeed with output: %O", this.name, replaceTransferAgentToName(output)), { disabled: this.disableLogging });
104
113
  }
114
+ preprocess(_, context) {
115
+ this.checkContextStatus(context);
116
+ if (context) {
117
+ const { limits, usage } = context;
118
+ if (limits?.maxAgentCalls && usage.agentCalls >= limits.maxAgentCalls) {
119
+ throw new Error(`Exceeded max agent calls ${usage.agentCalls}/${limits.maxAgentCalls}`);
120
+ }
121
+ usage.agentCalls++;
122
+ }
123
+ }
124
+ postprocess(input, output, context) {
125
+ this.checkContextStatus(context);
126
+ this.memory?.addMemory({ role: "user", content: input });
127
+ this.memory?.addMemory({
128
+ role: "agent",
129
+ content: replaceTransferAgentToName(output),
130
+ source: this.name,
131
+ });
132
+ }
105
133
  async shutdown() {
106
134
  this.memory?.detach();
107
135
  }
@@ -27,10 +27,10 @@ export declare const aiAgentOptionsSchema: z.ZodObject<{
27
27
  disableLogging: z.ZodOptional<z.ZodBoolean>;
28
28
  memory: z.ZodOptional<z.ZodUnion<[z.ZodBoolean, z.ZodAny, z.ZodAny]>>;
29
29
  }, "strip", z.ZodTypeAny, {
30
+ description?: string | undefined;
30
31
  tools?: (Agent<Message, Message> | ((...args: unknown[]) => unknown))[] | undefined;
31
- toolChoice?: "auto" | "none" | "required" | Agent<Message, Message> | "router" | undefined;
32
+ toolChoice?: Agent<Message, Message> | "auto" | "none" | "required" | "router" | undefined;
32
33
  name?: string | undefined;
33
- description?: string | undefined;
34
34
  model?: ChatModel | undefined;
35
35
  instructions?: string | PromptBuilder | undefined;
36
36
  outputKey?: string | undefined;
@@ -42,10 +42,10 @@ export declare const aiAgentOptionsSchema: z.ZodObject<{
42
42
  disableLogging?: boolean | undefined;
43
43
  memory?: any;
44
44
  }, {
45
+ description?: string | undefined;
45
46
  tools?: (Agent<Message, Message> | ((...args: unknown[]) => unknown))[] | undefined;
46
- toolChoice?: "auto" | "none" | "required" | Agent<Message, Message> | "router" | undefined;
47
+ toolChoice?: Agent<Message, Message> | "auto" | "none" | "required" | "router" | undefined;
47
48
  name?: string | undefined;
48
- description?: string | undefined;
49
49
  model?: ChatModel | undefined;
50
50
  instructions?: string | PromptBuilder | undefined;
51
51
  outputKey?: string | undefined;
@@ -64,5 +64,5 @@ export declare class AIAgent<I extends Message = Message, O extends Message = Me
64
64
  instructions: PromptBuilder;
65
65
  outputKey?: string;
66
66
  toolChoice?: AIAgentToolChoice;
67
- process(input: I, context?: Context): Promise<import("./types.js").TransferAgentOutput | O>;
67
+ process(input: I, context: Context): Promise<import("./types.js").TransferAgentOutput | O>;
68
68
  }
@@ -47,9 +47,7 @@ export class AIAgent extends Agent {
47
47
  outputKey;
48
48
  toolChoice;
49
49
  async process(input, context) {
50
- if (!context)
51
- throw new Error("Context is required to run AIAgent");
52
- const model = context?.model ?? this.model;
50
+ const model = context.model ?? this.model;
53
51
  if (!model)
54
52
  throw new Error("model is required to run AIAgent");
55
53
  const { toolAgents, messages, ...modelInput } = await this.instructions.build({
@@ -21,6 +21,6 @@ export declare class AgentMemory {
21
21
  memories: Memory[];
22
22
  private subscriptions;
23
23
  addMemory(memory: Memory): void;
24
- attach(context: Context): void;
24
+ attach(context: Pick<Context, "subscribe">): void;
25
25
  detach(): void;
26
26
  }
@@ -3,16 +3,17 @@ import type { MessagePayload, MessageQueueListener, Unsubscribe } from "../execu
3
3
  import { type PromiseOrValue } from "../utils/type-utils.js";
4
4
  import { Agent, type AgentOptions, type Message } from "./agent.js";
5
5
  export interface UserAgentOptions<I extends Message = Message, O extends Message = Message> extends AgentOptions<I, O> {
6
- context?: Context;
6
+ context: Context;
7
7
  process?: (input: I, context: Context) => PromiseOrValue<O>;
8
8
  }
9
9
  export declare class UserAgent<I extends Message = Message, O extends Message = Message> extends Agent<I, O> {
10
10
  static from<I extends Message, O extends Message>(options: UserAgentOptions<I, O>): UserAgent<I, O>;
11
11
  constructor(options: UserAgentOptions<I, O>);
12
- private context?;
12
+ readonly context: Context;
13
13
  private get ctx();
14
14
  private _process?;
15
- process(input: I, context?: Context): Promise<O>;
15
+ call(input: string | I, context?: Context): Promise<O>;
16
+ process(input: I, context: Context): Promise<O>;
16
17
  publish(topic: string | string[], message: Message | string): void;
17
18
  subscribe(topic: string, listener?: undefined): Promise<MessagePayload>;
18
19
  subscribe(topic: string, listener: MessageQueueListener): Unsubscribe;
@@ -16,16 +16,16 @@ export class UserAgent extends Agent {
16
16
  return this.context;
17
17
  }
18
18
  _process;
19
+ call(input, context) {
20
+ return super.call(input, context ?? this.context);
21
+ }
19
22
  async process(input, context) {
20
- const ctx = context ?? this.context;
21
- if (!ctx)
22
- throw new Error("UserAgent must have a context");
23
23
  if (this._process) {
24
- return this._process(input, ctx);
24
+ return this._process(input, context);
25
25
  }
26
26
  const publicTopic = typeof this.publishTopic === "function" ? await this.publishTopic(input) : this.publishTopic;
27
27
  if (publicTopic?.length) {
28
- ctx.publish(publicTopic, input, this);
28
+ context.publish(publicTopic, input, this);
29
29
  return {};
30
30
  }
31
31
  throw new Error("UserAgent must have a process function or a publishTopic");
@@ -1,11 +1,31 @@
1
- import type EventEmitter from "node:events";
2
- import type { Agent, FunctionAgentFn, Message } from "../agents/agent.js";
1
+ import EventEmitter from "node:events";
2
+ import { Agent, type FunctionAgentFn, type Message } from "../agents/agent.js";
3
+ import { UserAgent } from "../agents/user-agent.js";
3
4
  import type { ChatModel } from "../models/chat-model.js";
4
- import type { MessagePayload, MessageQueueListener, Unsubscribe } from "./message-queue.js";
5
+ import { type MessagePayload, MessageQueue, type MessageQueueListener, type Unsubscribe } from "./message-queue.js";
5
6
  export type Runnable<I extends Message = Message, O extends Message = Message> = Agent<I, O> | FunctionAgentFn;
7
+ export interface ContextUsage {
8
+ promptTokens: number;
9
+ completionTokens: number;
10
+ agentCalls: number;
11
+ }
12
+ export interface ContextLimits {
13
+ maxTokens?: number;
14
+ maxAgentCalls?: number;
15
+ timeout?: number;
16
+ }
6
17
  export interface Context extends EventEmitter {
7
18
  model?: ChatModel;
8
19
  tools?: Agent[];
20
+ usage: ContextUsage;
21
+ limits?: ContextLimits;
22
+ status?: "normal" | "timeout";
23
+ /**
24
+ * Create a user agent to consistently call an agent
25
+ * @param agent Agent to call
26
+ * @returns User agent
27
+ */
28
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>): UserAgent<I, O>;
9
29
  /**
10
30
  * Call an agent with a message
11
31
  * @param agent Agent to call
@@ -21,11 +41,11 @@ export interface Context extends EventEmitter {
21
41
  * @returns the output of the agent and the final active agent
22
42
  */
23
43
  call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string, options: {
24
- returnActiveAgent?: true;
44
+ returnActiveAgent: true;
25
45
  }): Promise<[O, Runnable]>;
26
46
  call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string, options?: {
27
47
  returnActiveAgent?: boolean;
28
- }): Promise<O | [O, Runnable]>;
48
+ }): UserAgent<I, O> | Promise<O | [O, Runnable]>;
29
49
  /**
30
50
  * Publish a message to a topic, the engine will call the listeners of the topic
31
51
  * @param topic topic name, or an array of topic names
@@ -38,3 +58,36 @@ export interface Context extends EventEmitter {
38
58
  subscribe(topic: string, listener?: MessageQueueListener): Unsubscribe | Promise<MessagePayload>;
39
59
  unsubscribe(topic: string, listener: MessageQueueListener): void;
40
60
  }
61
+ export declare class ExecutionContext extends EventEmitter implements Context {
62
+ private readonly engine?;
63
+ constructor(engine?: {
64
+ model?: ChatModel;
65
+ tools?: Agent[];
66
+ limits?: ContextLimits;
67
+ messageQueue?: MessageQueue;
68
+ emit?: EventEmitter["emit"];
69
+ } | undefined);
70
+ private messageQueue;
71
+ get model(): ChatModel | undefined;
72
+ get tools(): Agent<Message, Message>[] | undefined;
73
+ usage: ContextUsage;
74
+ limits?: ContextLimits | undefined;
75
+ private abortController;
76
+ private timer?;
77
+ private initTimeout;
78
+ get status(): "normal" | "timeout";
79
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>): UserAgent<I, O>;
80
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string): Promise<O>;
81
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>, message: I | string, options: {
82
+ returnActiveAgent: true;
83
+ }): Promise<[O, Runnable]>;
84
+ call<I extends Message, O extends Message>(agent: Runnable<I, O>, message?: I | string, options?: {
85
+ returnActiveAgent?: boolean;
86
+ }): UserAgent<I, O> | Promise<O | [O, Runnable]>;
87
+ publish(topic: string | string[], message: Message | string, from?: Agent): void;
88
+ subscribe(topic: string, listener?: undefined): Promise<MessagePayload>;
89
+ subscribe(topic: string, listener: MessageQueueListener): Unsubscribe;
90
+ unsubscribe(topic: string, listener: MessageQueueListener): void;
91
+ emit(eventName: string | symbol, ...args: unknown[]): boolean;
92
+ private callAgent;
93
+ }