@aigne/core 1.20.1 → 1.22.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 (75) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/lib/cjs/agents/agent.d.ts +6 -4
  3. package/lib/cjs/agents/agent.js +2 -0
  4. package/lib/cjs/agents/ai-agent.d.ts +8 -10
  5. package/lib/cjs/agents/ai-agent.js +6 -5
  6. package/lib/cjs/agents/chat-model.d.ts +1 -0
  7. package/lib/cjs/agents/chat-model.js +1 -0
  8. package/lib/cjs/agents/mcp-agent.d.ts +5 -0
  9. package/lib/cjs/agents/mcp-agent.js +5 -0
  10. package/lib/cjs/agents/team-agent.d.ts +1 -0
  11. package/lib/cjs/agents/team-agent.js +1 -0
  12. package/lib/cjs/agents/user-agent.d.ts +1 -0
  13. package/lib/cjs/agents/user-agent.js +6 -3
  14. package/lib/cjs/aigne/aigne.d.ts +15 -6
  15. package/lib/cjs/aigne/aigne.js +19 -2
  16. package/lib/cjs/aigne/context.d.ts +31 -10
  17. package/lib/cjs/aigne/context.js +86 -14
  18. package/lib/cjs/loader/agent-js.d.ts +2 -2
  19. package/lib/cjs/loader/agent-js.js +3 -0
  20. package/lib/cjs/loader/agent-yaml.d.ts +23 -6
  21. package/lib/cjs/loader/agent-yaml.js +38 -2
  22. package/lib/cjs/loader/index.d.ts +1 -1
  23. package/lib/cjs/loader/index.js +16 -4
  24. package/lib/cjs/memory/memory.d.ts +1 -0
  25. package/lib/cjs/memory/memory.js +1 -0
  26. package/lib/cjs/memory/recorder.d.ts +1 -0
  27. package/lib/cjs/memory/recorder.js +1 -0
  28. package/lib/cjs/memory/retriever.d.ts +1 -0
  29. package/lib/cjs/memory/retriever.js +1 -0
  30. package/lib/cjs/prompt/prompt-builder.d.ts +1 -1
  31. package/lib/dts/agents/agent.d.ts +6 -4
  32. package/lib/dts/agents/ai-agent.d.ts +8 -10
  33. package/lib/dts/agents/chat-model.d.ts +1 -0
  34. package/lib/dts/agents/mcp-agent.d.ts +5 -0
  35. package/lib/dts/agents/team-agent.d.ts +1 -0
  36. package/lib/dts/agents/user-agent.d.ts +1 -0
  37. package/lib/dts/aigne/aigne.d.ts +15 -6
  38. package/lib/dts/aigne/context.d.ts +31 -10
  39. package/lib/dts/loader/agent-js.d.ts +2 -2
  40. package/lib/dts/loader/agent-yaml.d.ts +23 -6
  41. package/lib/dts/loader/index.d.ts +1 -1
  42. package/lib/dts/memory/memory.d.ts +1 -0
  43. package/lib/dts/memory/recorder.d.ts +1 -0
  44. package/lib/dts/memory/retriever.d.ts +1 -0
  45. package/lib/dts/prompt/prompt-builder.d.ts +1 -1
  46. package/lib/esm/agents/agent.d.ts +6 -4
  47. package/lib/esm/agents/agent.js +2 -0
  48. package/lib/esm/agents/ai-agent.d.ts +8 -10
  49. package/lib/esm/agents/ai-agent.js +3 -2
  50. package/lib/esm/agents/chat-model.d.ts +1 -0
  51. package/lib/esm/agents/chat-model.js +1 -0
  52. package/lib/esm/agents/mcp-agent.d.ts +5 -0
  53. package/lib/esm/agents/mcp-agent.js +5 -0
  54. package/lib/esm/agents/team-agent.d.ts +1 -0
  55. package/lib/esm/agents/team-agent.js +1 -0
  56. package/lib/esm/agents/user-agent.d.ts +1 -0
  57. package/lib/esm/agents/user-agent.js +6 -3
  58. package/lib/esm/aigne/aigne.d.ts +15 -6
  59. package/lib/esm/aigne/aigne.js +19 -2
  60. package/lib/esm/aigne/context.d.ts +31 -10
  61. package/lib/esm/aigne/context.js +86 -14
  62. package/lib/esm/loader/agent-js.d.ts +2 -2
  63. package/lib/esm/loader/agent-js.js +3 -0
  64. package/lib/esm/loader/agent-yaml.d.ts +23 -6
  65. package/lib/esm/loader/agent-yaml.js +38 -2
  66. package/lib/esm/loader/index.d.ts +1 -1
  67. package/lib/esm/loader/index.js +17 -5
  68. package/lib/esm/memory/memory.d.ts +1 -0
  69. package/lib/esm/memory/memory.js +1 -0
  70. package/lib/esm/memory/recorder.d.ts +1 -0
  71. package/lib/esm/memory/recorder.js +1 -0
  72. package/lib/esm/memory/retriever.d.ts +1 -0
  73. package/lib/esm/memory/retriever.js +1 -0
  74. package/lib/esm/prompt/prompt-builder.d.ts +1 -1
  75. package/package.json +2 -1
