@aigne/core 1.70.1 → 1.71.0-beta

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 (49) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/lib/cjs/agents/agent.d.ts +4 -0
  3. package/lib/cjs/agents/agent.js +3 -0
  4. package/lib/cjs/agents/image-agent.js +2 -2
  5. package/lib/cjs/agents/types.d.ts +9 -1
  6. package/lib/cjs/loader/agent-js.d.ts +1 -2
  7. package/lib/cjs/loader/agent-js.js +2 -2
  8. package/lib/cjs/loader/agent-yaml.d.ts +19 -3
  9. package/lib/cjs/loader/agent-yaml.js +151 -110
  10. package/lib/cjs/loader/index.d.ts +10 -1
  11. package/lib/cjs/loader/index.js +42 -17
  12. package/lib/cjs/prompt/prompt-builder.d.ts +3 -3
  13. package/lib/cjs/prompt/prompt-builder.js +8 -2
  14. package/lib/cjs/prompt/skills/afs.js +41 -4
  15. package/lib/cjs/prompt/template.d.ts +1 -0
  16. package/lib/cjs/prompt/template.js +5 -3
  17. package/lib/cjs/utils/agent-utils.d.ts +3 -2
  18. package/lib/cjs/utils/agent-utils.js +7 -0
  19. package/lib/cjs/utils/token-estimator.d.ts +9 -0
  20. package/lib/cjs/utils/token-estimator.js +66 -0
  21. package/lib/dts/agents/agent.d.ts +4 -0
  22. package/lib/dts/agents/types.d.ts +9 -1
  23. package/lib/dts/loader/agent-js.d.ts +1 -2
  24. package/lib/dts/loader/agent-yaml.d.ts +19 -3
  25. package/lib/dts/loader/index.d.ts +10 -1
  26. package/lib/dts/prompt/prompt-builder.d.ts +3 -3
  27. package/lib/dts/prompt/template.d.ts +1 -0
  28. package/lib/dts/utils/agent-utils.d.ts +3 -2
  29. package/lib/dts/utils/token-estimator.d.ts +9 -0
  30. package/lib/esm/agents/agent.d.ts +4 -0
  31. package/lib/esm/agents/agent.js +3 -0
  32. package/lib/esm/agents/image-agent.js +2 -2
  33. package/lib/esm/agents/types.d.ts +9 -1
  34. package/lib/esm/loader/agent-js.d.ts +1 -2
  35. package/lib/esm/loader/agent-js.js +2 -2
  36. package/lib/esm/loader/agent-yaml.d.ts +19 -3
  37. package/lib/esm/loader/agent-yaml.js +147 -110
  38. package/lib/esm/loader/index.d.ts +10 -1
  39. package/lib/esm/loader/index.js +41 -19
  40. package/lib/esm/prompt/prompt-builder.d.ts +3 -3
  41. package/lib/esm/prompt/prompt-builder.js +8 -2
  42. package/lib/esm/prompt/skills/afs.js +41 -4
  43. package/lib/esm/prompt/template.d.ts +1 -0
  44. package/lib/esm/prompt/template.js +5 -3
  45. package/lib/esm/utils/agent-utils.d.ts +3 -2
  46. package/lib/esm/utils/agent-utils.js +6 -0
  47. package/lib/esm/utils/token-estimator.d.ts +9 -0
  48. package/lib/esm/utils/token-estimator.js +63 -0
  49. package/package.json +3 -3
@@ -65,6 +65,12 @@ class PromptBuilder {
65
65
  }
66
66
  instructions;
67
67
  workingDir;
