@aigne/core 1.15.0 → 1.16.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 (141) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +9 -7
  3. package/README.zh.md +9 -7
  4. package/lib/cjs/agents/agent.d.ts +129 -6
  5. package/lib/cjs/agents/agent.js +112 -20
  6. package/lib/cjs/agents/ai-agent.d.ts +3 -2
  7. package/lib/cjs/agents/ai-agent.js +10 -6
  8. package/lib/{esm/models → cjs/agents}/chat-model.d.ts +24 -13
  9. package/lib/cjs/{models → agents}/chat-model.js +48 -7
  10. package/lib/cjs/agents/guide-rail-agent.d.ts +62 -0
  11. package/lib/cjs/agents/guide-rail-agent.js +14 -0
  12. package/lib/cjs/agents/mcp-agent.js +9 -9
  13. package/lib/cjs/aigne/aigne.d.ts +3 -2
  14. package/lib/cjs/aigne/aigne.js +2 -2
  15. package/lib/cjs/aigne/context.d.ts +2 -1
  16. package/lib/cjs/aigne/context.js +7 -0
  17. package/lib/cjs/index.d.ts +1 -1
  18. package/lib/cjs/index.js +1 -1
  19. package/lib/cjs/loader/agent-yaml.d.ts +1 -1
  20. package/lib/cjs/loader/index.d.ts +18 -11
  21. package/lib/cjs/loader/index.js +8 -27
  22. package/lib/cjs/memory/retriever.d.ts +2 -2
  23. package/lib/cjs/prompt/prompt-builder.d.ts +3 -3
  24. package/lib/cjs/prompt/template.d.ts +3 -3
  25. package/lib/cjs/utils/json-schema.js +1 -1
  26. package/lib/cjs/utils/logger.d.ts +33 -8
  27. package/lib/cjs/utils/logger.js +63 -5
  28. package/lib/cjs/utils/model-utils.d.ts +1 -1
  29. package/lib/cjs/utils/stream-utils.d.ts +3 -1
  30. package/lib/cjs/utils/stream-utils.js +31 -1
  31. package/lib/cjs/utils/type-utils.d.ts +5 -0
  32. package/lib/dts/agents/agent.d.ts +129 -6
  33. package/lib/dts/agents/ai-agent.d.ts +3 -2
  34. package/lib/{cjs/models → dts/agents}/chat-model.d.ts +24 -13
  35. package/lib/dts/agents/guide-rail-agent.d.ts +62 -0
  36. package/lib/dts/aigne/aigne.d.ts +3 -2
  37. package/lib/dts/aigne/context.d.ts +2 -1
  38. package/lib/dts/index.d.ts +1 -1
  39. package/lib/dts/loader/agent-yaml.d.ts +1 -1
  40. package/lib/dts/loader/index.d.ts +18 -11
  41. package/lib/dts/memory/retriever.d.ts +2 -2
  42. package/lib/dts/prompt/prompt-builder.d.ts +3 -3
  43. package/lib/dts/prompt/template.d.ts +3 -3
  44. package/lib/dts/utils/logger.d.ts +33 -8
  45. package/lib/dts/utils/model-utils.d.ts +1 -1
  46. package/lib/dts/utils/stream-utils.d.ts +3 -1
  47. package/lib/dts/utils/type-utils.d.ts +5 -0
  48. package/lib/esm/agents/agent.d.ts +129 -6
  49. package/lib/esm/agents/agent.js +112 -20
  50. package/lib/esm/agents/ai-agent.d.ts +3 -2
  51. package/lib/esm/agents/ai-agent.js +10 -6
  52. package/lib/{dts/models → esm/agents}/chat-model.d.ts +24 -13
  53. package/lib/esm/{models → agents}/chat-model.js +48 -7
  54. package/lib/esm/agents/guide-rail-agent.d.ts +62 -0
  55. package/lib/esm/agents/guide-rail-agent.js +11 -0
  56. package/lib/esm/agents/mcp-agent.js +9 -9
  57. package/lib/esm/aigne/aigne.d.ts +3 -2
  58. package/lib/esm/aigne/aigne.js +2 -2
  59. package/lib/esm/aigne/context.d.ts +2 -1
  60. package/lib/esm/aigne/context.js +7 -0
  61. package/lib/esm/index.d.ts +1 -1
  62. package/lib/esm/index.js +1 -1
  63. package/lib/esm/loader/agent-yaml.d.ts +1 -1
  64. package/lib/esm/loader/index.d.ts +18 -11
  65. package/lib/esm/loader/index.js +8 -27
  66. package/lib/esm/memory/retriever.d.ts +2 -2
  67. package/lib/esm/prompt/prompt-builder.d.ts +3 -3
  68. package/lib/esm/prompt/template.d.ts +3 -3
  69. package/lib/esm/utils/json-schema.js +1 -1
  70. package/lib/esm/utils/logger.d.ts +33 -8
  71. package/lib/esm/utils/logger.js +61 -4
  72. package/lib/esm/utils/model-utils.d.ts +1 -1
  73. package/lib/esm/utils/stream-utils.d.ts +3 -1
  74. package/lib/esm/utils/stream-utils.js +29 -1
  75. package/lib/esm/utils/type-utils.d.ts +5 -0
  76. package/package.json +1 -20
  77. package/lib/cjs/client/client.d.ts +0 -97
  78. package/lib/cjs/client/client.js +0 -87
  79. package/lib/cjs/client/index.d.ts +0 -1
  80. package/lib/cjs/client/index.js +0 -17
  81. package/lib/cjs/models/bedrock-chat-model.d.ts +0 -79
  82. package/lib/cjs/models/bedrock-chat-model.js +0 -303
  83. package/lib/cjs/models/claude-chat-model.d.ts +0 -114
  84. package/lib/cjs/models/claude-chat-model.js +0 -317
  85. package/lib/cjs/models/deepseek-chat-model.d.ts +0 -23
  86. package/lib/cjs/models/deepseek-chat-model.js +0 -35
  87. package/lib/cjs/models/gemini-chat-model.d.ts +0 -23
  88. package/lib/cjs/models/gemini-chat-model.js +0 -35
  89. package/lib/cjs/models/ollama-chat-model.d.ts +0 -22
  90. package/lib/cjs/models/ollama-chat-model.js +0 -34
  91. package/lib/cjs/models/open-router-chat-model.d.ts +0 -22
  92. package/lib/cjs/models/open-router-chat-model.js +0 -34
  93. package/lib/cjs/models/openai-chat-model.d.ts +0 -166
  94. package/lib/cjs/models/openai-chat-model.js +0 -415
  95. package/lib/cjs/models/xai-chat-model.d.ts +0 -21
  96. package/lib/cjs/models/xai-chat-model.js +0 -33
  97. package/lib/cjs/server/error.d.ts +0 -15
  98. package/lib/cjs/server/error.js +0 -22
  99. package/lib/cjs/server/index.d.ts +0 -2
  100. package/lib/cjs/server/index.js +0 -18
  101. package/lib/cjs/server/server.d.ts +0 -135
  102. package/lib/cjs/server/server.js +0 -187
  103. package/lib/dts/client/client.d.ts +0 -97
  104. package/lib/dts/client/index.d.ts +0 -1
  105. package/lib/dts/models/bedrock-chat-model.d.ts +0 -79
  106. package/lib/dts/models/claude-chat-model.d.ts +0 -114
  107. package/lib/dts/models/deepseek-chat-model.d.ts +0 -23
  108. package/lib/dts/models/gemini-chat-model.d.ts +0 -23
  109. package/lib/dts/models/ollama-chat-model.d.ts +0 -22
  110. package/lib/dts/models/open-router-chat-model.d.ts +0 -22
  111. package/lib/dts/models/openai-chat-model.d.ts +0 -166
  112. package/lib/dts/models/xai-chat-model.d.ts +0 -21
  113. package/lib/dts/server/error.d.ts +0 -15
  114. package/lib/dts/server/index.d.ts +0 -2
  115. package/lib/dts/server/server.d.ts +0 -135
  116. package/lib/esm/client/client.d.ts +0 -97
  117. package/lib/esm/client/client.js +0 -83
  118. package/lib/esm/client/index.d.ts +0 -1
  119. package/lib/esm/client/index.js +0 -1
  120. package/lib/esm/models/bedrock-chat-model.d.ts +0 -79
  121. package/lib/esm/models/bedrock-chat-model.js +0 -298
  122. package/lib/esm/models/claude-chat-model.d.ts +0 -114
  123. package/lib/esm/models/claude-chat-model.js +0 -310
  124. package/lib/esm/models/deepseek-chat-model.d.ts +0 -23
  125. package/lib/esm/models/deepseek-chat-model.js +0 -31
  126. package/lib/esm/models/gemini-chat-model.d.ts +0 -23
  127. package/lib/esm/models/gemini-chat-model.js +0 -31
  128. package/lib/esm/models/ollama-chat-model.d.ts +0 -22
  129. package/lib/esm/models/ollama-chat-model.js +0 -30
  130. package/lib/esm/models/open-router-chat-model.d.ts +0 -22
  131. package/lib/esm/models/open-router-chat-model.js +0 -30
  132. package/lib/esm/models/openai-chat-model.d.ts +0 -166
  133. package/lib/esm/models/openai-chat-model.js +0 -405
  134. package/lib/esm/models/xai-chat-model.d.ts +0 -21
  135. package/lib/esm/models/xai-chat-model.js +0 -29
  136. package/lib/esm/server/error.d.ts +0 -15
  137. package/lib/esm/server/error.js +0 -18
  138. package/lib/esm/server/index.d.ts +0 -2
  139. package/lib/esm/server/index.js +0 -2
  140. package/lib/esm/server/server.d.ts +0 -135
  141. package/lib/esm/server/server.js +0 -180