@@ -1,3 +1,4 @@
1
+ import { AIGNEObserver } from "@aigne/observability";
1
2
  import { Agent, type AgentResponse, type AgentResponseStream, type Message } from "../agents/agent.js";
2
3
  import { ChatModel } from "../agents/chat-model.js";
3
4
  import type { UserAgent } from "../agents/user-agent.js";
@@ -33,6 +34,10 @@ export interface AIGNEOptions {
33
34
  * Limits for the AIGNE instance, such as timeout, max tokens, max invocations, etc.
34
35
  */
35
36
  limits?: ContextLimits;
37
+ /**
38
+ * Observer for the AIGNE instance.
39
+ */
40
+ observer?: AIGNEObserver;
36
41
  }
37
42
  /**
38
43
  * AIGNE is a class that orchestrates multiple agents to build complex AI applications.
@@ -98,6 +103,10 @@ export declare class AIGNE<U extends UserContext = UserContext> {
98
103
  readonly agents: Agent<Message, Message>[] & {
99
104
  [key: string]: Agent<Message, Message>;
100
105
  };
106
+ /**
107
+ * Observer for the AIGNE instance.
108
+ */
109
+ readonly observer?: AIGNEObserver;
101
110
  /**
102
111
  * Adds one or more agents to this AIGNE instance.
103
112
  * Each agent is attached to this AIGNE instance, allowing it to access the AIGNE's resources.
@@ -111,7 +120,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
111
120
  *
112
121
  * @returns A new AIGNEContext instance bound to this AIGNE.
113
122
  */
114
- newContext(options?: Partial<Context>): AIGNEContext;
123
+ newContext(options?: Partial<Pick<Context, "userContext" | "memories">>): AIGNEContext;
115
124
  /**
116
125
  * Creates a user agent for consistent interactions with a specified agent.
117
126
  * This method allows you to create a wrapper around an agent for repeated invocations.
@@ -134,7 +143,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
134
143
  * @param options.streaming - Must be false to return a response stream
135
144
  * @returns A promise resolving to a tuple containing the agent's response and the final active agent
136
145
  */
137
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
146
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options: InvokeOptions<U> & {
138
147
  returnActiveAgent: true;
139
148
  streaming?: false;
140
149
  }): Promise<[O, Agent]>;
@@ -148,7 +157,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
148
157
  * @param options.streaming - Must be true to return a response stream
149
158
  * @returns A promise resolving to a tuple containing the agent's response stream and a promise for the final agent
150
159
  */
151
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
160
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options: InvokeOptions<U> & {
152
161
  returnActiveAgent: true;
153
162
  streaming: true;
154
163
  }): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
@@ -165,7 +174,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
165
174
  * Here's a simple example of how to invoke an agent:
166
175
  * {@includeCode ../../test/aigne/aigne.test.ts#example-simple}
167
176
  */
168
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options?: InvokeOptions<U> & {
177
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options?: InvokeOptions<U> & {
169
178
  returnActiveAgent?: false;
170
179
  streaming?: false;
171
180
  }): Promise<O>;
@@ -182,7 +191,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
182
191
  * Here's an example of how to invoke an agent with streaming response:
183
192
  * {@includeCode ../../test/aigne/aigne.test.ts#example-streaming}
184
193
  */
185
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions<U> & {
194
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options: InvokeOptions<U> & {
186
195
  returnActiveAgent?: false;
187
196
  streaming: true;
188
197
  }): Promise<AgentResponseStream<O>>;
@@ -196,7 +205,7 @@ export declare class AIGNE<U extends UserContext = UserContext> {
196
205
  * @returns Either a UserAgent (when no message provided) or a promise resolving to the agent's response
197
206
  * with optional active agent information based on the provided options
198
207
  */
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]>;
208
+ 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
209
  /**
201
210
  * Publishes a message to the message queue for inter-agent communication.
202
211
  * This method broadcasts a message to all subscribers of the specified topic(s).
@@ -1,3 +1,4 @@
1
+ import { AIGNEObserver } from "@aigne/observability";
1
2
  import { z } from "zod";
2
3
  import { Agent, } from "../agents/agent.js";
3
4
  import { ChatModel } from "../agents/chat-model.js";
@@ -49,10 +50,15 @@ export class AIGNE {
49
50
  this.description = options?.description;
50
51
  this.model = options?.model;
51
52
  this.limits = options?.limits;
53
+ this.observer =
54
+ process.env.AIGNE_OBSERVABILITY_DISABLED === "true"
55
+ ? undefined
56
+ : (options?.observer ?? new AIGNEObserver());
52
57
  if (options?.skills?.length)
53
58
  this.skills.push(...options.skills);
54
59
  if (options?.agents?.length)
55
60
  this.addAgent(...options.agents);
61
+ this.observer?.serve();
56
62
  this.initProcessExitHandler();
57
63
  }
58
64
  /**
@@ -87,6 +93,10 @@ export class AIGNE {
87
93
  * Provides indexed access by agent name.
88
94
  */
89
95
  agents = createAccessorArray([], (arr, name) => arr.find((i) => i.name === name));
96
+ /**
97
+ * Observer for the AIGNE instance.
98
+ */
99
+ observer;
90
100
  /**
91
101
  * Adds one or more agents to this AIGNE instance.
92
102
  * Each agent is attached to this AIGNE instance, allowing it to access the AIGNE's resources.
@@ -107,10 +117,16 @@ export class AIGNE {
107
117
  * @returns A new AIGNEContext instance bound to this AIGNE.
108
118
  */
109
119
  newContext(options) {
110
- return new AIGNEContext(this, options);
120
+ const context = new AIGNEContext(this);
121
+ if (options?.userContext)
122
+ context.userContext = options.userContext;
123
+ if (options?.memories)
124
+ context.memories = options.memories;
125
+ return context;
111
126
  }
112
127
  invoke(agent, message, options) {
113
- return new AIGNEContext(this).invoke(agent, message, options);
128
+ const context = new AIGNEContext(this);
129
+ return context.invoke(agent, message, { ...options, newContext: false });
114
130
  }
115
131
  /**
116
132
  * Publishes a message to the message queue for inter-agent communication.
@@ -188,5 +204,6 @@ const aigneOptionsSchema = z.object({
188
204
  model: z.instanceof(ChatModel).optional(),
189
205
  skills: z.array(z.instanceof(Agent)).optional(),
190
206
  agents: z.array(z.instanceof(Agent)).optional(),
207
+ observer: z.instanceof(AIGNEObserver).optional(),
191
208
  });
192
209
  const aigneAddAgentArgsSchema = z.array(z.instanceof(Agent));
@@ -1,3 +1,5 @@
1
+ import type { AIGNEObserver } from "@aigne/observability";
2
+ import type { Span } from "@opentelemetry/api";
1
3
  import { Emitter } from "strict-event-emitter";
2
4
  import { Agent, type AgentInvokeOptions, type AgentProcessAsyncGenerator, type AgentResponse, type AgentResponseStream, type Message } from "../agents/agent.js";
3
5
  import type { ChatModel } from "../agents/chat-model.js";
@@ -45,6 +47,13 @@ export interface InvokeOptions<U extends UserContext = UserContext> extends Part
45
47
  returnMetadata?: boolean;
46
48
  disableTransfer?: boolean;
47
49
  sourceAgent?: Agent;
50
+ /**
51
+ * Whether to create a new context for this invocation.
52
+ * If false, the invocation will use the current context.
53
+ *
54
+ * @default true
55
+ */
56
+ newContext?: boolean;
48
57
  }
49
58
  /**
50
59
  * @hidden
@@ -57,8 +66,11 @@ export interface UserContext extends Record<string, unknown> {
57
66
  export interface Context<U extends UserContext = UserContext> extends TypedEventEmitter<ContextEventMap, ContextEmitEventMap> {
58
67
  id: string;
59
68
  parentId?: string;
69
+ rootId: string;
60
70
  model?: ChatModel;
61
71
  skills?: Agent[];
72
+ observer?: AIGNEObserver;
73
+ span?: Span;
62
74
  usage: ContextUsage;
63
75
  limits?: ContextLimits;
64
76
  status?: "normal" | "timeout";
@@ -78,11 +90,11 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
78
90
  * @param options.streaming return a stream of the output
79
91
  * @returns the output of the agent and the final active agent
80
92
  */
81
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
93
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options: InvokeOptions & {
82
94
  returnActiveAgent: true;
83
95
  streaming?: false;
84
96
  }): Promise<[O, Agent]>;
85
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
97
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options: InvokeOptions & {
86
98
  returnActiveAgent: true;
87
99
  streaming: true;
88
100
  }): Promise<[AgentResponseStream<O>, Promise<Agent>]>;
@@ -92,13 +104,13 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
92
104
  * @param message Message to pass to the agent