68
+ copy() {
69
+ return new PromptBuilder({
70
+ instructions: typeof this.instructions === "string" ? this.instructions : this.instructions?.copy(),
71
+ workingDir: this.workingDir,
72
+ });
73
+ }
68
74
  async build(options) {
69
75
  return {
70
76
  messages: await this.buildMessages(options),
@@ -75,11 +81,11 @@ class PromptBuilder {
75
81
  ...(await this.buildTools(options)),
76
82
  };
77
83
  }
78
- async buildImagePrompt(options) {
84
+ async buildPrompt(options) {
79
85
  const messages = (await (typeof this.instructions === "string"
80
86
  ? template_js_1.ChatMessagesTemplate.from([template_js_1.SystemMessageTemplate.from(this.instructions)])
81
87
  : this.instructions)?.format(this.getTemplateVariables(options), { workingDir: this.workingDir })) ?? [];
82
- const inputFileKey = options.agent?.inputFileKey;
88
+ const inputFileKey = options.inputFileKey;
83
89
  const files = (0, type_utils_js_1.flat)(inputFileKey
84
90
  ? (0, type_utils_js_1.checkArguments)("Check input files", (0, schema_js_1.optionalize)(model_js_1.fileUnionContentsSchema), options.input?.[inputFileKey])
85
91
  : null);
@@ -55,19 +55,39 @@ async function getAFSSkills(afs) {
55
55
  }),
56
56
  agent_js_1.FunctionAgent.from({
57
57
  name: "afs_read",
58
- description: "Read file contents from the AFS - path must be an exact file path from list or search results",
58
+ description: `\
59
+ Read file contents from the AFS - path must be an exact file path from list or search results
60
+
61
+ Usage:
62
+ - Use withLineNumbers=true to get line numbers for code reviews or edits
63
+ `,
59
64
  inputSchema: zod_1.z.object({
60
65
  path: zod_1.z
61
66
  .string()
62
67
  .describe("Exact file path from list or search results (e.g., '/docs/api.md', '/src/utils/helper.js')"),
68
+ withLineNumbers: zod_1.z
69
+ .boolean()
70
+ .optional()
71
+ .describe(`Whether to include line numbers in the returned content, default is false`),
63
72
  }),
64
73
  process: async (input) => {
65
74
  const result = await afs.read(input.path);
75
+ let content = result.result?.content;
76
+ if (input.withLineNumbers && typeof content === "string") {
77
+ content = content
78
+ .split("\n")
79
+ .map((line, idx) => `${idx + 1}| ${line}`)
80
+ .join("\n");
81
+ }
66
82
  return {
67
83
  status: "success",
68
84
  tool: "afs_read",
69
85
  path: input.path,
70
86
  ...result,
87
+ result: {
88
+ ...result.result,
89
+ content,
90
+ },
71
91
  };
72
92
  },
73
93
  }),
@@ -109,7 +129,9 @@ async function getAFSSkills(afs) {
109
129
  }
110
130
  function buildTreeView(entries) {
111
131
  const tree = {};
132
+ const entryMap = new Map();
112
133
  for (const entry of entries) {
134
+ entryMap.set(entry.path, entry);
113
135
  const parts = entry.path.split("/").filter(Boolean);
114
136
  let current = tree;
115
137
  for (const part of parts) {
@@ -119,13 +141,28 @@ function buildTreeView(entries) {
119
141
  current = current[part];
120
142
  }
121
143
  }
122
- function renderTree(node, prefix = "") {
144
+ function renderTree(node, prefix = "", currentPath = "") {
123
145
  let result = "";
124
146
  const keys = Object.keys(node);
125
147
  keys.forEach((key, index) => {
126
148
  const isLast = index === keys.length - 1;
127
- result += `${prefix}${isLast ? "└── " : "├── "}${key}\n`;
128
- result += renderTree(node[key], `${prefix}${isLast ? " " : "│ "}`);
149
+ const fullPath = currentPath ? `${currentPath}/${key}` : `/${key}`;
150
+ const entry = entryMap.get(fullPath);
151
+ // Build metadata suffix
152
+ const metadataParts = [];
153
+ // Children count
154
+ const childrenCount = entry?.metadata?.childrenCount;
155
+ if (childrenCount !== undefined && childrenCount > 0) {
156
+ metadataParts.push(`${childrenCount} items`);
157
+ }
158
+ // Executable
159
+ if (entry?.metadata?.execute) {
160
+ metadataParts.push("executable");
161
+ }
162
+ const metadataSuffix = metadataParts.length > 0 ? ` [${metadataParts.join(", ")}]` : "";
163
+ result += `${prefix}${isLast ? "└── " : "├── "}${key}${metadataSuffix}`;
164
+ result += `\n`;
165
+ result += renderTree(node[key], `${prefix}${isLast ? " " : "│ "}`, fullPath);
129
166
  });
130
167
  return result;
131
168
  }
@@ -62,6 +62,7 @@ export declare class ChatMessagesTemplate {
62
62
  messages: ChatMessageTemplate[];
63
63
  static from(messages: ChatMessageTemplate[] | string): ChatMessagesTemplate;
64
64
  constructor(messages: ChatMessageTemplate[]);
65
+ copy(): ChatMessagesTemplate;
65
66
  format(variables?: Record<string, unknown>, options?: FormatOptions): Promise<ChatModelInputMessage[]>;
66
67
  }
67
68
  declare const chatMessageSchema: z.ZodUnion<[z.ZodObject<{
@@ -8,6 +8,7 @@ exports.safeParseChatMessages = safeParseChatMessages;
8
8
  exports.parseChatMessages = parseChatMessages;
9
9
  const index_js_1 = require("@aigne/platform-helpers/nodejs/index.js");
10
10
  const nunjucks_1 = __importDefault(require("nunjucks"));
11
+ const yaml_1 = require("yaml");
11
12
  const zod_1 = require("zod");
12
13
  const type_utils_js_1 = require("../utils/type-utils.js");
13
14
  const index_js_2 = require("./filters/index.js");
@@ -144,9 +145,7 @@ class ToolMessageTemplate extends ChatMessageTemplate {
144
145
  return new ToolMessageTemplate(content, toolCallId, name, options);
145
146
  }
146
147
  constructor(content, toolCallId, name, options) {
147
- super("tool", typeof content === "string"
148
- ? content
149
- : JSON.stringify(content, (_, value) => typeof value === "bigint" ? value.toString() : value), name, options);
148
+ super("tool", typeof content === "string" ? content : (0, yaml_1.stringify)(content), name, options);
150
149
  this.toolCallId = toolCallId;
151
150
  }
152
151
  async format(_variables, _options) {
@@ -168,6 +167,9 @@ class ChatMessagesTemplate {
168
167
  constructor(messages) {
169
168
  this.messages = messages;
170
169
  }
170
+ copy() {
171
+ return new ChatMessagesTemplate(this.messages.map((m) => m));
172
+ }
171
173
  async format(variables, options) {
172
174
  return Promise.all(this.messages.map((message) => message.format(variables, options)));
173
175
  }
@@ -1,4 +1,4 @@
1
- import type { AgentHooks } from "../agents/agent.js";
1
+ import type { Agent, AgentHooks } from "../agents/agent.js";
2
2
  import type { AIGNECLIAgents } from "../aigne/type.js";
3
3
  export declare function sortHooks(hooks: AgentHooks[]): AgentHooks[];
4
4
  export interface CLIAgent<T> {
@@ -9,4 +9,5 @@ export interface CLIAgent<T> {
9
9
  agents?: CLIAgent<T>[];
10
10
  }
11
11
  export declare function mapCliAgent<A, O>({ agent, agents, ...input }: CLIAgent<A>, transform: (input: A) => O): CLIAgent<O>;
12
- export declare function findCliAgent(cli: AIGNECLIAgents, parent: string[] | "*", name: string): import("../agents/agent.js").Agent<any, any> | undefined;
12
+ export declare function findCliAgent(cli: AIGNECLIAgents, parent: string[] | "*", name: string): Agent<any, any> | undefined;
13
+ export declare function isAgent<A extends Agent>(obj: any): obj is A;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.sortHooks = sortHooks;
4
4
  exports.mapCliAgent = mapCliAgent;
5
5
  exports.findCliAgent = findCliAgent;
6
+ exports.isAgent = isAgent;
6
7
  const priorities = ["high", "medium", "low"];
7
8
  function sortHooks(hooks) {
8
9
  return hooks
@@ -51,3 +52,9 @@ function findCliAgentRecursive(agents, name) {
51
52
  }
52
53
  return undefined;
53
54
  }
55
+ function isAgent(obj) {
56
+ return (obj &&
57
+ typeof obj.name === "string" &&
58
+ typeof obj.invoke === "function" &&
59
+ typeof obj.process === "function");
60
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Estimate tokens in text by analyzing character types
3
+ * This function handles mixed-language text (Chinese and English) by counting
4
+ * different character types and applying appropriate token ratios for each type
5
+ *
6
+ * @param text - The text to estimate
7
+ * @returns Estimated token count
8
+ */
9
+ export declare function estimateTokens(text: string): number;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.estimateTokens = estimateTokens;
4
+ /**
5
+ * Token estimation ratios for different character types
6
+ * Based on empirical data from various tokenizers
7
+ */
8
+ const CHAR_TYPE_RATIOS = {
9
+ chinese: 1.5, // Chinese characters: ~1.5 characters per token
10
+ word: 0.75, // English words: ~0.75 tokens per word (accounting for subword tokenization)
11
+ other: 4, // Other characters (punctuation, numbers, etc.): ~4 characters per token
12
+ };
13
+ /**
14
+ * Regular expressions for character type detection
15
+ */
16
+ const CHAR_PATTERNS = {
17
+ // CJK characters (Chinese, Japanese Kanji, etc.)
18
+ chinese: /[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff]/g,
19
+ // English words (sequences of letters)
20
+ word: /[a-zA-Z]+/g,
21
+ };
22
+ /**
23
+ * Estimate tokens in text by analyzing character types
24
+ * This function handles mixed-language text (Chinese and English) by counting
25
+ * different character types and applying appropriate token ratios for each type
26
+ *
27
+ * @param text - The text to estimate
28
+ * @returns Estimated token count
29
+ */
30
+ function estimateTokens(text) {
31
+ if (!text)
32
+ return 0;
33
+ let tokens = 0;
34
+ const processedIndices = new Set();
35
+ // Count Chinese characters (including CJK)
36
+ const chineseMatches = text.match(CHAR_PATTERNS.chinese);
37
+ if (chineseMatches) {
38
+ tokens += chineseMatches.length / CHAR_TYPE_RATIOS.chinese;
39
+ // Mark processed positions
40
+ const chineseRegex = new RegExp(CHAR_PATTERNS.chinese.source, "g");
41
+ let match = chineseRegex.exec(text);
42
+ while (match !== null) {
43
+ processedIndices.add(match.index);
44
+ match = chineseRegex.exec(text);
45
+ }
46
+ }
47
+ // Count English words
48
+ const wordMatches = text.match(CHAR_PATTERNS.word);
49
+ if (wordMatches) {
50
+ tokens += wordMatches.length * CHAR_TYPE_RATIOS.word;
51
+ const wordRegex = new RegExp(CHAR_PATTERNS.word.source, "g");
52
+ let match = wordRegex.exec(text);
53
+ while (match !== null) {
54
+ for (let i = 0; i < match[0].length; i++) {
55
+ processedIndices.add(match.index + i);
56
+ }
57
+ match = wordRegex.exec(text);
58
+ }
59
+ }
60
+ // Count remaining characters (punctuation, numbers, whitespace, etc.)
61
+ const remainingChars = text.length - processedIndices.size;
62
+ if (remainingChars > 0) {
63
+ tokens += remainingChars / CHAR_TYPE_RATIOS.other;
64
+ }
65
+ return Math.ceil(tokens);
66
+ }
@@ -205,6 +205,10 @@ export declare abstract class Agent<I extends Message = any, O extends Message =
205
205
  * @returns Agent name
206
206
  */
207
207
  [nodejs.customInspect]: () => string;
208
+ static load<I extends Message = any, O extends Message = any>(_options: {
209
+ filepath: string;
210
+ parsed: object;
211
+ }): Promise<Agent<I, O>>;
208
212
  constructor(options?: AgentOptions<I, O>);
209
213
  /**
210
214
  * List of memories this agent can use
@@ -1,5 +1,5 @@
1
1
  import z, { type ZodType } from "zod";
2
- import { type Agent, DEFAULT_INPUT_ACTION_GET, type Message } from "./agent.js";
2
+ import { type Agent, type AgentOptions, DEFAULT_INPUT_ACTION_GET, type Message } from "./agent.js";
3
3
  export declare const transferAgentOutputKey = "$transferAgentTo";
4
4
  export interface TransferAgentOutput extends Message {
5
5
  [transferAgentOutputKey]: {
@@ -21,3 +21,11 @@ export declare function getterSchema<T extends ZodType>(schema: T): z.ZodUnion<[
21
21
  }, {
22
22
  $get: string;
23
23
  }>]>;
24
+ export interface AgentClass {
25
+ new (...args: any[]): Agent<any, any>;
26
+ load<I extends Message = any, O extends Message = any>(options: {
27
+ filepath: string;
28
+ parsed: AgentOptions;
29
+ [key: string]: any;
30
+ }): Promise<Agent<I, O>>;
31
+ }
@@ -1,2 +1 @@
1
- import { Agent } from "../agents/agent.js";
2
- export declare function loadAgentFromJsFile(path: string): Promise<Agent<any, any> | import("./agent-yaml.js").AgentSchema>;
1
+ export declare function loadAgentFromJsFile(path: string): Promise<import("../index.js").Agent<any, any> | import("./agent-yaml.js").AgentSchema>;
@@ -1,9 +1,10 @@
1
1
  import type { AFSOptions } from "@aigne/afs";
2
2
  import { type ZodType, z } from "zod";
3
- import type { AgentHooks, FunctionAgentFn, TaskRenderMode } from "../agents/agent.js";
3
+ import type { AgentClass, AgentHooks, FunctionAgentFn, TaskRenderMode } from "../agents/agent.js";
4
4
  import { AIAgentToolChoice } from "../agents/ai-agent.js";
5
5
  import { type Role } from "../agents/chat-model.js";
6
6
  import { ProcessMode, type ReflectionMode } from "../agents/team-agent.js";
7
+ import type { LoadOptions } from "./index.js";
7
8
  import { chatModelSchema, imageModelSchema } from "./schema.js";
8
9
  export interface HooksSchema {
9
10
  priority?: AgentHooks["priority"];
@@ -44,6 +45,7 @@ export interface BaseAgentSchema {
44
45
  afs?: boolean | (Omit<AFSOptions, "modules"> & {
45
46
  modules?: AFSModuleSchema[];
46
47
  });
48
+ shareAFS?: boolean;
47
49
  }
48
50
  export type Instructions = {
49
51
  role: Exclude<Role, "tool">;
@@ -93,6 +95,20 @@ export interface FunctionAgentSchema extends BaseAgentSchema {
93
95
  type: "function";
94
96
  process: FunctionAgentFn;
95
97
  }
96
- export type AgentSchema = AIAgentSchema | ImageAgentSchema | MCPAgentSchema | TeamAgentSchema | TransformAgentSchema | FunctionAgentSchema;
98
+ export interface ThirdAgentSchema extends BaseAgentSchema {
99
+ agentClass?: AgentClass;
100
+ type: "";
101
+ [key: string]: any;
102
+ }
103
+ export type AgentSchema = AIAgentSchema | ImageAgentSchema | MCPAgentSchema | TeamAgentSchema | TransformAgentSchema | FunctionAgentSchema | ThirdAgentSchema;
97
104
  export declare function parseAgentFile(path: string, data: any): Promise<AgentSchema>;
98
- export declare function loadAgentFromYamlFile(path: string): Promise<AgentSchema>;
105
+ export declare function loadAgentFromYamlFile(path: string, options?: LoadOptions): Promise<AgentSchema>;
106
+ export declare const getInstructionsSchema: ({ filepath }: {
107
+ filepath: string;
108
+ }) => ZodType<Instructions>;
109
+ export declare const getAgentSchema: ({ filepath }: {
110
+ filepath: string;
111
+ }) => ZodType<AgentSchema, z.ZodTypeDef, AgentSchema>;
112
+ export declare const getNestAgentSchema: ({ filepath, }: {
113
+ filepath: string;
114
+ }) => ZodType<NestAgentSchema>;
@@ -1,11 +1,13 @@
1
- import { type AFSModule } from "@aigne/afs";
1
+ import { AFS, type AFSModule } from "@aigne/afs";
2
2
  import { type ZodType, z } from "zod";
3
3
  import { Agent, type AgentOptions } from "../agents/agent.js";
4
4
  import type { ChatModel } from "../agents/chat-model.js";
5
5
  import type { ImageModel } from "../agents/image-model.js";
6
6
  import type { AIGNEOptions } from "../aigne/aigne.js";
7
7
  import type { MemoryAgent, MemoryAgentOptions } from "../memory/memory.js";
8
+ import { PromptBuilder } from "../prompt/prompt-builder.js";
8
9
  import { type PromiseOrValue } from "../utils/type-utils.js";
10
+ import { type Instructions, loadAgentFromYamlFile, type NestAgentSchema } from "./agent-yaml.js";
9
11
  export interface LoadOptions {
10
12
  memories?: {
11
13
  new (parameters?: MemoryAgentOptions): MemoryAgent;
@@ -13,6 +15,7 @@ export interface LoadOptions {
13
15
  model?: ChatModel | ((model?: z.infer<typeof aigneFileSchema>["model"]) => PromiseOrValue<ChatModel | undefined>);
14
16
  imageModel?: ImageModel | ((model?: z.infer<typeof aigneFileSchema>["imageModel"]) => PromiseOrValue<ImageModel | undefined>);
15
17
  afs?: {
18
+ sharedAFS?: AFS;
16
19
  availableModules?: {
17
20
  module: string;
18
21
  alias?: string[];
@@ -20,9 +23,14 @@ export interface LoadOptions {
20
23
  }[];
21
24
  };
22
25
  aigne?: z.infer<typeof aigneFileSchema>;
26
+ require?: (modulePath: string, options: {
27
+ parent?: string;
28
+ }) => Promise<any>;
23
29
  }
24
30
  export declare function load(path: string, options?: LoadOptions): Promise<AIGNEOptions>;
25
31
  export declare function loadAgent(path: string, options?: LoadOptions, agentOptions?: AgentOptions): Promise<Agent>;
32
+ export declare function loadNestAgent(path: string, agent: NestAgentSchema, options?: LoadOptions, agentOptions?: AgentOptions & Record<string, unknown>): Promise<Agent>;
33
+ export declare function parseAgent(path: string, agent: Awaited<ReturnType<typeof loadAgentFromYamlFile>>, options?: LoadOptions, agentOptions?: AgentOptions): Promise<Agent>;
26
34
  type CliAgent = string | {
27
35
  url?: string;
28
36
  name?: string;
@@ -230,4 +238,5 @@ export declare function loadAIGNEFile(path: string): Promise<{
230
238
  aigne: z.infer<typeof aigneFileSchema>;
231
239
  rootDir: string;
232
240
  }>;
241
+ export declare function instructionsToPromptBuilder(instructions: Instructions): PromptBuilder;
233
242
  export {};
@@ -2,7 +2,6 @@ import type { GetPromptResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  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
- import type { ImageAgent } from "../agents/image-agent.js";
6
5
  import { type FileUnionContent } from "../agents/model.js";
7
6
  import { ChatMessagesTemplate } from "./template.js";
8
7
  export interface PromptBuilderOptions {
@@ -26,11 +25,12 @@ export declare class PromptBuilder {
26
25
  constructor(options?: PromptBuilderOptions);
27
26
  instructions?: string | ChatMessagesTemplate;
28
27
  workingDir?: string;
28
+ copy(): PromptBuilder;
29
29
  build(options: PromptBuildOptions): Promise<ChatModelInput & {
30
30
  toolAgents?: Agent[];
31
31
  }>;
32
- buildImagePrompt(options: Pick<PromptBuildOptions, "input" | "context"> & {
33
- agent: ImageAgent;
32
+ buildPrompt(options: Pick<PromptBuildOptions, "input" | "context"> & {
33
+ inputFileKey?: string;
34
34
  }): Promise<{
35
35
  prompt: string;
36
36
  image?: FileUnionContent[];
@@ -62,6 +62,7 @@ export declare class ChatMessagesTemplate {
62
62
  messages: ChatMessageTemplate[];
63
63
  static from(messages: ChatMessageTemplate[] | string): ChatMessagesTemplate;
64
64
  constructor(messages: ChatMessageTemplate[]);
65
+ copy(): ChatMessagesTemplate;
65
66
  format(variables?: Record<string, unknown>, options?: FormatOptions): Promise<ChatModelInputMessage[]>;
66
67
  }
67
68
  declare const chatMessageSchema: z.ZodUnion<[z.ZodObject<{
@@ -1,4 +1,4 @@
1
- import type { AgentHooks } from "../agents/agent.js";
1
+ import type { Agent, AgentHooks } from "../agents/agent.js";
2
2
  import type { AIGNECLIAgents } from "../aigne/type.js";
3
3
  export declare function sortHooks(hooks: AgentHooks[]): AgentHooks[];
4
4
  export interface CLIAgent<T> {
@@ -9,4 +9,5 @@ export interface CLIAgent<T> {
9
9
  agents?: CLIAgent<T>[];
10
10
  }
11
11
  export declare function mapCliAgent<A, O>({ agent, agents, ...input }: CLIAgent<A>, transform: (input: A) => O): CLIAgent<O>;
12
- export declare function findCliAgent(cli: AIGNECLIAgents, parent: string[] | "*", name: string): import("../agents/agent.js").Agent<any, any> | undefined;
12
+ export declare function findCliAgent(cli: AIGNECLIAgents, parent: string[] | "*", name: string): Agent<any, any> | undefined;
13
+ export declare function isAgent<A extends Agent>(obj: any): obj is A;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Estimate tokens in text by analyzing character types
3
+ * This function handles mixed-language text (Chinese and English) by counting
4
+ * different character types and applying appropriate token ratios for each type
5
+ *
6
+ * @param text - The text to estimate
7
+ * @returns Estimated token count
8
+ */
9
+ export declare function estimateTokens(text: string): number;
@@ -205,6 +205,10 @@ export declare abstract class Agent<I extends Message = any, O extends Message =
205
205
  * @returns Agent name
206
206
  */
207
207
  [nodejs.customInspect]: () => string;
208
+ static load<I extends Message = any, O extends Message = any>(_options: {
209
+ filepath: string;
210
+ parsed: object;
211
+ }): Promise<Agent<I, O>>;
208
212
  constructor(options?: AgentOptions<I, O>);
209
213
  /**
210
214
  * List of memories this agent can use
@@ -77,6 +77,9 @@ export const agentOptionsSchema = z.object({
77
77
  * {@includeCode ../../test/agents/agent.test.ts#example-custom-agent}
78
78
  */
79
79
  export class Agent {
80
+ static async load(_options) {
81
+ throw new Error("Not implemented");
82
+ }
80
83
  constructor(options = {}) {
81
84
  checkArguments("Agent options", agentOptionsSchema, options);
82
85
  const { inputSchema, outputSchema } = options;
@@ -31,10 +31,10 @@ export class ImageAgent extends Agent {
31
31
  if (!imageModel)
32
32
  throw new Error("image model is required to run ImageAgent");
33
33
  const modelOptions = await imageModel.getModelOptions(input, options);
34
- const { prompt, image } = await this.instructions.buildImagePrompt({
34
+ const { prompt, image } = await this.instructions.buildPrompt({
35
35
  ...options,
36
36
  input,
37
- agent: this,
37
+ inputFileKey: this.inputFileKey,
38
38
  });
39
39
  const n = input.n || modelOptions?.n;
40
40
  return (await this.invokeChildAgent(imageModel, {
@@ -1,5 +1,5 @@
1
1
  import z, { type ZodType } from "zod";
2
- import { type Agent, DEFAULT_INPUT_ACTION_GET, type Message } from "./agent.js";
2
+ import { type Agent, type AgentOptions, DEFAULT_INPUT_ACTION_GET, type Message } from "./agent.js";
3
3
  export declare const transferAgentOutputKey = "$transferAgentTo";
4
4
  export interface TransferAgentOutput extends Message {
5
5
  [transferAgentOutputKey]: {
@@ -21,3 +21,11 @@ export declare function getterSchema<T extends ZodType>(schema: T): z.ZodUnion<[
21
21
  }, {
22
22
  $get: string;
23
23
  }>]>;
24
+ export interface AgentClass {
25
+ new (...args: any[]): Agent<any, any>;
26
+ load<I extends Message = any, O extends Message = any>(options: {
27
+ filepath: string;
28
+ parsed: AgentOptions;
29
+ [key: string]: any;
30
+ }): Promise<Agent<I, O>>;
31
+ }
@@ -1,2 +1 @@
1
- import { Agent } from "../agents/agent.js";
2
- export declare function loadAgentFromJsFile(path: string): Promise<Agent<any, any> | import("./agent-yaml.js").AgentSchema>;
1
+ export declare function loadAgentFromJsFile(path: string): Promise<import("../index.js").Agent<any, any> | import("./agent-yaml.js").AgentSchema>;
@@ -1,5 +1,5 @@
1
1
  import { nodejs } from "@aigne/platform-helpers/nodejs/index.js";
2
- import { Agent } from "../agents/agent.js";
2
+ import { isAgent } from "../utils/agent-utils.js";
3
3
  import { tryOrThrow } from "../utils/type-utils.js";
4
4
  import { parseAgentFile } from "./agent-yaml.js";
5
5
  import { LoadJsAgentError } from "./error.js";
@@ -7,7 +7,7 @@ const importFn = new Function("path", "return import(path)");
7
7
  export async function loadAgentFromJsFile(path) {
8
8
  const url = nodejs.path.isAbsolute(path) ? nodejs.url.pathToFileURL(path).toString() : path;
9
9
  const { default: agent } = await tryOrThrow(() => importFn(url), (error) => new LoadJsAgentError(`Failed to load agent definition from ${url}: ${error.message}`));
10
- if (agent instanceof Agent)
10
+ if (isAgent(agent))
11
11
  return agent;
12
12
  return tryOrThrow(() => parseAgentFile(path, {
13
13
  type: "function",
@@ -1,9 +1,10 @@
1
1
  import type { AFSOptions } from "@aigne/afs";
2
2
  import { type ZodType, z } from "zod";
3
- import type { AgentHooks, FunctionAgentFn, TaskRenderMode } from "../agents/agent.js";
3
+ import type { AgentClass, AgentHooks, FunctionAgentFn, TaskRenderMode } from "../agents/agent.js";
4
4
  import { AIAgentToolChoice } from "../agents/ai-agent.js";
5
5
  import { type Role } from "../agents/chat-model.js";
6
6
  import { ProcessMode, type ReflectionMode } from "../agents/team-agent.js";
7
+ import type { LoadOptions } from "./index.js";
7
8
  import { chatModelSchema, imageModelSchema } from "./schema.js";
8
9
  export interface HooksSchema {
9
10
  priority?: AgentHooks["priority"];
@@ -44,6 +45,7 @@ export interface BaseAgentSchema {
44
45
  afs?: boolean | (Omit<AFSOptions, "modules"> & {
45
46
  modules?: AFSModuleSchema[];
46
47
  });
48
+ shareAFS?: boolean;
47
49
  }
48
50
  export type Instructions = {
49
51
  role: Exclude<Role, "tool">;
@@ -93,6 +95,20 @@ export interface FunctionAgentSchema extends BaseAgentSchema {
93
95
  type: "function";
94
96
  process: FunctionAgentFn;
95
97
  }
96
- export type AgentSchema = AIAgentSchema | ImageAgentSchema | MCPAgentSchema | TeamAgentSchema | TransformAgentSchema | FunctionAgentSchema;
98
+ export interface ThirdAgentSchema extends BaseAgentSchema {
99
+ agentClass?: AgentClass;
100
+ type: "";
101
+ [key: string]: any;
102
+ }
103
+ export type AgentSchema = AIAgentSchema | ImageAgentSchema | MCPAgentSchema | TeamAgentSchema | TransformAgentSchema | FunctionAgentSchema | ThirdAgentSchema;
97
104
  export declare function parseAgentFile(path: string, data: any): Promise<AgentSchema>;
98
- export declare function loadAgentFromYamlFile(path: string): Promise<AgentSchema>;
105
+ export declare function loadAgentFromYamlFile(path: string, options?: LoadOptions): Promise<AgentSchema>;
106
+ export declare const getInstructionsSchema: ({ filepath }: {
107
+ filepath: string;
108
+ }) => ZodType<Instructions>;
109
+ export declare const getAgentSchema: ({ filepath }: {
110
+ filepath: string;
111
+ }) => ZodType<AgentSchema, z.ZodTypeDef, AgentSchema>;
112
+ export declare const getNestAgentSchema: ({ filepath, }: {
113
+ filepath: string;
114
+ }) => ZodType<NestAgentSchema>;