@@ -5,14 +5,6 @@ import { z } from "zod";
5
5
  import { FunctionAgent } from "../agents/agent.js";
6
6
  import { AIAgent } from "../agents/ai-agent.js";
7
7
  import { MCPAgent } from "../agents/mcp-agent.js";
8
- import { BedrockChatModel } from "../models/bedrock-chat-model.js";
9
- import { ClaudeChatModel } from "../models/claude-chat-model.js";
10
- import { DeepSeekChatModel } from "../models/deepseek-chat-model.js";
11
- import { GeminiChatModel } from "../models/gemini-chat-model.js";
12
- import { OllamaChatModel } from "../models/ollama-chat-model.js";
13
- import { OpenRouterChatModel } from "../models/open-router-chat-model.js";
14
- import { OpenAIChatModel } from "../models/openai-chat-model.js";
15
- import { XAIChatModel } from "../models/xai-chat-model.js";
16
8
  import { tryOrThrow } from "../utils/type-utils.js";
17
9
  import { loadAgentFromJsFile } from "./agent-js.js";
18
10
  import { loadAgentFromYamlFile } from "./agent-yaml.js";
@@ -26,7 +18,7 @@ export async function load(options) {
26
18
  const skills = await Promise.all((aigne.skills ?? []).map((filename) => loadAgent(join(rootDir, filename))));
27
19
  return {
28
20
  ...aigne,
29
- model: await loadModel(aigne.chat_model),
21
+ model: await loadModel(options.models, aigne.chat_model),
30
22
  agents,
31
23
  skills,
32
24
  };
@@ -64,26 +56,15 @@ export async function loadAgent(path) {
64
56
  }
65
57
  const { MODEL_PROVIDER, MODEL_NAME } = process.env;
66
58
  const DEFAULT_MODEL_PROVIDER = "openai";
67
- const DEFAULT_MODEL_NAME = "gpt-4o-mini";
68
- export async function loadModel(model, modelOptions) {
59
+ export async function loadModel(models, model, modelOptions) {
69
60
  const params = {
70
- model: MODEL_NAME ?? model?.name ?? DEFAULT_MODEL_NAME,
61
+ model: MODEL_NAME ?? model?.name ?? undefined,
71
62
  temperature: model?.temperature ?? undefined,
72
- topP: model?.top_p ?? undefined,
73
- frequencyPenalty: model?.frequent_penalty ?? undefined,
74
- presencePenalty: model?.presence_penalty ?? undefined,
63
+ topP: model?.topP ?? undefined,
64
+ frequencyPenalty: model?.frequencyPenalty ?? undefined,
65
+ presencePenalty: model?.presencePenalty ?? undefined,
75
66
  };
76
- const availableModels = [
77
- OpenAIChatModel,
78
- ClaudeChatModel,
79
- XAIChatModel,
80
- GeminiChatModel,
81
- DeepSeekChatModel,
82
- OpenRouterChatModel,
83
- OllamaChatModel,
84
- BedrockChatModel,
85
- ];
86
- const M = availableModels.find((m) => m.name
67
+ const M = models.find((m) => m.name
87
68
  .toLowerCase()
88
69
  .includes((MODEL_PROVIDER ?? model?.provider ?? DEFAULT_MODEL_PROVIDER).toLowerCase()));
89
70
  if (!M)
@@ -101,7 +82,7 @@ const aigneFileSchema = z.object({
101
82
  name: z.string().nullish(),
102
83
  temperature: z.number().min(0).max(2).nullish(),
103
84
  top_p: z.number().min(0).nullish(),
104
- frequent_penalty: z.number().min(-2).max(2).nullish(),
85
+ frequency_penalty: z.number().min(-2).max(2).nullish(),
105
86
  presence_penalty: z.number().min(-2).max(2).nullish(),
106
87
  }),
107
88
  ])
@@ -39,11 +39,11 @@ export declare const memoryRetrieverInputSchema: z.ZodObject<{
39
39
  limit: z.ZodOptional<z.ZodNumber>;
40
40
  search: z.ZodOptional<z.ZodString>;
41
41
  }, "strip", z.ZodTypeAny, {
42
- limit?: number | undefined;
43
42
  search?: string | undefined;
44
- }, {
45
43
  limit?: number | undefined;
44
+ }, {
46
45
  search?: string | undefined;
46
+ limit?: number | undefined;
47
47
  }>;
48
48
  /**
49
49
  * @hidden
@@ -1,9 +1,9 @@
1
1
  import type { GetPromptResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { Agent, type Message } from "../agents/agent.js";
3
3
  import type { AIAgent } from "../agents/ai-agent.js";
4
+ import type { ChatModel, ChatModelInput } from "../agents/chat-model.js";
4
5
  import type { Context } from "../aigne/context.js";
5
6
  import type { MemoryAgent } from "../memory/memory.js";
6
- import type { ChatModel, ChatModelInput } from "../models/chat-model.js";
7
7
  import { ChatMessagesTemplate } from "./template.js";
8
8
  export declare const MESSAGE_KEY = "$message";
9
9
  export declare function createMessage<I extends Message>(message: string | I): I;
@@ -11,7 +11,7 @@ export declare function getMessage(input: Message): string | undefined;
11
11
  export interface PromptBuilderOptions {
12
12
  instructions?: string | ChatMessagesTemplate;
13
13
  }
14
- export interface PromptBuilderBuildOptions {
14
+ export interface PromptBuildOptions {
15
15
  memory?: MemoryAgent | MemoryAgent[];
16
16
  context: Context;
17
17
  agent?: AIAgent;
@@ -32,7 +32,7 @@ export declare class PromptBuilder {
32
32
  private static fromMCPPromptResult;
33
33
  constructor(options?: PromptBuilderOptions);
34
34
  instructions?: string | ChatMessagesTemplate;
35
- build(options: PromptBuilderBuildOptions): Promise<ChatModelInput & {
35
+ build(options: PromptBuildOptions): Promise<ChatModelInput & {
36
36
  toolAgents?: Agent[];
37
37
  }>;
38
38
  private buildMessages;
@@ -1,4 +1,4 @@
1
- import type { ChatModelInputMessage, ChatModelInputMessageContent, ChatModelOutputToolCall } from "../models/chat-model.js";
1
+ import type { ChatModelInputMessage, ChatModelInputMessageContent, ChatModelOutputToolCall } from "../agents/chat-model.js";
2
2
  export declare class PromptTemplate {
3
3
  template: string;
4
4
  static from(template: string): PromptTemplate;
@@ -24,7 +24,7 @@ export declare class AgentMessageTemplate extends ChatMessageTemplate {
24
24
  constructor(content?: ChatModelInputMessage["content"], toolCalls?: ChatModelOutputToolCall[] | undefined, name?: string);
25
25
  format(variables?: Record<string, unknown>): {
26
26
  toolCalls: ChatModelOutputToolCall[] | undefined;
27
- role: import("../models/chat-model.js").Role;
27
+ role: import("../agents/chat-model.js").Role;
28
28
  content?: ChatModelInputMessageContent;
29
29
  toolCallId?: string;
30
30
  name?: string;
@@ -36,7 +36,7 @@ export declare class ToolMessageTemplate extends ChatMessageTemplate {
36
36
  constructor(content: object | string, toolCallId: string, name?: string);
37
37
  format(variables?: Record<string, unknown>): {
38
38
  toolCallId: string;
39
- role: import("../models/chat-model.js").Role;
39
+ role: import("../agents/chat-model.js").Role;
40
40
  content?: ChatModelInputMessageContent;
41
41
  toolCalls?: {
42
42
  id: string;
@@ -23,7 +23,7 @@ export function parseJSON(json) {
23
23
  return JSON.parse(json);
24
24
  }
25
25
  catch (error) {
26
- logger.core("Failed to parse JSON", { json, error });
26
+ logger.error("Failed to parse JSON", { json, error });
27
27
  throw error;
28
28
  }
29
29
  }
@@ -1,8 +1,33 @@
1
- import debug from "debug";
2
- export declare const logger: debug.Debug & {
3
- debug: debug.Debug;
4
- default: debug.Debug;
5
- } & {
6
- core: debug.Debugger;
7
- mcp: debug.Debugger;
8
- };
1
+ export declare enum LogLevel {
2
+ ERROR = "error",
3
+ WARN = "warn",
4
+ INFO = "info",
5
+ DEBUG = "debug"
6
+ }
7
+ export declare class Logger {
8
+ constructor(options: {
9
+ level: LogLevel;
10
+ ns: string;
11
+ });
12
+ level: LogLevel;
13
+ private debugLogger;
14
+ private infoLogger;
15
+ private warnLogger;
16
+ private errorLogger;
17
+ logMessage: {
18
+ (...data: any[]): void;
19
+ (...data: any[]): void;
20
+ (message?: any, ...optionalParams: any[]): void;
21
+ };
22
+ logError: {
23
+ (...data: any[]): void;
24
+ (...data: any[]): void;
25
+ (message?: any, ...optionalParams: any[]): void;
26
+ };
27
+ debug(message: string, ...args: unknown[]): void;
28
+ info(message: string, ...args: unknown[]): void;
29
+ warn(message: string, ...args: unknown[]): void;
30
+ error(message: string, ...args: unknown[]): void;
31
+ enabled(level: LogLevel): boolean;
32
+ }
33
+ export declare const logger: Logger;
@@ -1,6 +1,63 @@
1
+ import { isatty } from "node:tty";
1
2
  import debug from "debug";
2
- const base = debug("aigne");
3
- export const logger = Object.assign(debug, {
4
- core: base.extend("core"),
5
- mcp: base.extend("mcp"),
3
+ export var LogLevel;
4
+ (function (LogLevel) {
5
+ LogLevel["ERROR"] = "error";
6
+ LogLevel["WARN"] = "warn";
7
+ LogLevel["INFO"] = "info";
8
+ LogLevel["DEBUG"] = "debug";
9
+ })(LogLevel || (LogLevel = {}));
10
+ const levels = Object.values(LogLevel);
11
+ export class Logger {
12
+ constructor(options) {
13
+ this.level = options.level;
14
+ this.debugLogger = debug(`${options.ns}:debug`);
15
+ this.infoLogger = debug(`${options.ns}:info`);
16
+ this.warnLogger = debug(`${options.ns}:warn`);
17
+ this.errorLogger = debug(`${options.ns}:error`);
18
+ for (const logger of [this.debugLogger, this.infoLogger, this.warnLogger]) {
19
+ // @ts-ignore
20
+ logger.useColors = isatty(process.stdout.fd);
21
+ logger.enabled = true;
22
+ logger.log = (...args) => this.logMessage(...args);
23
+ }
24
+ this.errorLogger.log = (...args) => this.logError(...args);
25
+ // @ts-ignore
26
+ this.errorLogger.useColors = isatty(process.stderr.fd);
27
+ this.errorLogger.enabled = true;
28
+ }
29
+ level;
30
+ debugLogger;
31
+ infoLogger;
32
+ warnLogger;
33
+ errorLogger;
34
+ logMessage = console.log;
35
+ logError = console.error;
36
+ debug(message, ...args) {
37
+ if (this.enabled(LogLevel.DEBUG)) {
38
+ this.debugLogger(message, ...args);
39
+ }
40
+ }
41
+ info(message, ...args) {
42
+ if (this.enabled(LogLevel.INFO)) {
43
+ this.infoLogger(message, ...args);
44
+ }
45
+ }
46
+ warn(message, ...args) {
47
+ if (this.enabled(LogLevel.WARN)) {
48
+ this.warnLogger(message, ...args);
49
+ }
50
+ }
51
+ error(message, ...args) {
52
+ if (this.enabled(LogLevel.ERROR)) {
53
+ this.errorLogger(message, ...args);
54
+ }
55
+ }
56
+ enabled(level) {
57
+ return levels.indexOf(this.level) >= levels.indexOf(level);
58
+ }
59
+ }
60
+ export const logger = new Logger({
61
+ ns: "aigne:core",
62
+ level: LogLevel.INFO,
6
63
  });
@@ -1,3 +1,3 @@
1
- import type { ChatModelOutputUsage } from "../models/chat-model.js";
1
+ import type { ChatModelOutputUsage } from "../agents/chat-model.js";
2
2
  import type { Nullish } from "./type-utils.js";
3
3
  export declare function mergeUsage(...usages: Nullish<ChatModelOutputUsage>[]): ChatModelOutputUsage;
@@ -6,7 +6,7 @@ export declare function mergeAgentResponseChunk<T extends Message>(output: T, ch
6
6
  export declare function agentResponseStreamToObject<T extends Message>(stream: AgentResponseStream<T> | AgentProcessAsyncGenerator<T>): Promise<T>;
7
7
  export declare function asyncGeneratorToReadableStream<T extends Message>(generator: AgentProcessAsyncGenerator<T>): AgentResponseStream<T>;
8
8
  export declare function onAgentResponseStreamEnd<T extends Message>(stream: AgentResponseStream<T>, callback: (result: T) => PromiseOrValue<Partial<T> | void>, options?: {
9
- errorCallback?: (error: Error) => Error;
9
+ errorCallback?: (error: Error) => PromiseOrValue<Error>;
10
10
  processChunk?: (chunk: AgentResponseChunk<T>) => AgentResponseChunk<T>;
11
11
  }): ReadableStream<any>;
12
12
  export declare function isAsyncGenerator<T extends AsyncGenerator>(value: AsyncGenerator | unknown): value is T;
@@ -19,3 +19,5 @@ export declare function readableStreamToArray<T>(stream: ReadableStream<T>, opti
19
19
  catchError?: false;
20
20
  }): Promise<T[]>;
21
21
  export declare function stringToAgentResponseStream(str: string, key?: "text" | typeof MESSAGE_KEY | string): AgentResponseStream<Message>;
22
+ export declare function toReadableStream(stream: NodeJS.ReadStream): ReadableStream<Uint8Array<ArrayBufferLike>>;
23
+ export declare function readAllString(stream: NodeJS.ReadStream | ReadableStream): Promise<string>;
@@ -98,7 +98,7 @@ export function onAgentResponseStreamEnd(stream, callback, options) {
98
98
  }
99
99
  }
100
100
  catch (error) {
101
- controller.error(options?.errorCallback?.(error) ?? error);
101
+ controller.error((await options?.errorCallback?.(error)) ?? error);
102
102
  }
103
103
  },
104
104
  });
@@ -151,3 +151,31 @@ export function stringToAgentResponseStream(str, key = "text") {
151
151
  const segments = segmenter.segment(str);
152
152
  return arrayToReadableStream(Array.from(segments).map((segment) => ({ delta: { text: { [key]: segment.segment } } })));
153
153
  }
154
+ export function toReadableStream(stream) {
155
+ return new ReadableStream({
156
+ start(controller) {
157
+ const onData = (chunk) => {
158
+ controller.enqueue(new Uint8Array(chunk));
159
+ };
160
+ const onEnd = () => {
161
+ cleanup();
162
+ controller.close();
163
+ };
164
+ const onError = (err) => {
165
+ cleanup();
166
+ controller.error(err);
167
+ };
168
+ function cleanup() {
169
+ stream.off("data", onData);
170
+ stream.off("end", onEnd);
171
+ stream.off("error", onError);
172
+ }
173
+ stream.on("data", onData);
174
+ stream.on("end", onEnd);
175
+ stream.on("error", onError);
176
+ },
177
+ });
178
+ }
179
+ export async function readAllString(stream) {
180
+ return (await readableStreamToArray((stream instanceof ReadableStream ? stream : toReadableStream(stream)).pipeThrough(new TextDecoderStream()))).join("");
181
+ }
@@ -2,6 +2,11 @@ import { type ZodType } from "zod";
2
2
  export type PromiseOrValue<T> = T | Promise<T>;
3
3
  export type Nullish<T> = T | null | undefined | void;
4
4
  export type OmitPropertiesFromArrayFirstElement<T extends unknown[], K extends string | number | symbol> = T extends [infer U, ...infer Rest] ? [Omit<U, K>, ...Rest] : never;
5
+ export type XOr<T, K extends keyof T, O extends keyof T> = (Omit<T, O> & {
6
+ [key in O]?: undefined;
7
+ }) | (Omit<T, K> & {
8
+ [key in K]?: undefined;
9
+ });
5
10
  export declare function isNil(value: unknown): value is null | undefined;
6
11
  export declare function isRecord<T>(value: unknown): value is Record<string, T>;
7
12
  export declare function isEmpty(obj: unknown): boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aigne/core",
3
- "version": "1.15.0",
3
+ "version": "1.16.0",
4
4
  "description": "AIGNE core library for building AI-powered applications",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -50,9 +50,6 @@
50
50
  "loader/*": [
51
51
  "./lib/dts/loader/*"
52
52
  ],
53
- "models/*": [
54
- "./lib/dts/models/*"
55
- ],
56
53
  "memory/*": [
57
54
  "./lib/dts/memory/*"
58
55
  ],
@@ -61,12 +58,6 @@
61
58
  ],
62
59
  "utils/*": [
63
60
  "./lib/dts/utils/*"
64
- ],
65
- "client/*": [
66
- "./lib/dts/client/*"
67
- ],
68
- "server/*": [
69
- "./lib/dts/server/*"
70
61
  ]
71
62
  }
72
63
  },
@@ -91,15 +82,7 @@
91
82
  "zod": "^3.24.4",
92
83
  "zod-to-json-schema": "^3.24.5"
93
84
  },
94
- "peerDependencies": {
95
- "@anthropic-ai/sdk": "^0.39.0",
96
- "@aws-sdk/client-bedrock-runtime": "^3.796.0",
97
- "@google/generative-ai": "^0.24.0",
98
- "openai": "^4.87.3"
99
- },
100
85
  "devDependencies": {
101
- "@anthropic-ai/sdk": "^0.41.0",
102
- "@google/generative-ai": "^0.24.1",
103
86
  "@types/bun": "^1.2.12",
104
87
  "@types/compression": "^1.7.5",
105
88
  "@types/content-type": "^1.1.8",
@@ -109,9 +92,7 @@
109
92
  "compression": "^1.8.0",
110
93
  "detect-port": "^2.1.0",
111
94
  "express": "^5.1.0",
112
- "hono": "^4.7.8",
113
95
  "npm-run-all": "^4.1.5",
114
- "openai": "^4.97.0",
115
96
  "rimraf": "^6.0.1",
116
97
  "typescript": "^5.8.3"
117
98
  },
@@ -1,97 +0,0 @@
1
- /**
2
- * Client module used to interact with the AIGNE framework.
3
- */
4
- import type { AgentInvokeOptions, AgentResponse, AgentResponseStream, Message } from "../agents/agent.js";
5
- /**
6
- * Configuration options for the AIGNEClient.
7
- */
8
- export interface AIGNEClientOptions {
9
- /**
10
- * The URL of the AIGNE server to connect to.
11
- * This should point to the base endpoint where the AIGNEServer is hosted.
12
- */
13
- url: string;
14
- }
15
- /**
16
- * Options for invoking an agent through the AIGNEClient.
17
- * Extends the standard AgentInvokeOptions with client-specific options.
18
- */
19
- export interface AIGNEClientInvokeOptions extends AgentInvokeOptions {
20
- /**
21
- * Additional fetch API options to customize the HTTP request.
22
- * These options will be merged with the default options used by the client.
23
- */
24
- fetchOptions?: Partial<RequestInit>;
25
- }
26
- /**
27
- * Client for interacting with a remote AIGNE server.
28
- * AIGNEClient provides a client-side interface that matches the AIGNE API,
29
- * allowing applications to invoke agents and receive responses from a remote AIGNE instance.
30
- *
31
- * @example
32
- * Here's a simple example of how to use AIGNEClient:
33
- * {@includeCode ../../test/client/client.test.ts#example-aigne-client-simple}
34
- *
35
- * @example
36
- * Here's an example of how to use AIGNEClient with streaming response:
37
- * {@includeCode ../../test/client/client.test.ts#example-aigne-client-streaming}
38
- */
39
- export declare class AIGNEClient {
40
- options: AIGNEClientOptions;
41
- /**
42
- * Creates a new AIGNEClient instance.
43
- *
44
- * @param options - Configuration options for connecting to the AIGNE server
45
- */
46
- constructor(options: AIGNEClientOptions);
47
- /**
48
- * Invokes an agent in non-streaming mode and returns the complete response.
49
- *
50
- * @param agent - Name of the agent to invoke
51
- * @param input - Input message for the agent
52
- * @param options - Options with streaming mode explicitly set to false or omitted
53
- * @returns The complete agent response
54
- *
55
- * @example
56
- * Here's a simple example of how to use AIGNEClient:
57
- * {@includeCode ../../test/client/client.test.ts#example-aigne-client-simple}
58
- */
59
- invoke<I extends Message, O extends Message>(agent: string, input: I, options?: AIGNEClientInvokeOptions & {
60
- streaming?: false;
61
- }): Promise<O>;
62
- /**
63
- * Invokes an agent with streaming mode enabled and returns a stream of response chunks.
64
- *
65
- * @param agent - Name of the agent to invoke
66
- * @param input - Input message for the agent
67
- * @param options - Options with streaming mode explicitly set to true
68
- * @returns A stream of agent response chunks
69
- *
70
- * @example
71
- * Here's an example of how to use AIGNEClient with streaming response:
72
- * {@includeCode ../../test/client/client.test.ts#example-aigne-client-streaming}
73
- */
74
- invoke<I extends Message, O extends Message>(agent: string, input: I, options: AIGNEClientInvokeOptions & {
75
- streaming: true;
76
- }): Promise<AgentResponseStream<O>>;
77
- /**
78
- * Invokes an agent with the given input and options.
79
- *
80
- * @param agent - Name of the agent to invoke
81
- * @param input - Input message for the agent
82
- * @param options - Options for the invocation
83
- * @returns Either a complete response or a response stream depending on the streaming option
84
- */
85
- invoke<I extends Message, O extends Message>(agent: string, input: I, options?: AIGNEClientInvokeOptions): Promise<AgentResponse<O>>;
86
- /**
87
- * Enhanced fetch method that handles error responses from the AIGNE server.
88
- * This method wraps the standard fetch API to provide better error handling and reporting.
89
- *
90
- * @param args - Standard fetch API arguments (url and options)
91
- * @returns A Response object if the request was successful
92
- * @throws Error with detailed information if the request failed
93
- *
94
- * @private
95
- */
96
- fetch(...args: Parameters<typeof globalThis.fetch>): Promise<Response>;
97
- }
@@ -1,87 +0,0 @@
1
- "use strict";
2
- /**
3
- * Client module used to interact with the AIGNE framework.
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AIGNEClient = void 0;
7
- const event_stream_js_1 = require("../utils/event-stream.js");
8
- const type_utils_js_1 = require("../utils/type-utils.js");
9
- /**
10
- * Client for interacting with a remote AIGNE server.
11
- * AIGNEClient provides a client-side interface that matches the AIGNE API,
12
- * allowing applications to invoke agents and receive responses from a remote AIGNE instance.
13
- *
14
- * @example
15
- * Here's a simple example of how to use AIGNEClient:
16
- * {@includeCode ../../test/client/client.test.ts#example-aigne-client-simple}
17
- *
18
- * @example
19
- * Here's an example of how to use AIGNEClient with streaming response:
20
- * {@includeCode ../../test/client/client.test.ts#example-aigne-client-streaming}
21
- */
22
- class AIGNEClient {
23
- options;
24
- /**
25
- * Creates a new AIGNEClient instance.
26
- *
27
- * @param options - Configuration options for connecting to the AIGNE server
28
- */
29
- constructor(options) {
30
- this.options = options;
31
- }
32
- async invoke(agent, input, options) {
33
- // Send the agent invocation request to the AIGNE server
34
- const response = await this.fetch(this.options.url, {
35
- ...options?.fetchOptions,
36
- method: "POST",
37
- headers: {
38
- "Content-Type": "application/json",
39
- ...options?.fetchOptions?.headers,
40
- },
41
- body: JSON.stringify({ agent, input, options }),
42
- });
43
- // For non-streaming responses, simply parse the JSON response and return it
44
- if (!options?.streaming) {
45
- return await response.json();
46
- }
47
- // For streaming responses, set up the streaming pipeline
48
- const stream = response.body;
49
- if (!stream)
50
- throw new Error("Response body is not a stream");
51
- // Process the stream through a series of transforms:
52
- // 1. Convert bytes to text
53
- // 2. Parse SSE format into structured events
54
- // 3. Convert events into a standardized agent response stream
55
- return stream
56
- .pipeThrough(new TextDecoderStream())
57
- .pipeThrough(new event_stream_js_1.EventStreamParser())
58
- .pipeThrough(new event_stream_js_1.AgentResponseStreamParser());
59
- }
60
- /**
61
- * Enhanced fetch method that handles error responses from the AIGNE server.
62
- * This method wraps the standard fetch API to provide better error handling and reporting.
63
- *
64
- * @param args - Standard fetch API arguments (url and options)
65
- * @returns A Response object if the request was successful
66
- * @throws Error with detailed information if the request failed
67
- *
68
- * @private
69
- */
70
- async fetch(...args) {
71
- const result = await globalThis.fetch(...args);
72
- if (!result.ok) {
73
- let message;
74
- try {
75
- const text = await result.text();
76
- const json = (0, type_utils_js_1.tryOrThrow)(() => JSON.parse(text));
77
- message = json?.error?.message || text;
78
- }
79
- catch {
80
- // ignore
81
- }
82
- throw new Error(`Failed to fetch url ${args[0]} with status ${result.status}: ${message}`);
83
- }
84
- return result;
85
- }
86
- }
87
- exports.AIGNEClient = AIGNEClient;
@@ -1 +0,0 @@
1
- export * from "./client.js";
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./client.js"), exports);
@@ -1,79 +0,0 @@
1
- import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
2
- import { z } from "zod";
3
- import type { AgentResponse } from "../agents/agent.js";
4
- import { ChatModel, type ChatModelInput, type ChatModelOptions, type ChatModelOutput } from "./chat-model.js";
5
- /**
6
- * @hidden
7
- */
8
- export declare function extractLastJsonObject(text: string): string | null;
9
- export interface BedrockChatModelOptions {
10
- accessKeyId?: string;
11
- secretAccessKey?: string;
12
- region?: string;
13
- model?: string;
14
- modelOptions?: ChatModelOptions;
15
- }
16
- /**
17
- * @hidden
18
- */
19
- export declare const bedrockChatModelOptionsSchema: z.ZodObject<{
20
- region: z.ZodOptional<z.ZodString>;
21
- model: z.ZodOptional<z.ZodString>;
22
- modelOptions: z.ZodOptional<z.ZodObject<{
23
- model: z.ZodOptional<z.ZodString>;
24
- temperature: z.ZodOptional<z.ZodNumber>;
25
- topP: z.ZodOptional<z.ZodNumber>;
26
- frequencyPenalty: z.ZodOptional<z.ZodNumber>;
27
- presencePenalty: z.ZodOptional<z.ZodNumber>;
28
- parallelToolCalls: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
29
- }, "strip", z.ZodTypeAny, {
30
- parallelToolCalls: boolean;
31
- model?: string | undefined;
32
- temperature?: number | undefined;
33
- topP?: number | undefined;
34
- frequencyPenalty?: number | undefined;
35
- presencePenalty?: number | undefined;
36
- }, {
37
- model?: string | undefined;
38
- temperature?: number | undefined;
39
- topP?: number | undefined;
40
- frequencyPenalty?: number | undefined;
41
- presencePenalty?: number | undefined;
42
- parallelToolCalls?: boolean | undefined;
43
- }>>;
44
- }, "strip", z.ZodTypeAny, {
45
- modelOptions?: {
46
- parallelToolCalls: boolean;
47
- model?: string | undefined;
48
- temperature?: number | undefined;
49
- topP?: number | undefined;
50
- frequencyPenalty?: number | undefined;
51
- presencePenalty?: number | undefined;
52
- } | undefined;
53
- model?: string | undefined;
54
- region?: string | undefined;
55
- }, {
56
- modelOptions?: {
57
- model?: string | undefined;
58
- temperature?: number | undefined;
59
- topP?: number | undefined;
60
- frequencyPenalty?: number | undefined;
61
- presencePenalty?: number | undefined;
62
- parallelToolCalls?: boolean | undefined;
63
- } | undefined;
64
- model?: string | undefined;
65
- region?: string | undefined;
66
- }>;
67
- export declare class BedrockChatModel extends ChatModel {
68
- options?: BedrockChatModelOptions | undefined;
69
- constructor(options?: BedrockChatModelOptions | undefined);
70
- /**
71
- * @hidden
72
- */
73
- protected _client?: BedrockRuntimeClient;
74
- get client(): BedrockRuntimeClient;
75
- get modelOptions(): ChatModelOptions | undefined;
76
- process(input: ChatModelInput): Promise<AgentResponse<ChatModelOutput>>;
77
- private extractResultFromStream;
78
- private requestStructuredOutput;
79
- }