@aigne/agent-library 1.24.0 → 1.74.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 (163) hide show
  1. package/README.md +12 -12
  2. package/dist/_virtual/rolldown_runtime.cjs +29 -0
  3. package/dist/agent-skill-manager/index.cjs +30 -0
  4. package/dist/agent-skill-manager/index.d.cts +14 -0
  5. package/dist/agent-skill-manager/index.d.cts.map +1 -0
  6. package/dist/agent-skill-manager/index.d.mts +14 -0
  7. package/dist/agent-skill-manager/index.d.mts.map +1 -0
  8. package/dist/agent-skill-manager/index.mjs +30 -0
  9. package/dist/agent-skill-manager/index.mjs.map +1 -0
  10. package/{lib/esm/agent-skill-manager/prompt.js → dist/agent-skill-manager/prompt.cjs} +8 -3
  11. package/{lib/cjs/agent-skill-manager/prompt.js → dist/agent-skill-manager/prompt.mjs} +8 -6
  12. package/dist/agent-skill-manager/prompt.mjs.map +1 -0
  13. package/dist/ask-user-question/index.cjs +88 -0
  14. package/dist/ask-user-question/index.d.cts +33 -0
  15. package/dist/ask-user-question/index.d.cts.map +1 -0
  16. package/dist/ask-user-question/index.d.mts +33 -0
  17. package/dist/ask-user-question/index.d.mts.map +1 -0
  18. package/dist/ask-user-question/index.mjs +88 -0
  19. package/dist/ask-user-question/index.mjs.map +1 -0
  20. package/dist/bash/index.cjs +274 -0
  21. package/dist/bash/index.d.cts +184 -0
  22. package/dist/bash/index.d.cts.map +1 -0
  23. package/dist/bash/index.d.mts +184 -0
  24. package/dist/bash/index.d.mts.map +1 -0
  25. package/dist/bash/index.mjs +271 -0
  26. package/dist/bash/index.mjs.map +1 -0
  27. package/{lib/esm/bash/prompt.js → dist/bash/prompt.cjs} +6 -1
  28. package/{lib/cjs/bash/prompt.js → dist/bash/prompt.mjs} +6 -4
  29. package/dist/bash/prompt.mjs.map +1 -0
  30. package/dist/data-mapper/agents/mapper.cjs +62 -0
  31. package/dist/data-mapper/agents/mapper.mjs +62 -0
  32. package/dist/data-mapper/agents/mapper.mjs.map +1 -0
  33. package/dist/data-mapper/agents/reviewer.cjs +46 -0
  34. package/dist/data-mapper/agents/reviewer.mjs +46 -0
  35. package/dist/data-mapper/agents/reviewer.mjs.map +1 -0
  36. package/dist/data-mapper/index.cjs +25 -0
  37. package/dist/data-mapper/index.d.cts +26 -0
  38. package/dist/data-mapper/index.d.cts.map +1 -0
  39. package/dist/data-mapper/index.d.mts +26 -0
  40. package/dist/data-mapper/index.d.mts.map +1 -0
  41. package/dist/data-mapper/index.mjs +24 -0
  42. package/dist/data-mapper/index.mjs.map +1 -0
  43. package/{lib/esm/data-mapper/prompts.js → dist/data-mapper/prompts.cjs} +6 -1
  44. package/{lib/cjs/data-mapper/prompts.js → dist/data-mapper/prompts.mjs} +6 -4
  45. package/dist/data-mapper/prompts.mjs.map +1 -0
  46. package/dist/data-mapper/tools.cjs +119 -0
  47. package/dist/data-mapper/tools.d.cts +5 -0
  48. package/dist/data-mapper/tools.d.cts.map +1 -0
  49. package/dist/data-mapper/tools.d.mts +8 -0
  50. package/dist/data-mapper/tools.d.mts.map +1 -0
  51. package/dist/data-mapper/tools.mjs +117 -0
  52. package/dist/data-mapper/tools.mjs.map +1 -0
  53. package/dist/index.cjs +0 -0
  54. package/dist/index.d.cts +1 -0
  55. package/dist/index.d.mts +1 -0
  56. package/dist/index.mjs +1 -0
  57. package/dist/orchestrator/index.cjs +233 -0
  58. package/dist/orchestrator/index.d.cts +89 -0
  59. package/dist/orchestrator/index.d.cts.map +1 -0
  60. package/dist/orchestrator/index.d.mts +89 -0
  61. package/dist/orchestrator/index.d.mts.map +1 -0
  62. package/dist/orchestrator/index.mjs +230 -0
  63. package/dist/orchestrator/index.mjs.map +1 -0
  64. package/{lib/cjs/orchestrator/prompt.js → dist/orchestrator/prompt.cjs} +32 -28
  65. package/{lib/esm/orchestrator/prompt.js → dist/orchestrator/prompt.mjs} +30 -25
  66. package/dist/orchestrator/prompt.mjs.map +1 -0
  67. package/dist/orchestrator/type.cjs +74 -0
  68. package/dist/orchestrator/type.d.cts +27 -0
  69. package/dist/orchestrator/type.d.cts.map +1 -0
  70. package/dist/orchestrator/type.d.mts +27 -0
  71. package/dist/orchestrator/type.d.mts.map +1 -0
  72. package/dist/orchestrator/type.mjs +67 -0
  73. package/dist/orchestrator/type.mjs.map +1 -0
  74. package/dist/utils/fs.cjs +23 -0
  75. package/dist/utils/fs.d.cts +6 -0
  76. package/dist/utils/fs.d.cts.map +1 -0
  77. package/dist/utils/fs.d.mts +6 -0
  78. package/dist/utils/fs.d.mts.map +1 -0
  79. package/dist/utils/fs.mjs +22 -0
  80. package/dist/utils/fs.mjs.map +1 -0
  81. package/dist/utils/mutex.cjs +28 -0
  82. package/dist/utils/mutex.d.cts +10 -0
  83. package/dist/utils/mutex.d.cts.map +1 -0
  84. package/dist/utils/mutex.d.mts +10 -0
  85. package/dist/utils/mutex.d.mts.map +1 -0
  86. package/dist/utils/mutex.mjs +28 -0
  87. package/dist/utils/mutex.mjs.map +1 -0
  88. package/package.json +51 -35
  89. package/CHANGELOG.md +0 -2392
  90. package/lib/cjs/agent-skill-manager/index.d.ts +0 -10
  91. package/lib/cjs/agent-skill-manager/index.js +0 -26
  92. package/lib/cjs/agent-skill-manager/prompt.d.ts +0 -1
  93. package/lib/cjs/ask-user-question/index.d.ts +0 -28
  94. package/lib/cjs/ask-user-question/index.js +0 -108
  95. package/lib/cjs/bash/index.d.ts +0 -180
  96. package/lib/cjs/bash/index.js +0 -365
  97. package/lib/cjs/bash/prompt.d.ts +0 -1
  98. package/lib/cjs/data-mapper/agents/mapper.d.ts +0 -14
  99. package/lib/cjs/data-mapper/agents/mapper.js +0 -63
  100. package/lib/cjs/data-mapper/agents/reviewer.d.ts +0 -19
  101. package/lib/cjs/data-mapper/agents/reviewer.js +0 -47
  102. package/lib/cjs/data-mapper/index.d.ts +0 -18
  103. package/lib/cjs/data-mapper/index.js +0 -24
  104. package/lib/cjs/data-mapper/prompts.d.ts +0 -1
  105. package/lib/cjs/data-mapper/tools.d.ts +0 -11
  106. package/lib/cjs/data-mapper/tools.js +0 -164
  107. package/lib/cjs/index.d.ts +0 -1
  108. package/lib/cjs/index.js +0 -2
  109. package/lib/cjs/orchestrator/index.d.ts +0 -78
  110. package/lib/cjs/orchestrator/index.js +0 -277
  111. package/lib/cjs/orchestrator/prompt.d.ts +0 -3
  112. package/lib/cjs/orchestrator/type.d.ts +0 -388
  113. package/lib/cjs/orchestrator/type.js +0 -95
  114. package/lib/cjs/package.json +0 -3
  115. package/lib/cjs/utils/fs.d.ts +0 -2
  116. package/lib/cjs/utils/fs.js +0 -25
  117. package/lib/cjs/utils/mutex.d.ts +0 -6
  118. package/lib/cjs/utils/mutex.js +0 -28
  119. package/lib/dts/agent-skill-manager/index.d.ts +0 -10
  120. package/lib/dts/agent-skill-manager/prompt.d.ts +0 -1
  121. package/lib/dts/ask-user-question/index.d.ts +0 -28
  122. package/lib/dts/bash/index.d.ts +0 -180
  123. package/lib/dts/bash/prompt.d.ts +0 -1
  124. package/lib/dts/data-mapper/agents/mapper.d.ts +0 -14
  125. package/lib/dts/data-mapper/agents/reviewer.d.ts +0 -19
  126. package/lib/dts/data-mapper/index.d.ts +0 -18
  127. package/lib/dts/data-mapper/prompts.d.ts +0 -1
  128. package/lib/dts/data-mapper/tools.d.ts +0 -11
  129. package/lib/dts/index.d.ts +0 -1
  130. package/lib/dts/orchestrator/index.d.ts +0 -78
  131. package/lib/dts/orchestrator/prompt.d.ts +0 -3
  132. package/lib/dts/orchestrator/type.d.ts +0 -388
  133. package/lib/dts/utils/fs.d.ts +0 -2
  134. package/lib/dts/utils/mutex.d.ts +0 -6
  135. package/lib/esm/agent-skill-manager/index.d.ts +0 -10
  136. package/lib/esm/agent-skill-manager/index.js +0 -23
  137. package/lib/esm/agent-skill-manager/prompt.d.ts +0 -1
  138. package/lib/esm/ask-user-question/index.d.ts +0 -28
  139. package/lib/esm/ask-user-question/index.js +0 -105
  140. package/lib/esm/bash/index.d.ts +0 -180
  141. package/lib/esm/bash/index.js +0 -328
  142. package/lib/esm/bash/prompt.d.ts +0 -1
  143. package/lib/esm/data-mapper/agents/mapper.d.ts +0 -14
  144. package/lib/esm/data-mapper/agents/mapper.js +0 -61
  145. package/lib/esm/data-mapper/agents/reviewer.d.ts +0 -19
  146. package/lib/esm/data-mapper/agents/reviewer.js +0 -45
  147. package/lib/esm/data-mapper/index.d.ts +0 -18
  148. package/lib/esm/data-mapper/index.js +0 -16
  149. package/lib/esm/data-mapper/prompts.d.ts +0 -1
  150. package/lib/esm/data-mapper/tools.d.ts +0 -11
  151. package/lib/esm/data-mapper/tools.js +0 -155
  152. package/lib/esm/index.d.ts +0 -1
  153. package/lib/esm/index.js +0 -1
  154. package/lib/esm/orchestrator/index.d.ts +0 -78
  155. package/lib/esm/orchestrator/index.js +0 -240
  156. package/lib/esm/orchestrator/prompt.d.ts +0 -3
  157. package/lib/esm/orchestrator/type.d.ts +0 -388
  158. package/lib/esm/orchestrator/type.js +0 -89
  159. package/lib/esm/package.json +0 -3
  160. package/lib/esm/utils/fs.d.ts +0 -2
  161. package/lib/esm/utils/fs.js +0 -21
  162. package/lib/esm/utils/mutex.d.ts +0 -6
  163. package/lib/esm/utils/mutex.js +0 -24