93
105
  * @returns the output of the agent
94
106
  */
95
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options?: InvokeOptions & {
107
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options?: InvokeOptions & {
96
108
  streaming?: false;
97
109
  }): Promise<O>;
98
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I, options: InvokeOptions & {
110
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, message: I & Message, options: InvokeOptions & {
99
111
  streaming: true;
100
112
  }): Promise<AgentResponseStream<O>>;
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]>;
113
+ 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]>;
102
114
  /**
103
115
  * Publish a message to a topic, the aigne will invoke the listeners of the topic
104
116
  * @param topic topic name, or an array of topic names
@@ -126,12 +138,18 @@ export interface Context<U extends UserContext = UserContext> extends TypedEvent
126
138
  * @hidden
127
139
  */
128
140
  export declare class AIGNEContext implements Context {
129
- constructor(...[parent, ...args]: ConstructorParameters<typeof AIGNEContextShared>);
130
- parentId?: string;
141
+ constructor(parent?: ConstructorParameters<typeof AIGNEContextShared>[0], { reset }?: {
142
+ reset?: boolean;
143
+ });
131
144
  id: string;
145
+ parentId?: string;
146
+ rootId: string;
147
+ span?: Span;
132
148
  readonly internal: AIGNEContextShared;
149
+ get messageQueue(): MessageQueue;
133
150
  get model(): ChatModel | undefined;
134
151
  get skills(): Agent<Message, Message>[] | undefined;
152
+ get observer(): AIGNEObserver | undefined;
135
153
  get limits(): ContextLimits | undefined;
136
154
  get status(): "normal" | "timeout";
137
155
  get usage(): ContextUsage;
@@ -148,19 +166,22 @@ export declare class AIGNEContext implements Context {
148
166
  subscribe: Context["subscribe"];
149
167
  unsubscribe: Context["unsubscribe"];
150
168
  emit<K extends keyof ContextEmitEventMap>(eventName: K, ...args: Args<K, ContextEmitEventMap>): boolean;
169
+ private trace;
151
170
  on<K extends keyof ContextEventMap>(eventName: K, listener: Listener<K, ContextEventMap>): this;
152
171
  once<K extends keyof ContextEventMap>(eventName: K, listener: Listener<K, ContextEventMap>): this;
153
172
  off<K extends keyof ContextEventMap>(eventName: K, listener: Listener<K, ContextEventMap>): this;
154
173
  }
155
174
  declare class AIGNEContextShared {
156
175
  private readonly parent?;
157
- constructor(parent?: (Pick<Context, "model" | "skills" | "limits"> & {
176
+ span?: Span;
177
+ constructor(parent?: (Pick<Context, "model" | "skills" | "limits" | "observer"> & {
158
178
  messageQueue?: MessageQueue;
159
- }) | undefined, overrides?: Partial<Context>);
179
+ }) | undefined);
160
180
  readonly messageQueue: MessageQueue;
161
181
  readonly events: Emitter<any>;
162
182
  get model(): ChatModel | undefined;
163
183
  get skills(): Agent<Message, Message>[] | undefined;
184
+ get observer(): AIGNEObserver | undefined;
164
185
  get limits(): ContextLimits | undefined;
165
186
  usage: ContextUsage;
166
187
  userContext: Context["userContext"];
@@ -169,7 +190,7 @@ declare class AIGNEContextShared {
169
190
  private timer?;
170
191
  private initTimeout;
171
192
  get status(): "normal" | "timeout";
172
- invoke<I extends Message, O extends Message>(agent: Agent<I, O>, input: I, context: Context, options?: InvokeOptions): AgentProcessAsyncGenerator<O & {
193
+ invoke<I extends Message, O extends Message>(agent: Agent<I, O>, input: I & Message, context: Context, options?: InvokeOptions): AgentProcessAsyncGenerator<O & {
173
194
  __activeAgent__: Agent;
174
195
  }>;
175
196
  private invokeAgent;
@@ -1,3 +1,4 @@
1
+ import { SpanStatusCode, context, trace } from "@opentelemetry/api";
1
2
  import equal from "fast-deep-equal";
2
3
  import { Emitter } from "strict-event-emitter";
3
4
  import { v7 } from "uuid";
@@ -6,6 +7,7 @@ import { Agent, isAgentResponseDelta, isEmptyChunk, } from "../agents/agent.js";
6
7
  import { isTransferAgentOutput, transferAgentOutputKey, } from "../agents/types.js";
7
8
  import { UserAgent } from "../agents/user-agent.js";
8
9
  import { AgentResponseProgressStream } from "../utils/event-stream.js";
10
+ import { logger } from "../utils/logger.js";
9
11
  import { promiseWithResolvers } from "../utils/promise.js";
10
12
  import { agentResponseStreamToObject, asyncGeneratorToReadableStream, mergeReadableStreams, onAgentResponseStreamEnd, } from "../utils/stream-utils.js";
11
13
  import { checkArguments, isEmpty, isNil, omit, } from "../utils/type-utils.js";
@@ -15,24 +17,47 @@ import { newEmptyContextUsage } from "./usage.js";
15
17
  * @hidden
16
18
  */
17
19
  export class AIGNEContext {
18
- constructor(...[parent, ...args]) {
19
- if (parent instanceof AIGNEContext) {
20
- this.parentId = parent.id;
20
+ constructor(parent, { reset } = {}) {
21
+ const tracer = parent?.observer?.tracer;
22
+ if (parent instanceof AIGNEContext && !reset) {
21
23
  this.internal = parent.internal;
24
+ this.parentId = parent.id;
25
+ this.rootId = parent.rootId;
26
+ if (parent.span) {
27
+ const parentContext = trace.setSpan(context.active(), parent.span);
28
+ this.span = tracer?.startSpan("childAIGNEContext", undefined, parentContext);
29
+ }
30
+ else {
31
+ if (!process.env.AIGNE_OBSERVABILITY_DISABLED) {
32
+ throw new Error("parent span is not set");
33
+ }
34
+ }
22
35
  }
23
36
  else {
24
- this.internal = new AIGNEContextShared(parent, ...args);
37
+ this.internal = new AIGNEContextShared(parent);
38
+ this.span = tracer?.startSpan("AIGNEContext");
39
+ // 修改了 rootId 是否会之前的有影响?,之前为 this.id
40
+ this.rootId = this.span?.spanContext?.().traceId ?? v7();
25
41
  }
42
+ this.id = this.span?.spanContext()?.spanId ?? v7();
26
43
  }
44
+ id;
27
45
  parentId;
28
- id = v7();
46
+ rootId;
47
+ span;
29
48
  internal;
49
+ get messageQueue() {
50
+ return this.internal.messageQueue;
51
+ }
30
52
  get model() {
31
53
  return this.internal.model;
32
54
  }
33
55
  get skills() {
34
56
  return this.internal.skills;
35
57
  }
58
+ get observer() {
59
+ return this.internal.observer;
60
+ }
36
61
  get limits() {
37
62
  return this.internal.limits;
38
63
  }
@@ -55,9 +80,7 @@ export class AIGNEContext {
55
80
  this.internal.memories = memories;
56
81
  }
57
82
  newContext({ reset } = {}) {
58
- if (reset)
59
- return new AIGNEContext(this, { userContext: {} });
60
- return new AIGNEContext(this);
83
+ return new AIGNEContext(this, { reset });
61
84
  }
62
85
  invoke = ((agent, message, options) => {
63
86
  checkArguments("AIGNEContext.invoke", aigneContextInvokeArgsSchema, {
@@ -79,7 +102,7 @@ export class AIGNEContext {
79
102
  activeAgent: agent,
80
103
  });
81
104
  }
82
- const newContext = this.newContext();
105
+ const newContext = options?.newContext === false ? this : this.newContext();
83
106
  return Promise.resolve(newContext.internal.invoke(agent, message, newContext, options)).then(async (response) => {
84
107
  if (!options?.streaming) {
85
108
  let { __activeAgent__: activeAgent, ...output } = await agentResponseStreamToObject(response);
@@ -156,8 +179,55 @@ export class AIGNEContext {
156
179
  timestamp: Date.now(),
157
180
  };
158
181
  const newArgs = [b, ...args.slice(1)];
182
+ this.trace(eventName, args, b);
159
183
  return this.internal.events.emit(eventName, ...newArgs);
160
184
  }
185
+ async trace(eventName, args, b) {
186
+ const span = this.span;
187
+ if (!span)
188
+ return;
189
+ try {
190
+ switch (eventName) {
191
+ case "agentStarted": {
192
+ const { agent, input } = args[0];
193
+ span.updateName(agent.name);
194
+ span.setAttribute("custom.trace_id", this.rootId);
195
+ span.setAttribute("custom.span_id", this.id);
196
+ if (this.parentId) {
197
+ span.setAttribute("custom.parent_id", this.parentId);
198
+ }
199
+ span.setAttribute("custom.started_at", b.timestamp);
200
+ span.setAttribute("input", JSON.stringify(input));
201
+ span.setAttribute("agentTag", agent.tag ?? "UnknownAgent");
202
+ break;
203
+ }
204
+ case "agentSucceed": {
205
+ const { output } = args[0];
206
+ try {
207
+ span.setAttribute("output", JSON.stringify(output));
208
+ }
209
+ catch (_e) {
210
+ logger.error("parse output error", _e.message);
211
+ span.setAttribute("output", JSON.stringify({}));
212
+ }
213
+ span.setStatus({ code: SpanStatusCode.OK, message: "Agent succeed" });
214
+ span.end();
215
+ await this.observer?.traceExporter?.forceFlush?.();
216
+ break;
217
+ }
218
+ case "agentFailed": {
219
+ const { error } = args[0];
220
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
221
+ span.end();
222
+ await this.observer?.traceExporter?.forceFlush?.();
223
+ break;
224
+ }
225
+ }
226
+ }
227
+ catch (err) {
228
+ logger.error("AIGNEContext.trace observer error", { eventName, error: err });
229
+ }
230
+ }
161
231
  on(eventName, listener) {
162
232
  this.internal.events.on(eventName, listener);
163
233
  return this;
@@ -173,11 +243,10 @@ export class AIGNEContext {
173
243
  }
174
244
  class AIGNEContextShared {
175
245
  parent;
176
- constructor(parent, overrides) {
246
+ span;
247
+ constructor(parent) {
177
248
  this.parent = parent;
178
249
  this.messageQueue = this.parent?.messageQueue ?? new MessageQueue();
179
- this.userContext = overrides?.userContext ?? {};
180
- this.memories = overrides?.memories ?? [];
181
250
  }
182
251
  messageQueue;
183
252
  events = new Emitter();
@@ -187,12 +256,15 @@ class AIGNEContextShared {
187
256
  get skills() {
188
257
  return this.parent?.skills;
189
258
  }
259
+ get observer() {
260
+ return this.parent?.observer;
261
+ }
190
262
  get limits() {
191
263
  return this.parent?.limits;
192
264
  }
193
265
  usage = newEmptyContextUsage();
194
- userContext;
195
- memories;
266
+ userContext = {};
267
+ memories = [];
196
268
  abortController = new AbortController();
197
269
  timer;
198
270
  initTimeout() {
@@ -1,6 +1,6 @@
1
1
  import { type ZodObject, type ZodType, z } from "zod";
2
- import type { Message } from "../agents/agent.js";
3
- export declare function loadAgentFromJsFile(path: string): Promise<{
2
+ import { Agent, type Message } from "../agents/agent.js";
3
+ export declare function loadAgentFromJsFile(path: string): Promise<Agent<any, any> | {
4
4
  process: (args_0: Message) => Message;
5
5
  name: string;
6
6
  description?: string | undefined;
@@ -1,5 +1,6 @@
1
1
  import { jsonSchemaToZod } from "@aigne/json-schema-to-zod";
2
2
  import { z } from "zod";
3
+ import { Agent } from "../agents/agent.js";
3
4
  import { customCamelize } from "../utils/camelize.js";
4
5
  import { tryOrThrow } from "../utils/type-utils.js";
5
6
  import { inputOutputSchema } from "./schema.js";
@@ -19,6 +20,8 @@ const agentJsFileSchema = z.object({
19
20
  });
20
21
  export async function loadAgentFromJsFile(path) {
21
22
  const { default: agent } = await tryOrThrow(() => import(path), (error) => new Error(`Failed to load agent definition from ${path}: ${error.message}`));
23
+ if (agent instanceof Agent)
24
+ return agent;
22
25
  if (typeof agent !== "function") {
23
26
  throw new Error(`Agent file ${path} must export a default function, but got ${typeof agent}`);
24
27
  }
@@ -1,6 +1,29 @@
1
1
  import { type ZodObject, type ZodType, z } from "zod";
2
2
  import { AIAgentToolChoice } from "../agents/ai-agent.js";
3
+ import { ProcessMode } from "../agents/team-agent.js";
3
4
  export declare function loadAgentFromYamlFile(path: string): Promise<{
5
+ type: "mcp";
6
+ url?: string | undefined;
7
+ command?: string | undefined;
8
+ args?: string[] | undefined;
9
+ } | {
10
+ type: "team";
11
+ name: string;
12
+ description?: string | undefined;
13
+ skills?: string[] | undefined;
14
+ mode?: ProcessMode | undefined;
15
+ inputSchema?: ZodObject<Record<string, ZodType<any, z.ZodTypeDef, any>>, z.UnknownKeysParam, z.ZodTypeAny, {
16
+ [x: string]: any;
17
+ }, {
18
+ [x: string]: any;
19
+ }> | undefined;
20
+ outputSchema?: ZodObject<Record<string, ZodType<any, z.ZodTypeDef, any>>, z.UnknownKeysParam, z.ZodTypeAny, {
21
+ [x: string]: any;
22
+ }, {
23
+ [x: string]: any;
24
+ }> | undefined;
25
+ } | {
26
+ instructions: string | undefined;
4
27
  type: "ai";
5
28
  name: string;
6
29
  description?: string | undefined;
@@ -9,7 +32,6 @@ export declare function loadAgentFromYamlFile(path: string): Promise<{
9
32
  provider: string;
10
33
  subscribeTopic?: string[] | undefined;
11
34
  } | undefined;
12
- instructions?: string | undefined;
13
35
  inputSchema?: ZodObject<Record<string, ZodType<any, z.ZodTypeDef, any>>, z.UnknownKeysParam, z.ZodTypeAny, {
14
36
  [x: string]: any;
15
37
  }, {
@@ -23,9 +45,4 @@ export declare function loadAgentFromYamlFile(path: string): Promise<{
23
45
  inputKey?: string | undefined;
24
46
  outputKey?: string | undefined;
25
47
  toolChoice?: AIAgentToolChoice | undefined;
26
- } | {
27
- type: "mcp";
28
- url?: string | undefined;
29
- args?: string[] | undefined;
30
- command?: string | undefined;
31
48
  }>;
@@ -3,6 +3,7 @@ import { nodejs } from "@aigne/platform-helpers/nodejs/index.js";
3
3
  import { parse } from "yaml";
4
4
  import { z } from "zod";
5
5
  import { AIAgentToolChoice } from "../agents/ai-agent.js";
6
+ import { ProcessMode } from "../agents/team-agent.js";
6
7
  import { customCamelize } from "../utils/camelize.js";
7
8
  import { tryOrThrow } from "../utils/type-utils.js";
8
9
  import { inputOutputSchema } from "./schema.js";
@@ -15,7 +16,12 @@ const agentFileSchema = z.discriminatedUnion("type", [
15
16
  .nullish()
16
17
  .transform((v) => v ?? undefined),
17
18
  instructions: z
18
- .string()
19
+ .union([
20
+ z.string(),
21
+ z.object({
22
+ url: z.string(),
23
+ }),
24
+ ])
19
25
  .nullish()
20
26
  .transform((v) => v ?? undefined),
21
27
  input_key: z
@@ -69,16 +75,46 @@ const agentFileSchema = z.discriminatedUnion("type", [
69
75
  .nullish()
70
76
  .transform((v) => v ?? undefined),
71
77
  }),
78
+ z.object({
79
+ type: z.literal("team"),
80
+ name: z.string(),
81
+ description: z
82
+ .string()
83
+ .nullish()
84
+ .transform((v) => v ?? undefined),
85
+ input_schema: inputOutputSchema
86
+ .nullish()
87
+ .transform((v) => (v ? jsonSchemaToZod(v) : undefined)),
88
+ output_schema: inputOutputSchema
89
+ .nullish()
90
+ .transform((v) => (v ? jsonSchemaToZod(v) : undefined)),
91
+ skills: z
92
+ .array(z.string())
93
+ .nullish()
94
+ .transform((v) => v ?? undefined),
95
+ mode: z
96
+ .nativeEnum(ProcessMode)
97
+ .nullish()
98
+ .transform((v) => v ?? undefined),
99
+ }),
72
100
  ]);
73
101
  export async function loadAgentFromYamlFile(path) {
74
102
  const raw = await tryOrThrow(() => nodejs.fs.readFile(path, "utf8"), (error) => new Error(`Failed to load agent definition from ${path}: ${error.message}`));
75
103
  const json = await tryOrThrow(() => parse(raw), (error) => new Error(`Failed to parse agent definition from ${path}: ${error.message}`));
76
- const agent = tryOrThrow(() => customCamelize(agentFileSchema.parse({
104
+ const agent = await tryOrThrow(async () => customCamelize(await agentFileSchema.parseAsync({
77
105
  ...json,
78
106
  type: json.type ?? "ai",
79
107
  skills: json.skills ?? json.tools,
80
108
  }), {
81
109
  shallowKeys: ["input_schema", "output_schema"],
82
110
  }), (error) => new Error(`Failed to validate agent definition from ${path}: ${error.message}`));
111
+ if (agent.type === "ai") {
112
+ return {
113
+ ...agent,
114
+ instructions: typeof agent.instructions === "object" && "url" in agent.instructions
115
+ ? await nodejs.fs.readFile(nodejs.path.join(nodejs.path.dirname(path), agent.instructions.url), "utf8")
116
+ : agent.instructions,
117
+ };
118
+ }
83
119
  return agent;
84
120
  }
@@ -1,6 +1,6 @@
1
1
  import type { Camelize } from "camelize-ts";
2
2
  import { z } from "zod";
3
- import { type Agent } from "../agents/agent.js";
3
+ import { Agent } from "../agents/agent.js";
4
4
  import type { ChatModel, ChatModelOptions } from "../agents/chat-model.js";
5
5
  import type { MemoryAgent, MemoryAgentOptions } from "../memory/memory.js";
6
6
  export interface LoadOptions {
@@ -1,9 +1,10 @@
1
1
  import { nodejs } from "@aigne/platform-helpers/nodejs/index.js";
2
2
  import { parse } from "yaml";
3
3
  import { z } from "zod";
4
- import { FunctionAgent } from "../agents/agent.js";
4
+ import { Agent, FunctionAgent } from "../agents/agent.js";
5
5
  import { AIAgent } from "../agents/ai-agent.js";
6
6
  import { MCPAgent } from "../agents/mcp-agent.js";
7
+ import { TeamAgent } from "../agents/team-agent.js";
7
8
  import { tryOrThrow } from "../utils/type-utils.js";
8
9
  import { loadAgentFromJsFile } from "./agent-js.js";
9
10
  import { loadAgentFromYamlFile } from "./agent-yaml.js";
@@ -22,20 +23,25 @@ export async function load(options) {
22
23
  };
23
24
  }
24
25
  export async function loadAgent(path, options) {
25
- if (nodejs.path.extname(path) === ".js") {
26
+ if ([".js", ".mjs", ".ts", ".mts"].includes(nodejs.path.extname(path))) {
26
27
  const agent = await loadAgentFromJsFile(path);
28
+ if (agent instanceof Agent)
29
+ return agent;
27
30
  return FunctionAgent.from(agent);
28
31
  }
29
- if (nodejs.path.extname(path) === ".yaml" || nodejs.path.extname(path) === ".yml") {
32
+ if ([".yml", ".yaml"].includes(nodejs.path.extname(path))) {
30
33
  const agent = await loadAgentFromYamlFile(path);
34
+ const skills = "skills" in agent
35
+ ? agent.skills &&
36
+ (await Promise.all(agent.skills.map((filename) => loadAgent(nodejs.path.join(nodejs.path.dirname(path), filename), options))))
37
+ : undefined;
31
38
  if (agent.type === "ai") {
32
39
  return AIAgent.from({
33
40
  ...agent,
34
41
  memory: !options?.memories?.length || !agent.memory
35
42
  ? undefined
36
43
  : await loadMemory(options.memories, typeof agent.memory === "object" ? agent.memory.provider : undefined, typeof agent.memory === "object" ? agent.memory : {}),
37
- skills: agent.skills &&
38
- (await Promise.all(agent.skills.map((filename) => loadAgent(nodejs.path.join(nodejs.path.dirname(path), filename), options)))),
44
+ skills,
39
45
  });
40
46
  }
41
47
  if (agent.type === "mcp") {
@@ -52,6 +58,12 @@ export async function loadAgent(path, options) {
52
58
  }
53
59
  throw new Error(`Missing url or command in mcp agent: ${path}`);
54
60
  }
61
+ if (agent.type === "team") {
62
+ return TeamAgent.from({
63
+ ...agent,
64
+ skills,
65
+ });
66
+ }
55
67
  }
56
68
  throw new Error(`Unsupported agent file type: ${path}`);
57
69
  }
@@ -21,6 +21,7 @@ export interface MemoryAgentOptions extends Partial<Pick<MemoryAgent, "recorder"
21
21
  * instead provides memory management capabilities to the system.
22
22
  */
23
23
  export declare class MemoryAgent extends Agent {
24
+ tag: string;
24
25
  /**
25
26
  * Creates a new MemoryAgent instance.
26
27
  */
@@ -12,6 +12,7 @@ export const newMemoryId = () => v7();
12
12
  * instead provides memory management capabilities to the system.
13
13
  */
14
14
  export class MemoryAgent extends Agent {
15
+ tag = "MemoryAgent";
15
16
  /**
16
17
  * Creates a new MemoryAgent instance.
17
18
  */
@@ -77,6 +77,7 @@ export declare const memoryRecorderOutputSchema: z.ZodObject<{
77
77
  * implementations of the process method to handle the actual storage logic.
78
78
  */
79
79
  export declare abstract class MemoryRecorder extends Agent<MemoryRecorderInput, MemoryRecorderOutput> {
80
+ tag: string;
80
81
  /**
81
82
  * Creates a new MemoryRecorder instance with predefined input and output schemas.
82
83
  *
@@ -31,6 +31,7 @@ export const memoryRecorderOutputSchema = z.object({
31
31
  * implementations of the process method to handle the actual storage logic.
32
32
  */
33
33
  export class MemoryRecorder extends Agent {
34
+ tag = "MemoryRecorderAgent";
34
35
  /**
35
36
  * Creates a new MemoryRecorder instance with predefined input and output schemas.
36
37
  *