@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
@@ -11,7 +11,7 @@ const zod_1 = require("zod");
11
11
  const agent_js_1 = require("../agents/agent.js");
12
12
  const types_js_1 = require("../agents/types.js");
13
13
  const user_agent_js_1 = require("../agents/user-agent.js");
14
- const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
14
+ const event_stream_js_1 = require("../utils/event-stream.js");
15
15
  const promise_js_1 = require("../utils/promise.js");
16
16
  const stream_utils_js_1 = require("../utils/stream-utils.js");
17
17
  const type_utils_js_1 = require("../utils/type-utils.js");
@@ -86,38 +86,54 @@ class AIGNEContext {
86
86
  });
87
87
  }
88
88
  const newContext = this.newContext();
89
- const msg = (0, prompt_builder_js_1.createMessage)(message);
90
- return Promise.resolve(newContext.internal.invoke(agent, msg, newContext, options)).then(async (response) => {
89
+ return Promise.resolve(newContext.internal.invoke(agent, message, newContext, options)).then(async (response) => {
91
90
  if (!options?.streaming) {
92
- const { __activeAgent__: activeAgent, ...output } = await (0, stream_utils_js_1.agentResponseStreamToObject)(response);
91
+ let { __activeAgent__: activeAgent, ...output } = await (0, stream_utils_js_1.agentResponseStreamToObject)(response);
92
+ output = await this.onInvocationResult(output, options);
93
93
  if (options?.returnActiveAgent) {
94
94
  return [output, activeAgent];
95
95
  }
96
96
  return output;
97
97
  }
98
98
  const activeAgentPromise = (0, promise_js_1.promiseWithResolvers)();
99
- const stream = (0, stream_utils_js_1.onAgentResponseStreamEnd)((0, stream_utils_js_1.asyncGeneratorToReadableStream)(response), async ({ __activeAgent__: activeAgent }) => {
100
- activeAgentPromise.resolve(activeAgent);
101
- }, {
102
- processChunk(chunk) {
103
- if (chunk.delta.json) {
99
+ const stream = (0, stream_utils_js_1.onAgentResponseStreamEnd)((0, stream_utils_js_1.asyncGeneratorToReadableStream)(response), {
100
+ onChunk(chunk) {
101
+ if ((0, agent_js_1.isAgentResponseDelta)(chunk) && chunk.delta.json) {
104
102
  return {
105
103
  ...chunk,
106
104
  delta: {
107
105
  ...chunk.delta,
108
- json: (0, type_utils_js_1.omitBy)(chunk.delta.json, (_, k) => k === "__activeAgent__"),
106
+ json: (0, type_utils_js_1.omit)(chunk.delta.json, "__activeAgent__"),
109
107
  },
110
108
  };
111
109
  }
112
- return chunk;
110
+ },
111
+ onResult: async (output) => {
112
+ activeAgentPromise.resolve(output.__activeAgent__);
113
+ return await this.onInvocationResult(output, options);
113
114
  },
114
115
  });
116
+ const finalStream = !options.returnProgressChunks
117
+ ? stream
118
+ : (0, stream_utils_js_1.mergeReadableStreams)(stream, new event_stream_js_1.AgentResponseProgressStream(newContext));
115
119
  if (options.returnActiveAgent) {
116
- return [stream, activeAgentPromise.promise];
120
+ return [finalStream, activeAgentPromise.promise];
117
121
  }
118
- return stream;
122
+ return finalStream;
119
123
  });
120
124
  });
125
+ async onInvocationResult(output, options) {
126
+ if (!options?.returnMetadata) {
127
+ return output;
128
+ }
129
+ return {
130
+ ...output,
131
+ $meta: {
132
+ ...output.$meta,
133
+ usage: this.usage,
134
+ },
135
+ };
136
+ }
121
137
  publish = ((topic, payload, options) => {
122
138
  if (options?.userContext) {
123
139
  Object.assign(this.userContext, options.userContext);
@@ -171,7 +187,6 @@ class AIGNEContextShared {
171
187
  this.memories = overrides?.memories ?? [];
172
188
  }
173
189
  messageQueue;
174
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
175
190
  events = new strict_event_emitter_1.Emitter();
176
191
  get model() {
177
192
  return this.parent?.model;
@@ -205,44 +220,54 @@ class AIGNEContextShared {
205
220
  return withAbortSignal(this.abortController.signal, new Error("AIGNEContext is timeout"), () => this.invokeAgent(agent, input, context, options));
206
221
  }
207
222
  async *invokeAgent(agent, input, context, options) {
208
- let activeAgent = agent;
209
- for (;;) {
210
- const result = {};
211
- if (options?.sourceAgent && activeAgent !== options.sourceAgent) {
212
- options.sourceAgent.hooks.onHandoff?.({
213
- context,
214
- source: options.sourceAgent,
215
- target: activeAgent,
216
- input,
217
- });
218
- }
219
- const stream = await activeAgent.invoke(input, { ...options, context, streaming: true });
220
- for await (const value of stream) {
221
- if (value.delta.json) {
222
- value.delta.json = omitExistsProperties(result, value.delta.json);
223
- Object.assign(result, value.delta.json);
223
+ const startedAt = Date.now();
224
+ try {
225
+ let activeAgent = agent;
226
+ for (;;) {
227
+ const result = {};
228
+ if (options?.sourceAgent && activeAgent !== options.sourceAgent) {
229
+ options.sourceAgent.hooks.onHandoff?.({
230
+ context,
231
+ source: options.sourceAgent,
232
+ target: activeAgent,
233
+ input,
234
+ });
224
235
  }
225
- delete value.delta.json?.[types_js_1.transferAgentOutputKey];
226
- if ((0, agent_js_1.isEmptyChunk)(value))
227
- continue;
228
- yield value;
229
- }
230
- if (!options?.disableTransfer) {
231
- const transferToAgent = (0, types_js_1.isTransferAgentOutput)(result)
232
- ? result[types_js_1.transferAgentOutputKey].agent
233
- : undefined;
234
- if (transferToAgent) {
235
- activeAgent = transferToAgent;
236
- continue;
236
+ const stream = await activeAgent.invoke(input, { ...options, context, streaming: true });
237
+ for await (const value of stream) {
238
+ if ((0, agent_js_1.isAgentResponseDelta)(value)) {
239
+ if (value.delta.json) {
240
+ value.delta.json = omitExistsProperties(result, value.delta.json);
241
+ Object.assign(result, value.delta.json);
242
+ }
243
+ delete value.delta.json?.[types_js_1.transferAgentOutputKey];
244
+ }
245
+ if ((0, agent_js_1.isEmptyChunk)(value))
246
+ continue;
247
+ yield value;
248
+ }
249
+ if (!options?.disableTransfer) {
250
+ const transferToAgent = (0, types_js_1.isTransferAgentOutput)(result)
251
+ ? result[types_js_1.transferAgentOutputKey].agent
252
+ : undefined;
253
+ if (transferToAgent) {
254
+ activeAgent = transferToAgent;
255
+ continue;
256
+ }
237
257
  }
258
+ break;
238
259
  }
239
- break;
260
+ yield {
261
+ delta: {
262
+ json: { __activeAgent__: activeAgent },
263
+ },
264
+ };
265
+ }
266
+ finally {
267
+ const endedAt = Date.now();
268
+ const duration = endedAt - startedAt;
269
+ this.usage.duration += duration;
240
270
  }
241
- yield {
242
- delta: {
243
- json: { __activeAgent__: activeAgent },
244
- },
245
- };
246
271
  }
247
272
  }
248
273
  function omitExistsProperties(result, { ...delta }) {
@@ -21,7 +21,7 @@ export interface MessagePayload {
21
21
  /**
22
22
  * @hidden
23
23
  */
24
- export declare function toMessagePayload(payload: Omit<MessagePayload, "context"> | string | Message, options?: Partial<Pick<MessagePayload, "role" | "source">>): Omit<MessagePayload, "context">;
24
+ export declare function toMessagePayload(payload: Omit<MessagePayload, "context"> | Message, options?: Partial<Pick<MessagePayload, "role" | "source">>): Omit<MessagePayload, "context">;
25
25
  /**
26
26
  * @hidden
27
27
  */
@@ -4,7 +4,6 @@ exports.MessageQueue = exports.UserOutputTopic = exports.UserInputTopic = void 0
4
4
  exports.toMessagePayload = toMessagePayload;
5
5
  const strict_event_emitter_1 = require("strict-event-emitter");
6
6
  const zod_1 = require("zod");
7
- const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
8
7
  const type_utils_js_1 = require("../utils/type-utils.js");
9
8
  /**
10
9
  * @hidden
@@ -28,12 +27,12 @@ function isMessagePayload(payload) {
28
27
  */
29
28
  function toMessagePayload(payload, options) {
30
29
  if (isMessagePayload(payload)) {
31
- return { ...payload, message: (0, prompt_builder_js_1.createMessage)(payload.message), ...options };
30
+ return { ...payload, ...options };
32
31
  }
33
32
  return {
34
33
  role: options?.role || "user",
35
34
  source: options?.source,
36
- message: (0, prompt_builder_js_1.createMessage)(payload),
35
+ message: payload,
37
36
  };
38
37
  }
39
38
  /**
@@ -5,6 +5,7 @@ export interface ContextUsage {
5
5
  inputTokens: number;
6
6
  outputTokens: number;
7
7
  agentCalls: number;
8
+ duration: number;
8
9
  }
9
10
  /**
10
11
  * @hidden
@@ -9,5 +9,6 @@ function newEmptyContextUsage() {
9
9
  inputTokens: 0,
10
10
  outputTokens: 0,
11
11
  agentCalls: 0,
12
+ duration: 0,
12
13
  };
13
14
  }
@@ -5,11 +5,11 @@ export declare function loadAgentFromYamlFile(path: string): Promise<{
5
5
  name: string;
6
6
  description?: string | undefined;
7
7
  skills?: string[] | undefined;
8
- instructions?: string | undefined;
9
8
  memory?: true | {
10
9
  provider: string;
11
10
  subscribeTopic?: string[] | undefined;
12
11
  } | undefined;
12
+ instructions?: string | undefined;
13
13
  inputSchema?: ZodObject<Record<string, ZodType<any, z.ZodTypeDef, any>>, z.UnknownKeysParam, z.ZodTypeAny, {
14
14
  [x: string]: any;
15
15
  }, {
@@ -20,6 +20,7 @@ export declare function loadAgentFromYamlFile(path: string): Promise<{
20
20
  }, {
21
21
  [x: string]: any;
22
22
  }> | undefined;
23
+ inputKey?: string | undefined;
23
24
  outputKey?: string | undefined;
24
25
  toolChoice?: AIAgentToolChoice | undefined;
25
26
  } | {
@@ -21,6 +21,10 @@ const agentFileSchema = zod_1.z.discriminatedUnion("type", [
21
21
  .string()
22
22
  .nullish()
23
23
  .transform((v) => v ?? undefined),
24
+ input_key: zod_1.z
25
+ .string()
26
+ .nullish()
27
+ .transform((v) => v ?? undefined),
24
28
  input_schema: schema_js_1.inputOutputSchema
25
29
  .nullish()
26
30
  .transform((v) => (v ? (0, json_schema_to_zod_1.jsonSchemaToZod)(v) : undefined)),
@@ -3,33 +3,19 @@ import { Agent, type AgentInvokeOptions, type Message } from "../agents/agent.js
3
3
  import type { AIAgent } from "../agents/ai-agent.js";
4
4
  import type { ChatModel, ChatModelInput } from "../agents/chat-model.js";
5
5
  import { ChatMessagesTemplate } from "./template.js";
6
- export declare const MESSAGE_KEY = "$message";
7
- export declare function createMessage<V extends Message>(message: string, variables?: V): {
8
- [MESSAGE_KEY]: string;
9
- } & typeof variables;
10
- export declare function createMessage<I extends Message, V extends Message>(message: I, variables?: V): I & typeof variables;
11
- export declare function createMessage<I extends Message, V extends Message>(message: string | I, variables?: V): ({
12
- [MESSAGE_KEY]: string;
13
- } | I) & typeof variables;
14
- export declare function getMessage(input: Message): string | undefined;
15
6
  export interface PromptBuilderOptions {
16
7
  instructions?: string | ChatMessagesTemplate;
17
8
  }
18
9
  export interface PromptBuildOptions extends Pick<AgentInvokeOptions, "context"> {
19
- agent?: AIAgent;
10
+ agent?: AIAgent<any, any, any>;
20
11
  input?: Message;
21
12
  model?: ChatModel;
22
13
  outputSchema?: Agent["outputSchema"];
23
14
  }
24
15
  export declare class PromptBuilder {
25
- static from(instructions: string): PromptBuilder;
26
- static from(instructions: GetPromptResult): PromptBuilder;
27
- static from(instructions: {
28
- path: string;
29
- }): Promise<PromptBuilder>;
30
16
  static from(instructions: string | {
31
17
  path: string;
32
- } | GetPromptResult): PromptBuilder | Promise<PromptBuilder>;
18
+ } | GetPromptResult): PromptBuilder;
33
19
  private static fromFile;
34
20
  private static fromMCPPromptResult;
35
21
  constructor(options?: PromptBuilderOptions);
@@ -1,8 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PromptBuilder = exports.MESSAGE_KEY = void 0;
4
- exports.createMessage = createMessage;
5
- exports.getMessage = getMessage;
3
+ exports.PromptBuilder = void 0;
6
4
  const index_js_1 = require("@aigne/platform-helpers/nodejs/index.js");
7
5
  const yaml_1 = require("yaml");
8
6
  const zod_1 = require("zod");
@@ -11,20 +9,6 @@ const json_schema_js_1 = require("../utils/json-schema.js");
11
9
  const type_utils_js_1 = require("../utils/type-utils.js");
12
10
  const memory_message_template_js_1 = require("./prompts/memory-message-template.js");
13
11
  const template_js_1 = require("./template.js");
14
- exports.MESSAGE_KEY = "$message";
15
- function createMessage(message, variables) {
16
- return (typeof message === "string"
17
- ? { [exports.MESSAGE_KEY]: message, ...variables }
18
- : { ...message, ...variables });
19
- }
20
- function getMessage(input) {
21
- const userInputMessage = input[exports.MESSAGE_KEY];
22
- if (typeof userInputMessage === "string")
23
- return userInputMessage;
24
- if (!(0, type_utils_js_1.isNil)(userInputMessage))
25
- return JSON.stringify(userInputMessage);
26
- return undefined;
27
- }
28
12
  class PromptBuilder {
29
13
  static from(instructions) {
30
14
  if (typeof instructions === "string")
@@ -35,8 +19,8 @@ class PromptBuilder {
35
19
  return PromptBuilder.fromFile(instructions.path);
36
20
  throw new Error(`Invalid instructions ${instructions}`);
37
21
  }
38
- static async fromFile(path) {
39
- const text = await index_js_1.nodejs.fs.readFile(path, "utf-8");
22
+ static fromFile(path) {
23
+ const text = index_js_1.nodejs.fsSync.readFileSync(path, "utf-8");
40
24
  return PromptBuilder.from(text);
41
25
  }
42
26
  static fromMCPPromptResult(result) {
@@ -80,22 +64,25 @@ class PromptBuilder {
80
64
  }
81
65
  async buildMessages(options) {
82
66
  const { input } = options;
67
+ const inputKey = options.agent?.inputKey;
68
+ const message = inputKey && typeof input?.[inputKey] === "string" ? input[inputKey] : undefined;
83
69
  const messages = (typeof this.instructions === "string"
84
70
  ? template_js_1.ChatMessagesTemplate.from([template_js_1.SystemMessageTemplate.from(this.instructions)])
85
71
  : this.instructions)?.format(options.input) ?? [];
86
72
  const memories = [];
87
- if (options.agent) {
88
- memories.push(...(await options.agent.retrieveMemories({ search: options.input }, options)));
73
+ if (options.agent?.inputKey) {
74
+ memories.push(...(await options.agent.retrieveMemories({ search: message }, options)));
89
75
  }
90
76
  if (options.context.memories?.length) {
91
77
  memories.push(...options.context.memories);
92
78
  }
93
79
  if (memories.length)
94
80
  messages.push(...this.convertMemoriesToMessages(memories, options));
95
- const content = input && getMessage(input);
96
- // add user input if it's not the same as the last message
97
- if (content && messages.at(-1)?.content !== content) {
98
- messages.push({ role: "user", content });
81
+ if (message) {
82
+ messages.push({
83
+ role: "user",
84
+ content: message,
85
+ });
99
86
  }
100
87
  return messages;
101
88
  }
@@ -1,4 +1,5 @@
1
- import type { AgentResponseChunk, AgentResponseStream, Message } from "../agents/agent.js";
1
+ import { type AgentResponseChunk, type AgentResponseProgress, type AgentResponseStream, type Message } from "../agents/agent.js";
2
+ import type { Context } from "../aigne/context.js";
2
3
  export declare class EventStreamParser<T> extends TransformStream<string, T | Error> {
3
4
  constructor();
4
5
  }
@@ -9,3 +10,6 @@ export declare class AgentResponseStreamParser<O extends Message> extends Transf
9
10
  export declare class AgentResponseStreamSSE<O extends Message> extends ReadableStream<string> {
10
11
  constructor(stream: AgentResponseStream<O>);
11
12
  }
13
+ export declare class AgentResponseProgressStream extends ReadableStream<AgentResponseProgress> {
14
+ constructor(context: Context);
15
+ }
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentResponseStreamSSE = exports.AgentResponseStreamParser = exports.EventStreamParser = void 0;
3
+ exports.AgentResponseProgressStream = exports.AgentResponseStreamSSE = exports.AgentResponseStreamParser = exports.EventStreamParser = void 0;
4
4
  const eventsource_parser_1 = require("eventsource-parser");
5
5
  const immer_1 = require("immer");
6
+ const agent_js_1 = require("../agents/agent.js");
6
7
  const type_utils_js_1 = require("./type-utils.js");
7
8
  class EventStreamParser extends TransformStream {
8
9
  constructor() {
@@ -15,11 +16,16 @@ class EventStreamParser extends TransformStream {
15
16
  controller.enqueue(new Error(`Parse response chunk json error: ${e.message} ${event.data}`));
16
17
  });
17
18
  if (json) {
18
- if (event.event === "error") {
19
- controller.enqueue(new Error(json.message));
20
- }
21
- else {
22
- controller.enqueue(json);
19
+ switch (event.event) {
20
+ case "error":
21
+ controller.enqueue(new Error(json.message));
22
+ break;
23
+ default: {
24
+ if (!event.event)
25
+ controller.enqueue(json);
26
+ else
27
+ console.warn(`Unknown event type: ${event.event}`, event.data);
28
+ }
23
29
  }
24
30
  }
25
31
  },
@@ -42,25 +48,35 @@ class AgentResponseStreamParser extends TransformStream {
42
48
  controller.terminate();
43
49
  return;
44
50
  }
45
- this.json = (0, immer_1.produce)(this.json, (draft) => {
46
- if (chunk.delta.json)
47
- Object.assign(draft, chunk.delta.json);
48
- if (chunk.delta.text) {
49
- for (const [key, text] of Object.entries(chunk.delta.text)) {
50
- const original = draft[key];
51
- const t = (original || "") + (text || "");
52
- if (t)
53
- Object.assign(draft, { [key]: t });
51
+ if ((0, agent_js_1.isAgentResponseDelta)(chunk)) {
52
+ this.json = (0, immer_1.produce)(this.json, (draft) => {
53
+ if (chunk.delta.json)
54
+ Object.assign(draft, chunk.delta.json);
55
+ if (chunk.delta.text) {
56
+ for (const [key, text] of Object.entries(chunk.delta.text)) {
57
+ const original = draft[key];
58
+ const t = (original || "") + (text || "");
59
+ if (t)
60
+ Object.assign(draft, { [key]: t });
61
+ }
54
62
  }
63
+ });
64
+ controller.enqueue({
65
+ ...chunk,
66
+ delta: {
67
+ ...chunk.delta,
68
+ json: this.json,
69
+ },
70
+ });
71
+ }
72
+ else if ((0, agent_js_1.isAgentResponseProgress)(chunk)) {
73
+ if (chunk.progress.event === "agentFailed") {
74
+ const { name, message } = chunk.progress.error;
75
+ chunk.progress.error = new Error(message);
76
+ chunk.progress.error.name = name;
55
77
  }
56
- });
57
- controller.enqueue({
58
- ...chunk,
59
- delta: {
60
- ...chunk.delta,
61
- json: this.json,
62
- },
63
- });
78
+ controller.enqueue(chunk);
79
+ }
64
80
  },
65
81
  });
66
82
  }
@@ -78,6 +94,14 @@ class AgentResponseStreamSSE extends ReadableStream {
78
94
  controller.close();
79
95
  return;
80
96
  }
97
+ if ((0, agent_js_1.isAgentResponseProgress)(value)) {
98
+ if (value.progress.event === "agentFailed") {
99
+ value.progress.error = {
100
+ name: value.progress.error.name,
101
+ message: value.progress.error.message,
102
+ };
103
+ }
104
+ }
81
105
  controller.enqueue(`data: ${JSON.stringify(value)}\n\n`);
82
106
  }
83
107
  catch (error) {
@@ -89,3 +113,44 @@ class AgentResponseStreamSSE extends ReadableStream {
89
113
  }
90
114
  }
91
115
  exports.AgentResponseStreamSSE = AgentResponseStreamSSE;
116
+ class AgentResponseProgressStream extends ReadableStream {
117
+ constructor(context) {
118
+ super({
119
+ async start(controller) {
120
+ const writeEvent = (eventName, event) => {
121
+ const progress = {
122
+ ...event,
123
+ event: eventName,
124
+ agent: { name: event.agent.name },
125
+ };
126
+ controller.enqueue({ progress });
127
+ };
128
+ const close = () => {
129
+ context.off("agentStarted", onAgentStarted);
130
+ context.off("agentSucceed", onAgentSucceed);
131
+ context.off("agentFailed", onAgentFailed);
132
+ controller.close();
133
+ };
134
+ const onAgentStarted = (event) => {
135
+ writeEvent("agentStarted", event);
136
+ };
137
+ const onAgentSucceed = (event) => {
138
+ writeEvent("agentSucceed", event);
139
+ if (event.contextId === context.id) {
140
+ close();
141
+ }
142
+ };
143
+ const onAgentFailed = (event) => {
144
+ writeEvent("agentFailed", event);
145
+ if (event.contextId === context.id) {
146
+ close();
147
+ }
148
+ };
149
+ context.on("agentStarted", onAgentStarted);
150
+ context.on("agentSucceed", onAgentSucceed);
151
+ context.on("agentFailed", onAgentFailed);
152
+ },
153
+ });
154
+ }
155
+ }
156
+ exports.AgentResponseProgressStream = AgentResponseProgressStream;
@@ -1,15 +1,15 @@
1
1
  import { type AgentProcessAsyncGenerator, type AgentResponseChunk, type AgentResponseStream, type Message } from "../agents/agent.js";
2
- import type { MESSAGE_KEY } from "../prompt/prompt-builder.js";
3
2
  import { type PromiseOrValue } from "./type-utils.js";
4
3
  import "./stream-polyfill.js";
5
4
  export declare function objectToAgentResponseStream<T extends Message>(json: T): AgentResponseStream<T>;
6
5
  export declare function mergeAgentResponseChunk<T extends Message>(output: T, chunk: AgentResponseChunk<T>): T;
7
6
  export declare function agentResponseStreamToObject<T extends Message>(stream: AgentResponseStream<T> | AgentProcessAsyncGenerator<T>): Promise<T>;
8
7
  export declare function asyncGeneratorToReadableStream<T extends Message>(generator: AgentProcessAsyncGenerator<T>): AgentResponseStream<T>;
9
- export declare function onAgentResponseStreamEnd<T extends Message>(stream: AgentResponseStream<T>, callback: (result: T) => PromiseOrValue<Partial<T> | void>, options?: {
10
- errorCallback?: (error: Error) => PromiseOrValue<Error>;
11
- processChunk?: (chunk: AgentResponseChunk<T>) => AgentResponseChunk<T>;
12
- }): ReadableStream<any>;
8
+ export declare function onAgentResponseStreamEnd<T extends Message>(stream: AgentResponseStream<T>, options?: {
9
+ onChunk?: (chunk: AgentResponseChunk<T>) => PromiseOrValue<AgentResponseChunk<T> | undefined | void>;
10
+ onResult?: (result: T) => PromiseOrValue<Partial<T> | undefined | void>;
11
+ onError?: (error: Error) => PromiseOrValue<Error>;
12
+ }): AgentResponseStream<T>;
13
13
  export declare function isAsyncGenerator<T extends AsyncGenerator>(value: AsyncGenerator | unknown): value is T;
14
14
  export declare function arrayToAgentProcessAsyncGenerator<T extends Message>(chunks: (AgentResponseChunk<T> | Error)[], result?: Partial<T>): AgentProcessAsyncGenerator<T>;
15
15
  export declare function arrayToReadableStream<T>(chunks: (T | Error)[]): ReadableStream<T>;
@@ -17,8 +17,10 @@ export declare function readableStreamToArray<T>(stream: ReadableStream<T>, opti
17
17
  catchError: true;
18
18
  }): Promise<(T | Error)[]>;
19
19
  export declare function readableStreamToArray<T>(stream: ReadableStream<T>, options?: {
20
- catchError?: false;
20
+ catchError?: boolean;
21
21
  }): Promise<T[]>;
22
- export declare function stringToAgentResponseStream(str: string, key?: "text" | typeof MESSAGE_KEY | string): AgentResponseStream<Message>;
22
+ export declare function stringToAgentResponseStream(str: string, key?: "text" | string): AgentResponseStream<Message>;
23
23
  export declare function toReadableStream(stream: NodeJS.ReadStream): ReadableStream<Uint8Array<ArrayBufferLike>>;
24
24
  export declare function readAllString(stream: NodeJS.ReadStream | ReadableStream): Promise<string>;
25
+ export declare function mergeReadableStreams<T1, T2>(s1: ReadableStream<T1>, s2: ReadableStream<T2>): ReadableStream<T1 | T2>;
26
+ export declare function mergeReadableStreams(...streams: ReadableStream<any>[]): ReadableStream<any>;