@@ -1,164 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.applyJsonataWithValidation = applyJsonataWithValidation;
7
- exports.applyJsonata = applyJsonata;
8
- exports.extendJsonata = extendJsonata;
9
- exports.addNullableToOptional = addNullableToOptional;
10
- /* eslint-disable @typescript-eslint/no-explicit-any */
11
- const jsonata_1 = __importDefault(require("jsonata"));
12
- const jsonschema_1 = require("jsonschema");
13
- async function applyJsonataWithValidation(data, expr, schema) {
14
- try {
15
- const result = await applyJsonata(data, expr);
16
- if (result === null ||
17
- result === undefined ||
18
- (Array.isArray(result) && result.length === 0) ||
19
- (typeof result === "object" && Object.keys(result).length === 0)) {
20
- return { success: false, error: "Result is empty" };
21
- }
22
- const validator = new jsonschema_1.Validator();
23
- const optionalSchema = addNullableToOptional(schema);
24
- const validation = validator.validate(result, optionalSchema);
25
- if (!validation.valid) {
26
- return {
27
- success: false,
28
- error: validation.errors
29
- .map((e) => `${e.stack}. Source: ${e.instance ? JSON.stringify(e.instance) : "undefined"}`)
30
- .join("\n")
31
- .slice(0, 5000),
32
- };
33
- }
34
- return { success: true, data: result };
35
- }
36
- catch (error) {
37
- return { success: false, error: `Validation failed: ${error.message}` };
38
- }
39
- }
40
- async function applyJsonata(data, expr) {
41
- try {
42
- const expression = extendJsonata(expr);
43
- const result = await expression.evaluate(data);
44
- return result;
45
- }
46
- catch (error) {
47
- throw new Error(`JSONata evaluation failed for expression "${expr}": ${error.message}`);
48
- }
49
- }
50
- function extendJsonata(expr) {
51
- const expression = (0, jsonata_1.default)(expr);
52
- expression.registerFunction("max", (arr) => {
53
- if (Array.isArray(arr)) {
54
- return Math.max(...arr.map(Number).filter((n) => !Number.isNaN(n)));
55
- }
56
- return arr;
57
- });
58
- expression.registerFunction("min", (arr) => {
59
- if (Array.isArray(arr)) {
60
- return Math.min(...arr.map(Number).filter((n) => !Number.isNaN(n)));
61
- }
62
- return arr;
63
- });
64
- expression.registerFunction("number", (value) => Number.parseFloat(value));
65
- expression.registerFunction("substring", (str, start, end) => String(str).substring(start, end));
66
- expression.registerFunction("replace", (obj, pattern, replacement) => {
67
- if (Array.isArray(obj)) {
68
- return obj.map((item) => String(item).replace(pattern, replacement));
69
- }
70
- if (typeof obj === "object") {
71
- return Object.fromEntries(Object.entries(obj || {}).map(([key, value]) => [
72
- key,
73
- String(value).replace(pattern, replacement),
74
- ]));
75
- }
76
- return String(obj).replace(pattern, replacement);
77
- });
78
- expression.registerFunction("toDate", (date) => {
79
- try {
80
- // Handle numeric timestamps (milliseconds or seconds)
81
- if (typeof date === "number" || /^\d+$/.test(date)) {
82
- const timestamp = typeof date === "number" ? date : Number.parseInt(date, 10);
83
- // If timestamp is in seconds (typically 10 digits), convert to milliseconds
84
- const millisTimestamp = timestamp < 10000000000 ? timestamp * 1000 : timestamp;
85
- return new Date(millisTimestamp).toISOString();
86
- }
87
- // Handle date strings in MM/DD/YYYY format
88
- const match = String(date).match(/^(\d{2})\/(\d{2})\/(\d{4})(?:\s+(\d{2}):(\d{2}):(\d{2}))?$/);
89
- if (match) {
90
- // eslint-disable-next-line @typescript-eslint/naming-convention
91
- const [_, month, day, year, hours = "00", minutes = "00", seconds = "00"] = match;
92
- const isoDate = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.000Z`;
93
- return new Date(isoDate).toISOString();
94
- }
95
- // Default case: try standard Date parsing
96
- return new Date(date).toISOString();
97
- }
98
- catch (e) {
99
- throw new Error(`Invalid date: ${e.message}`);
100
- }
101
- });
102
- expression.registerFunction("dateMax", (dates) => dates.reduce((max, curr) => (new Date(max) > new Date(curr) ? max : curr)));
103
- expression.registerFunction("dateMin", (dates) => dates.reduce((min, curr) => (new Date(min) < new Date(curr) ? min : curr)));
104
- expression.registerFunction("dateDiff", (date1, date2, unit = "days") => {
105
- const d1 = new Date(date1);
106
- const d2 = new Date(date2);
107
- const diff = Math.abs(d1.getTime() - d2.getTime());
108
- switch (unit.toLowerCase()) {
109
- case "seconds":
110
- return Math.floor(diff / 1000);
111
- case "minutes":
112
- return Math.floor(diff / (1000 * 60));
113
- case "hours":
114
- return Math.floor(diff / (1000 * 60 * 60));
115
- case "days":
116
- return Math.floor(diff / (1000 * 60 * 60 * 24));
117
- default:
118
- return diff; // milliseconds
119
- }
120
- });
121
- return expression;
122
- }
123
- function addNullableToOptional(schema) {
124
- if (!schema || typeof schema !== "object")
125
- return schema;
126
- const newSchema = { ...schema };
127
- if (schema.type === "object" && schema.properties) {
128
- const required = new Set(Array.isArray(schema.required) ? schema.required : []);
129
- newSchema.properties = Object.entries(schema.properties).reduce((acc, [key, value]) => ({
130
- // biome-ignore lint/performance/noAccumulatingSpread: false positive
131
- ...acc,
132
- [key]: !required.has(key) ? makeNullable(value) : addNullableToOptional(value),
133
- }), {});
134
- }
135
- if (schema.type === "array" && schema.items) {
136
- newSchema.items = addNullableToOptional(schema.items);
137
- }
138
- return newSchema;
139
- }
140
- function makeNullable(schema) {
141
- if (!schema || typeof schema !== "object")
142
- return schema;
143
- const newSchema = { ...schema };
144
- if (Array.isArray(schema.type)) {
145
- if (!schema.type.includes("null")) {
146
- newSchema.type = [...schema.type, "null"];
147
- }
148
- }
149
- else if (schema.type) {
150
- newSchema.type = [schema.type, "null"];
151
- }
152
- // Recursively process nested properties
153
- if (schema.properties) {
154
- newSchema.properties = Object.entries(schema.properties).reduce((acc, [key, value]) => ({
155
- // biome-ignore lint/performance/noAccumulatingSpread: false positive
156
- ...acc,
157
- [key]: makeNullable(value),
158
- }), {});
159
- }
160
- if (schema.items) {
161
- newSchema.items = makeNullable(schema.items);
162
- }
163
- return newSchema;
164
- }
@@ -1 +0,0 @@
1
- export {};
package/lib/cjs/index.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,78 +0,0 @@
1
- import { type AgentInvokeOptions, type AgentOptions, AIAgent, type AIAgentOptions, type Message, type PromptBuilder } from "@aigne/core";
2
- import { type NestAgentSchema } from "@aigne/core/loader/agent-yaml.js";
3
- import type { AgentLoadOptions } from "@aigne/core/loader/index.js";
4
- import { type Instructions } from "@aigne/core/loader/schema.js";
5
- import { type ZodType } from "zod";
6
- import { type StateManagementOptions } from "./type.js";
7
- /**
8
- * Configuration options for the Orchestrator Agent
9
- */
10
- export interface OrchestratorAgentOptions<I extends Message = Message, O extends Message = Message> extends Omit<AIAgentOptions<I, O>, "instructions"> {
11
- objective?: PromptBuilder;
12
- planner?: OrchestratorAgent<I, O>["planner"];
13
- worker?: OrchestratorAgent<I, O>["worker"];
14
- completer?: OrchestratorAgent<I, O>["completer"];
15
- /**
16
- * Configuration for managing execution state
17
- * Prevents context overflow during long-running executions
18
- */
19
- stateManagement?: StateManagementOptions;
20
- concurrency?: number;
21
- }
22
- export interface LoadOrchestratorAgentOptions {
23
- objective?: string | Instructions;
24
- planner?: NestAgentSchema;
25
- worker?: NestAgentSchema;
26
- completer?: NestAgentSchema;
27
- stateManagement?: StateManagementOptions;
28
- }
29
- /**
30
- * Orchestrator Agent Class
31
- *
32
- * This Agent is responsible for:
33
- * 1. Generating an execution plan based on the objective
34
- * 2. Breaking down the plan into steps and tasks
35
- * 3. Coordinating the execution of steps and tasks
36
- * 4. Synthesizing the final result
37
- *
38
- * Workflow:
39
- * - Receives input objective
40
- * - Uses planner to create execution plan
41
- * - Executes tasks and steps according to the plan
42
- * - Synthesizes final result through completer
43
- */
44
- export declare class OrchestratorAgent<I extends Message = Message, O extends Message = Message> extends AIAgent<I, O> {
45
- tag: string;
46
- static schema<T>({ filepath }: {
47
- filepath: string;
48
- }): ZodType<T>;
49
- static load<I extends Message = Message, O extends Message = Message>({ filepath, parsed, options, }: {
50
- filepath: string;
51
- parsed: LoadOrchestratorAgentOptions & AgentOptions<I, O>;
52
- options?: AgentLoadOptions;
53
- }): Promise<OrchestratorAgent<I, O>>;
54
- /**
55
- * Factory method to create an OrchestratorAgent instance
56
- * @param options - Configuration options for the Orchestrator Agent
57
- * @returns A new OrchestratorAgent instance
58
- */
59
- static from<I extends Message, O extends Message>(options: OrchestratorAgentOptions<I, O>): OrchestratorAgent<I, O>;
60
- /**
61
- * Creates an OrchestratorAgent instance
62
- * @param options - Configuration options for the Orchestrator Agent
63
- */
64
- constructor(options: OrchestratorAgentOptions<I, O>);
65
- private objective?;
66
- private planner;
67
- private worker;
68
- private completer;
69
- private stateManagement?;
70
- private concurrency;
71
- /**
72
- * Compress execution state to prevent context overflow
73
- * Uses reverse accumulation to efficiently find optimal task count
74
- */
75
- private compressState;
76
- process(input: I, options: AgentInvokeOptions): AsyncGenerator<import("@aigne/core").AgentResponseChunk<O>, void, unknown>;
77
- }
78
- export default OrchestratorAgent;
@@ -1,277 +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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.OrchestratorAgent = void 0;
37
- const core_1 = require("@aigne/core");
38
- const agent_yaml_js_1 = require("@aigne/core/loader/agent-yaml.js");
39
- const schema_js_1 = require("@aigne/core/loader/schema.js");
40
- const agent_utils_js_1 = require("@aigne/core/utils/agent-utils.js");
41
- const fastq = __importStar(require("@aigne/core/utils/queue.js"));
42
- const token_estimator_js_1 = require("@aigne/core/utils/token-estimator.js");
43
- const type_utils_js_1 = require("@aigne/core/utils/type-utils.js");
44
- const zod_1 = require("zod");
45
- const prompt_js_1 = require("./prompt.js");
46
- const type_js_1 = require("./type.js");
47
- const defaultPlannerOptions = {
48
- name: "Planner",
49
- instructions: prompt_js_1.TODO_PLANNER_PROMPT_TEMPLATE,
50
- inputSchema: type_js_1.plannerInputSchema,
51
- outputSchema: type_js_1.plannerOutputSchema,
52
- };
53
- const defaultWorkerOptions = {
54
- name: "Worker",
55
- taskTitle: "Execute Task: {{task}}",
56
- instructions: prompt_js_1.TODO_WORKER_PROMPT_TEMPLATE,
57
- inputSchema: type_js_1.workerInputSchema,
58
- outputSchema: type_js_1.workerOutputSchema,
59
- };
60
- const defaultCompleterOptions = {
61
- name: "Completer",
62
- instructions: prompt_js_1.ORCHESTRATOR_COMPLETE_PROMPT,
63
- inputSchema: type_js_1.completerInputSchema,
64
- };
65
- const DEFAULT_CONCURRENCY = 5;
66
- /**
67
- * Orchestrator Agent Class
68
- *
69
- * This Agent is responsible for:
70
- * 1. Generating an execution plan based on the objective
71
- * 2. Breaking down the plan into steps and tasks
72
- * 3. Coordinating the execution of steps and tasks
73
- * 4. Synthesizing the final result
74
- *
75
- * Workflow:
76
- * - Receives input objective
77
- * - Uses planner to create execution plan
78
- * - Executes tasks and steps according to the plan
79
- * - Synthesizes final result through completer
80
- */
81
- class OrchestratorAgent extends core_1.AIAgent {
82
- tag = "OrchestratorAgent";
83
- static schema({ filepath }) {
84
- const nestAgentSchema = (0, agent_yaml_js_1.getNestAgentSchema)({ filepath });
85
- const instructionsSchema = (0, schema_js_1.getInstructionsSchema)({ filepath });
86
- return (0, schema_js_1.camelizeSchema)(zod_1.z.object({
87
- objective: (0, schema_js_1.optionalize)(instructionsSchema),
88
- planner: (0, schema_js_1.optionalize)(nestAgentSchema),
89
- worker: (0, schema_js_1.optionalize)(nestAgentSchema),
90
- completer: (0, schema_js_1.optionalize)(nestAgentSchema),
91
- stateManagement: (0, schema_js_1.optionalize)((0, schema_js_1.camelizeSchema)(type_js_1.stateManagementOptionsSchema)),
92
- concurrency: (0, schema_js_1.optionalize)(zod_1.z.number().int().min(1).default(DEFAULT_CONCURRENCY)),
93
- }));
94
- }
95
- static async load({ filepath, parsed, options, }) {
96
- const valid = await OrchestratorAgent.schema({
97
- filepath,
98
- }).parseAsync(parsed);
99
- return new OrchestratorAgent({
100
- ...parsed,
101
- objective: valid.objective ? (0, schema_js_1.instructionsToPromptBuilder)(valid.objective) : undefined,
102
- planner: valid.planner
103
- ? (await options?.loadNestAgent(filepath, valid.planner, options, {
104
- ...defaultPlannerOptions,
105
- afs: parsed.afs,
106
- skills: parsed.skills,
107
- }))
108
- : undefined,
109
- worker: valid.worker
110
- ? (await options?.loadNestAgent(filepath, valid.worker, options, {
111
- ...defaultWorkerOptions,
112
- afs: parsed.afs,
113
- skills: parsed.skills,
114
- }))
115
- : undefined,
116
- completer: valid.completer
117
- ? (await options?.loadNestAgent(filepath, valid.completer, options, {
118
- ...defaultCompleterOptions,
119
- outputSchema: parsed.outputSchema,
120
- afs: parsed.afs,
121
- skills: parsed.skills,
122
- }))
123
- : undefined,
124
- stateManagement: valid.stateManagement,
125
- });
126
- }
127
- /**
128
- * Factory method to create an OrchestratorAgent instance
129
- * @param options - Configuration options for the Orchestrator Agent
130
- * @returns A new OrchestratorAgent instance
131
- */
132
- static from(options) {
133
- return new OrchestratorAgent(options);
134
- }
135
- /**
136
- * Creates an OrchestratorAgent instance
137
- * @param options - Configuration options for the Orchestrator Agent
138
- */
139
- constructor(options) {
140
- super({ ...options });
141
- this.objective = options.objective;
142
- this.planner = (0, agent_utils_js_1.isAgent)(options.planner)
143
- ? options.planner
144
- : new core_1.AIAgent({
145
- ...options,
146
- ...defaultPlannerOptions,
147
- });
148
- this.worker = (0, agent_utils_js_1.isAgent)(options.worker)
149
- ? options.worker
150
- : new core_1.AIAgent({
151
- ...options,
152
- ...defaultWorkerOptions,
153
- });
154
- this.completer = (0, agent_utils_js_1.isAgent)(options.completer)
155
- ? options.completer
156
- : new core_1.AIAgent({
157
- ...(0, type_utils_js_1.omit)(options, "inputSchema"),
158
- ...defaultCompleterOptions,
159
- outputKey: options.outputKey,
160
- outputSchema: options.outputSchema,
161
- });
162
- // Initialize state management config
163
- this.stateManagement = options.stateManagement;
164
- this.concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
165
- }
166
- objective;
167
- planner;
168
- worker;
169
- completer;
170
- stateManagement;
171
- concurrency;
172
- /**
173
- * Compress execution state to prevent context overflow
174
- * Uses reverse accumulation to efficiently find optimal task count
175
- */
176
- compressState(state) {
177
- const { maxTokens, keepRecent } = this.stateManagement ?? {};
178
- if (!maxTokens && !keepRecent) {
179
- return state;
180
- }
181
- const tasks = state.tasks;
182
- let selectedTasks = tasks;
183
- // Step 1: Apply keepRecent limit if configured
184
- if (keepRecent && tasks.length > keepRecent) {
185
- selectedTasks = tasks.slice(-keepRecent);
186
- }
187
- // Step 2: Apply maxTokens limit if configured
188
- if (maxTokens && selectedTasks.length > 0) {
189
- // Start from the most recent task and accumulate backwards
190
- let accumulatedTokens = 0;
191
- let taskCount = 0;
192
- for (let i = selectedTasks.length - 1; i >= 0; i--) {
193
- const taskJson = JSON.stringify(selectedTasks[i]);
194
- const taskTokens = (0, token_estimator_js_1.estimateTokens)(taskJson);
195
- if (accumulatedTokens + taskTokens > maxTokens && taskCount > 0) {
196
- // Stop if adding this task would exceed limit
197
- break;
198
- }
199
- accumulatedTokens += taskTokens;
200
- taskCount++;
201
- }
202
- // Keep the most recent N tasks that fit within token limit
203
- if (taskCount < selectedTasks.length) {
204
- selectedTasks = selectedTasks.slice(-taskCount);
205
- }
206
- }
207
- return { tasks: selectedTasks };
208
- }
209
- async *process(input, options) {
210
- const model = this.model || options.model || options.context.model;
211
- if (!model)
212
- throw new Error("model is required to run OrchestratorAgent");
213
- const objective = (await this.objective?.buildPrompt({
214
- input,
215
- context: options.context,
216
- }))?.prompt;
217
- const executionState = { tasks: [] };
218
- let iterationCount = 0;
219
- const maxIterations = this.stateManagement?.maxIterations ?? type_js_1.DEFAULT_MAX_ITERATIONS;
220
- while (true) {
221
- // Check if maximum iterations reached
222
- if (maxIterations && iterationCount >= maxIterations) {
223
- console.warn(`Maximum iterations (${maxIterations}) reached. Stopping execution.`);
224
- executionState.tasks.push({
225
- status: "failed",
226
- error: { message: `ERROR: Maximum iterations (${maxIterations}) reached` },
227
- task: `ERROR: Objective not completed within iteration limit of ${maxIterations}`,
228
- createdAt: Date.now(),
229
- completedAt: Date.now(),
230
- });
231
- break;
232
- }
233
- iterationCount++;
234
- // Compress state for planner input if needed
235
- const compressedState = this.compressState(executionState);
236
- const plan = await this.invokeChildAgent(this.planner, {
237
- objective,
238
- executionState: compressedState,
239
- ...(0, type_utils_js_1.pick)(input, this.planner.inputKeys),
240
- }, { ...options, model, streaming: false });
241
- if (plan.finished || !plan.nextTasks?.length) {
242
- break;
243
- }
244
- const createdAt = Date.now();
245
- const queue = fastq.promise(async ({ task }) => {
246
- const taskResult = await this.invokeChildAgent(this.worker, {
247
- objective,
248
- executionState: compressedState,
249
- task,
250
- ...(0, type_utils_js_1.pick)(input, this.worker.inputKeys),
251
- }, { ...options, model, streaming: false })
252
- .then((res) => {
253
- if (res.error || res.success === false) {
254
- return { status: "failed", result: res.result, error: res.error };
255
- }
256
- return { status: "completed", result: res.result };
257
- })
258
- .catch((error) => ({
259
- status: "failed",
260
- error: { message: error instanceof Error ? error.message : String(error) },
261
- }));
262
- return { ...taskResult, task, createdAt, completedAt: Date.now() };
263
- }, plan.parallelTasks ? this.concurrency : 1);
264
- const taskResults = await Promise.all(plan.nextTasks.map((task) => queue.push({ task })));
265
- executionState.tasks.push(...taskResults);
266
- }
267
- // Compress state for completer input if needed
268
- const compressedState = this.compressState(executionState);
269
- yield* await this.invokeChildAgent(this.completer, {
270
- objective,
271
- executionState: compressedState,
272
- ...(0, type_utils_js_1.pick)(input, this.completer.inputKeys),
273
- }, { ...options, model, streaming: true });
274
- }
275
- }
276
- exports.OrchestratorAgent = OrchestratorAgent;
277
- exports.default = OrchestratorAgent;
@@ -1,3 +0,0 @@
1
- export declare const ORCHESTRATOR_COMPLETE_PROMPT = "You are an intelligent assistant that synthesizes and presents the results of completed tasks.\n\n{% if $afs.enabled %}\n## Environment\n\n### AFS\n{{ $afs.description }}\n\n```yaml alt=\"The modules available in the AFS\"\n{{ $afs.modules | yaml.stringify }}\n```\n{% endif %}\n\n## User's Objective\n\n```txt alt=\"The user's latest objective you need to address\"\n{{ objective }}\n```\n\n## Current Execution State\n\n```yaml alt=\"The latest execution state\"\n{{ executionState | yaml.stringify }}\n```\n\n## Your Task\nBased on the execution results above, provide a comprehensive and helpful response to the user's objective.\n";
2
- export declare const TODO_PLANNER_PROMPT_TEMPLATE = "Your responsibility is to decide the next tasks based on the current execution state.\n\n## Responsibilities\n\nYou are the Planner in the Orchestrator. The entire Orchestrator completes tasks through collaboration of three roles:\n\n1. **Planner (you)** analyzes the current state and outputs \"nextTasks\" (one or more tasks)\n2. **Worker** executes the tasks and updates the execution state\n3. **Loop back to step 1**, Planner plans the next tasks based on the new state\n4. **Repeat steps 1-3** until Planner determines the objective is complete\n5. **Planner** sets \"finished: true\"\n6. **Completer** generates the final report and returns it to the user\n\n{% if $afs.enabled %}\n## Environment\n\n### AFS\n{{ $afs.description }}\n\n```yaml alt=\"The modules available in the AFS\"\n{{ $afs.modules | yaml.stringify }}\n```\n{% endif %}\n\n## User's Objective\n\n```txt alt=\"The user's next objective you need to plan for\"\n{{ objective }}\n```\n\n## Current Execution State\n\n```yaml alt=\"The latest execution state\"\n{{ executionState | yaml.stringify }}\n```\n\n## How to Plan Tasks\n\n### 1. Determine if Tasks Are Needed\n\nFirst, assess whether the objective requires any tasks at all. Ask yourself:\n\n**Does this objective require tasks?**\n\nConsider if completing the objective needs:\n- **Information gathering**: Does it need to collect or retrieve information?\n- **Analysis or processing**: Does it need to analyze, process, or compute something?\n- **State dependency**: Does it depend on information not yet in the execution state?\n\n**Set \"finished: true\" immediately when:**\n- The objective requires no exploration, analysis, or information gathering\n- The current execution state already contains everything needed to respond\n- The objective is purely conversational without requiring any action\n\n**Plan tasks when:**\n- The objective requires gathering information from external sources\n- The objective requires analysis, processing, or computation to be performed\n- Additional information must be collected before a complete response can be given\n\n### 2. Analyze Information Requirements\n\nIf tasks are needed, think about the current state and objective:\n- What information is needed to complete the objective?\n- Where can this information be obtained from?\n- What information has already been collected? What is still missing?\n- Is deeper exploration needed, or is it ready to generate a summary?\n\n### 3. Decision Principles\n\n- **Plan one or more tasks per iteration**: You can output multiple tasks when they are independent\n- **Only decide, don't execute**: You only output task descriptions, actual execution is done by the Worker\n- **Trust the iterative process**: You will be called again after tasks complete, allowing you to adjust the plan dynamically\n- **Avoid duplicate work**: Review the execution history to understand what has been completed\n- **Goal-oriented descriptions**: Task descriptions should state \"what to do\", not \"how to do it\"\n- **Handle failures appropriately**: If a previous task failed, decide whether to retry, skip, or use an alternative approach\n\n### 4. Parallel vs Sequential Execution\n\nYou can specify whether tasks should run in parallel or sequentially using `parallelTasks`.\n\n**IMPORTANT: When tasks run in parallel, they CANNOT see each other's results.** Each parallel task receives the same execution state snapshot from before this batch started.\n\n**Set `parallelTasks: true` ONLY when ALL conditions are met:**\n- Tasks operate on **completely independent** data sources or resources\n- Task results are **not needed by other tasks** in the same batch\n- Tasks have **no ordering requirements** between them\n- You are **100% certain** there are no dependencies\n\n**Set `parallelTasks: false` (default) when ANY of these apply:**\n- Any task needs results from another task in the same batch\n- Tasks must be executed in a specific order\n- Tasks operate on shared resources that could conflict\n- You are **uncertain** whether tasks are truly independent\n\n**When in doubt, use sequential execution.** It's safer to be slower than to produce incorrect results.\n\n### 5. Decision Making at Different Stages\n\nFlexibly decide the next step based on current progress:\n\n**Exploration Stage**:\n- Plan exploration tasks to gather required information\n- If exploring multiple independent sources, consider parallel execution\n\n**Processing Stage**:\n- Process gathered information\n- Use sequential execution when processing depends on previous results\n\n**Summary Stage**:\n- When sufficient information is collected, plan to generate a summary or report task\n\n**Completion Stage**:\n- Set \"finished: true\" when:\n - The objective doesn't require any tasks\n - All necessary tasks are completed\n - The objective is fully achieved\n- This will trigger the Completer to integrate all information and generate the final report\n\n## Understanding Task Status\n\nEach task in the execution state has a status:\n- **completed**: Task finished successfully, result is available\n- **failed**: Task encountered an error, check error field for details\n- **pending**: Task has not been executed yet\n\n## Output Format\n\n```yaml\nnextTasks: # List of tasks to execute (omit if finished)\n - \"task description 1\"\n - \"task description 2\"\nparallelTasks: false # true if tasks can run in parallel, false for sequential (default: false)\nfinished: false # true if objective is achieved and no more tasks needed\n```\n\n**Notes:**\n- Task descriptions should be **goal-oriented**, not specifying concrete operations\n- Let the worker autonomously decide how to complete each task\n- Default to sequential execution (`parallelTasks: false`) unless you're certain tasks are independent\n- When `finished: true`, omit `nextTasks`\n";
3
- export declare const TODO_WORKER_PROMPT_TEMPLATE = "You are a task execution agent. Your job is to execute the specific task assigned to you - nothing more, nothing less.\n\n{% if $afs.enabled %}\n## Environment\n\n### AFS\n{{ $afs.description }}\n\n```yaml alt=\"The modules available in the AFS\"\n{{ $afs.modules | yaml.stringify }}\n```\n{% endif %}\n\n## User's Objective\n\n```txt alt=\"The user's objective provide for context only\"\n{{ objective }}\n```\n\n**CRITICAL CONSTRAINT**: The objective above is provided ONLY for context. You must NOT attempt to:\n- Solve the entire objective\n- Plan additional steps beyond your current task\n- Make decisions about what should happen next\n- Execute any tasks other than the one explicitly assigned to you below\n\n## Latest Execution State\n\n```yaml alt=\"The latest execution state for your reference\"\n{{ executionState | yaml.stringify }}\n```\n\n## Your Current Task\n\n```txt alt=\"The specific task you need to execute now\"\n{{ task }}\n```\n\n## Important Instructions\n- Focus EXCLUSIVELY on completing the current task described above\n- The task is self-contained - execute it completely and accurately\n- Do NOT perform additional tasks beyond what is specified\n- Do NOT try to determine what should happen after this task\n- Use the available tools and skills to accomplish this specific task\n- Return a clear result that the planner can use to decide the next step\n\n## Output Format\nReturn your task execution result as a structured response. The output schema will guide you on the required fields.\n";