@inkeep/agents-sdk 0.39.5 → 0.41.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.
- package/dist/_virtual/rolldown_runtime.js +7 -0
- package/dist/agent.d.ts +186 -0
- package/dist/agent.js +720 -0
- package/dist/agentFullClient.d.ts +22 -0
- package/dist/agentFullClient.js +120 -0
- package/dist/artifact-component.d.ts +34 -0
- package/dist/artifact-component.js +104 -0
- package/dist/builderFunctions.d.ts +283 -0
- package/dist/builderFunctions.js +327 -0
- package/dist/builderFunctionsExperimental.d.ts +24 -0
- package/dist/builderFunctionsExperimental.js +27 -0
- package/dist/builders.d.ts +111 -0
- package/dist/builders.js +52 -0
- package/dist/credential-provider.d.ts +176 -0
- package/dist/credential-provider.js +237 -0
- package/dist/credential-ref.d.ts +60 -0
- package/dist/credential-ref.js +33 -0
- package/dist/data-component.d.ts +39 -0
- package/dist/data-component.js +109 -0
- package/dist/environment-settings.d.ts +27 -0
- package/dist/environment-settings.js +41 -0
- package/dist/external-agent.d.ts +64 -0
- package/dist/external-agent.js +156 -0
- package/dist/function-tool.d.ts +37 -0
- package/dist/function-tool.js +66 -0
- package/dist/index.d.ts +19 -1825
- package/dist/index.js +19 -4058
- package/dist/module-hosted-tool-manager.d.ts +40 -0
- package/dist/module-hosted-tool-manager.js +359 -0
- package/dist/project.d.ts +214 -0
- package/dist/project.js +615 -0
- package/dist/projectFullClient.d.ts +23 -0
- package/dist/projectFullClient.js +162 -0
- package/dist/runner.d.ts +41 -0
- package/dist/runner.js +145 -0
- package/dist/status-component.d.ts +22 -0
- package/dist/status-component.js +36 -0
- package/dist/subAgent.d.ts +52 -0
- package/dist/subAgent.js +616 -0
- package/dist/telemetry-provider.d.ts +218 -0
- package/dist/telemetry-provider.js +390 -0
- package/dist/tool.d.ts +53 -0
- package/dist/tool.js +130 -0
- package/dist/types.d.ts +296 -0
- package/dist/types.js +39 -0
- package/dist/utils/generateIdFromName.d.ts +9 -0
- package/dist/utils/generateIdFromName.js +12 -0
- package/dist/utils/getFunctionToolDeps.d.ts +17 -0
- package/dist/utils/getFunctionToolDeps.js +131 -0
- package/dist/utils/tool-normalization.d.ts +42 -0
- package/dist/utils/tool-normalization.js +41 -0
- package/dist/utils/validateFunction.d.ts +10 -0
- package/dist/utils/validateFunction.js +13 -0
- package/package.json +11 -16
- package/dist/index.cjs +0 -4147
- package/dist/index.d.cts +0 -1825
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/agent.js
ADDED
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
import { getFullProjectViaAPI } from "./projectFullClient.js";
|
|
2
|
+
import { updateFullAgentViaAPI } from "./agentFullClient.js";
|
|
3
|
+
import { FunctionTool } from "./function-tool.js";
|
|
4
|
+
import { getLogger } from "@inkeep/agents-core";
|
|
5
|
+
import { convertZodToJsonSchema, isZodSchema } from "@inkeep/agents-core/utils/schema-conversion";
|
|
6
|
+
|
|
7
|
+
//#region src/agent.ts
|
|
8
|
+
const logger = getLogger("agent");
|
|
9
|
+
function resolveGetter(value) {
|
|
10
|
+
if (typeof value === "function") return value();
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
var Agent = class {
|
|
14
|
+
subAgents = [];
|
|
15
|
+
agentMap = /* @__PURE__ */ new Map();
|
|
16
|
+
defaultSubAgent;
|
|
17
|
+
baseURL;
|
|
18
|
+
tenantId;
|
|
19
|
+
projectId;
|
|
20
|
+
agentId;
|
|
21
|
+
agentName;
|
|
22
|
+
agentDescription;
|
|
23
|
+
initialized = false;
|
|
24
|
+
contextConfig;
|
|
25
|
+
credentials;
|
|
26
|
+
models;
|
|
27
|
+
statusUpdateSettings;
|
|
28
|
+
prompt;
|
|
29
|
+
stopWhen;
|
|
30
|
+
constructor(config) {
|
|
31
|
+
this.defaultSubAgent = config.defaultSubAgent;
|
|
32
|
+
this.tenantId = "default";
|
|
33
|
+
this.projectId = "default";
|
|
34
|
+
this.agentId = config.id;
|
|
35
|
+
this.agentName = config.name || this.agentId;
|
|
36
|
+
this.agentDescription = config.description;
|
|
37
|
+
this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
|
|
38
|
+
this.contextConfig = config.contextConfig;
|
|
39
|
+
this.credentials = resolveGetter(config.credentials);
|
|
40
|
+
this.models = config.models;
|
|
41
|
+
this.statusUpdateSettings = config.statusUpdates;
|
|
42
|
+
this.prompt = config.prompt;
|
|
43
|
+
this.stopWhen = config.stopWhen ? { transferCountIs: config.stopWhen.transferCountIs } : void 0;
|
|
44
|
+
this.subAgents = resolveGetter(config.subAgents) || [];
|
|
45
|
+
this.agentMap = new Map(this.subAgents.map((agent$1) => [agent$1.getId(), agent$1]));
|
|
46
|
+
if (this.defaultSubAgent) {
|
|
47
|
+
if (!this.subAgents.some((agent$1) => agent$1.getId() === this.defaultSubAgent?.getId())) this.subAgents.push(this.defaultSubAgent);
|
|
48
|
+
this.agentMap.set(this.defaultSubAgent.getId(), this.defaultSubAgent);
|
|
49
|
+
}
|
|
50
|
+
if (this.models) this.propagateImmediateModelSettings();
|
|
51
|
+
logger.info({
|
|
52
|
+
agentId: this.agentId,
|
|
53
|
+
tenantId: this.tenantId,
|
|
54
|
+
agentCount: this.subAgents.length,
|
|
55
|
+
defaultSubAgent: this.defaultSubAgent?.getName()
|
|
56
|
+
}, "Agent created");
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Set or update the configuration (tenantId, projectId and apiUrl)
|
|
60
|
+
* This is used by the CLI to inject configuration from inkeep.config.ts
|
|
61
|
+
*/
|
|
62
|
+
setConfig(tenantId, projectId, apiUrl) {
|
|
63
|
+
if (this.initialized) throw new Error("Cannot set config after agent has been initialized");
|
|
64
|
+
this.tenantId = tenantId;
|
|
65
|
+
this.projectId = projectId;
|
|
66
|
+
this.baseURL = apiUrl;
|
|
67
|
+
for (const subAgent of this.subAgents) {
|
|
68
|
+
if (subAgent.setContext) subAgent.setContext(tenantId, projectId, apiUrl);
|
|
69
|
+
const tools = subAgent.getTools();
|
|
70
|
+
for (const [_, toolInstance] of Object.entries(tools)) if (toolInstance && typeof toolInstance === "object") {
|
|
71
|
+
if ("setContext" in toolInstance && typeof toolInstance.setContext === "function") toolInstance.setContext(tenantId, projectId, apiUrl);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (this.contextConfig?.setContext) this.contextConfig.setContext(tenantId, projectId, this.agentId, this.baseURL);
|
|
75
|
+
logger.info({
|
|
76
|
+
agentId: this.agentId,
|
|
77
|
+
tenantId: this.tenantId,
|
|
78
|
+
projectId: this.projectId,
|
|
79
|
+
apiUrl: this.baseURL
|
|
80
|
+
}, "Agent configuration updated");
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Convert the Agent to FullAgentDefinition format for the new agent endpoint
|
|
84
|
+
*/
|
|
85
|
+
async toFullAgentDefinition() {
|
|
86
|
+
const subAgentsObject = {};
|
|
87
|
+
const externalAgentsObject = {};
|
|
88
|
+
const functionToolsObject = {};
|
|
89
|
+
const functionsObject = {};
|
|
90
|
+
for (const subAgent of this.subAgents) {
|
|
91
|
+
const transfers = subAgent.getTransfers();
|
|
92
|
+
const delegates = subAgent.getDelegates();
|
|
93
|
+
const tools = [];
|
|
94
|
+
const selectedToolsMapping = {};
|
|
95
|
+
const headersMapping = {};
|
|
96
|
+
const toolPoliciesMapping = {};
|
|
97
|
+
const subAgentTools = subAgent.getTools();
|
|
98
|
+
for (const [_toolName, toolInstance] of Object.entries(subAgentTools)) {
|
|
99
|
+
const toolId = toolInstance.getId();
|
|
100
|
+
if (toolInstance.selectedTools) selectedToolsMapping[toolId] = toolInstance.selectedTools;
|
|
101
|
+
if (toolInstance.headers) headersMapping[toolId] = toolInstance.headers;
|
|
102
|
+
if (toolInstance.toolPolicies) toolPoliciesMapping[toolId] = toolInstance.toolPolicies;
|
|
103
|
+
tools.push(toolId);
|
|
104
|
+
if (toolInstance.constructor.name === "FunctionTool" && toolInstance instanceof FunctionTool) {
|
|
105
|
+
if (!functionsObject[toolId]) functionsObject[toolId] = toolInstance.serializeFunction();
|
|
106
|
+
if (!functionToolsObject[toolId]) {
|
|
107
|
+
const toolData = toolInstance.serializeTool();
|
|
108
|
+
functionToolsObject[toolId] = {
|
|
109
|
+
id: toolData.id,
|
|
110
|
+
name: toolData.name,
|
|
111
|
+
description: toolData.description,
|
|
112
|
+
functionId: toolData.functionId,
|
|
113
|
+
agentId: this.agentId
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const subAgentExternalAgents = subAgent.getExternalAgentDelegates();
|
|
119
|
+
for (const externalAgentDelegate of subAgentExternalAgents) {
|
|
120
|
+
const externalAgent = externalAgentDelegate.externalAgent;
|
|
121
|
+
externalAgentsObject[externalAgent.getId()] = {
|
|
122
|
+
id: externalAgent.getId(),
|
|
123
|
+
name: externalAgent.getName(),
|
|
124
|
+
description: externalAgent.getDescription(),
|
|
125
|
+
baseUrl: externalAgent.getBaseUrl(),
|
|
126
|
+
credentialReferenceId: externalAgent.getCredentialReferenceId(),
|
|
127
|
+
type: "external"
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const dataComponents = [];
|
|
131
|
+
const subAgentDataComponents = subAgent.getDataComponents();
|
|
132
|
+
if (subAgentDataComponents) for (const dataComponent of subAgentDataComponents) {
|
|
133
|
+
const dataComponentId = dataComponent.id || dataComponent.name.toLowerCase().replace(/\s+/g, "-");
|
|
134
|
+
dataComponents.push(dataComponentId);
|
|
135
|
+
}
|
|
136
|
+
const artifactComponents = [];
|
|
137
|
+
const subAgentArtifactComponents = subAgent.getArtifactComponents();
|
|
138
|
+
if (subAgentArtifactComponents) for (const artifactComponent of subAgentArtifactComponents) {
|
|
139
|
+
const artifactComponentId = artifactComponent.id || artifactComponent.name.toLowerCase().replace(/\s+/g, "-");
|
|
140
|
+
artifactComponents.push(artifactComponentId);
|
|
141
|
+
}
|
|
142
|
+
const canUse = tools.map((toolId) => ({
|
|
143
|
+
toolId,
|
|
144
|
+
toolSelection: selectedToolsMapping[toolId] || null,
|
|
145
|
+
headers: headersMapping[toolId] || null,
|
|
146
|
+
toolPolicies: toolPoliciesMapping[toolId] || null
|
|
147
|
+
}));
|
|
148
|
+
subAgentsObject[subAgent.getId()] = {
|
|
149
|
+
id: subAgent.getId(),
|
|
150
|
+
name: subAgent.getName(),
|
|
151
|
+
description: subAgent.config.description || "",
|
|
152
|
+
prompt: subAgent.getInstructions(),
|
|
153
|
+
models: subAgent.config.models,
|
|
154
|
+
stopWhen: subAgent.config.stopWhen,
|
|
155
|
+
canTransferTo: transfers.map((h) => h.getId()),
|
|
156
|
+
canDelegateTo: delegates.map((d) => {
|
|
157
|
+
if (typeof d === "object" && "externalAgent" in d) return {
|
|
158
|
+
externalAgentId: d.externalAgent.getId(),
|
|
159
|
+
...d.headers && { headers: d.headers }
|
|
160
|
+
};
|
|
161
|
+
if (typeof d === "object" && "agent" in d) return {
|
|
162
|
+
agentId: d.agent.getId(),
|
|
163
|
+
...d.headers && { headers: d.headers }
|
|
164
|
+
};
|
|
165
|
+
return d.getId();
|
|
166
|
+
}),
|
|
167
|
+
canUse,
|
|
168
|
+
dataComponents: dataComponents.length > 0 ? dataComponents : void 0,
|
|
169
|
+
artifactComponents: artifactComponents.length > 0 ? artifactComponents : void 0,
|
|
170
|
+
type: "internal"
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
const processedStatusUpdates = this.statusUpdateSettings ? {
|
|
174
|
+
...this.statusUpdateSettings,
|
|
175
|
+
statusComponents: this.statusUpdateSettings.statusComponents?.map((comp) => {
|
|
176
|
+
if (comp && typeof comp.getType === "function") return {
|
|
177
|
+
type: comp.getType(),
|
|
178
|
+
description: comp.getDescription(),
|
|
179
|
+
detailsSchema: comp.getDetailsSchema()
|
|
180
|
+
};
|
|
181
|
+
if (comp && typeof comp === "object" && comp.detailsSchema && isZodSchema(comp.detailsSchema)) {
|
|
182
|
+
const jsonSchema = convertZodToJsonSchema(comp.detailsSchema);
|
|
183
|
+
return {
|
|
184
|
+
type: comp.type,
|
|
185
|
+
description: comp.description,
|
|
186
|
+
detailsSchema: {
|
|
187
|
+
type: "object",
|
|
188
|
+
properties: jsonSchema.properties || {},
|
|
189
|
+
required: jsonSchema.required || void 0
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return comp;
|
|
194
|
+
})
|
|
195
|
+
} : void 0;
|
|
196
|
+
const agentToolsObject = {};
|
|
197
|
+
for (const subAgent of this.subAgents) {
|
|
198
|
+
const subAgentTools = subAgent.getTools();
|
|
199
|
+
for (const [_toolName, toolInstance] of Object.entries(subAgentTools)) {
|
|
200
|
+
const toolId = toolInstance.getId();
|
|
201
|
+
if (toolInstance.constructor.name !== "FunctionTool") {
|
|
202
|
+
if (!agentToolsObject[toolId]) {
|
|
203
|
+
if ("config" in toolInstance && "serverUrl" in toolInstance.config) {
|
|
204
|
+
const mcpTool = toolInstance;
|
|
205
|
+
agentToolsObject[toolId] = {
|
|
206
|
+
id: toolId,
|
|
207
|
+
name: toolInstance.getName(),
|
|
208
|
+
description: null,
|
|
209
|
+
config: {
|
|
210
|
+
type: "mcp",
|
|
211
|
+
mcp: {
|
|
212
|
+
server: { url: mcpTool.config.serverUrl },
|
|
213
|
+
transport: mcpTool.config.transport,
|
|
214
|
+
activeTools: mcpTool.config.activeTools
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
credentialReferenceId: null
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
id: this.agentId,
|
|
226
|
+
name: this.agentName,
|
|
227
|
+
description: this.agentDescription,
|
|
228
|
+
defaultSubAgentId: this.defaultSubAgent?.getId() || "",
|
|
229
|
+
subAgents: subAgentsObject,
|
|
230
|
+
externalAgents: externalAgentsObject,
|
|
231
|
+
contextConfig: this.contextConfig?.toObject(),
|
|
232
|
+
...Object.keys(functionToolsObject).length > 0 && { functionTools: functionToolsObject },
|
|
233
|
+
...Object.keys(functionsObject).length > 0 && { functions: functionsObject },
|
|
234
|
+
models: this.models,
|
|
235
|
+
stopWhen: this.stopWhen,
|
|
236
|
+
statusUpdates: processedStatusUpdates,
|
|
237
|
+
prompt: this.prompt,
|
|
238
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
239
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Initialize all tools in all agents (especially IPCTools that need MCP server URLs)
|
|
244
|
+
*/
|
|
245
|
+
async initializeAllTools() {
|
|
246
|
+
logger.info({ agentId: this.agentId }, "Initializing all tools in agent");
|
|
247
|
+
const toolInitPromises = [];
|
|
248
|
+
for (const subAgent of this.subAgents) {
|
|
249
|
+
const agentTools = subAgent.getTools();
|
|
250
|
+
for (const [toolName, toolInstance] of Object.entries(agentTools)) if (toolInstance && typeof toolInstance === "object") {
|
|
251
|
+
if (typeof toolInstance.init === "function") toolInitPromises.push((async () => {
|
|
252
|
+
try {
|
|
253
|
+
const skipDbRegistration = toolInstance.constructor.name === "IPCTool" || toolInstance.constructor.name === "HostedTool" || toolInstance.constructor.name === "Tool";
|
|
254
|
+
if (typeof toolInstance.init === "function") if (skipDbRegistration) await toolInstance.init({ skipDatabaseRegistration: true });
|
|
255
|
+
else await toolInstance.init();
|
|
256
|
+
logger.debug({
|
|
257
|
+
subAgentId: subAgent.getId(),
|
|
258
|
+
toolName,
|
|
259
|
+
toolType: toolInstance.constructor.name,
|
|
260
|
+
skipDbRegistration
|
|
261
|
+
}, "Tool initialized successfully");
|
|
262
|
+
} catch (error) {
|
|
263
|
+
logger.error({
|
|
264
|
+
subAgentId: subAgent.getId(),
|
|
265
|
+
toolName,
|
|
266
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
267
|
+
}, "Failed to initialize tool");
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
})());
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
await Promise.all(toolInitPromises);
|
|
274
|
+
logger.info({
|
|
275
|
+
agentId: this.agentId,
|
|
276
|
+
toolCount: toolInitPromises.length
|
|
277
|
+
}, "All tools initialized successfully");
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Initialize the agent and all agents in the backend using the new agent endpoint
|
|
281
|
+
*/
|
|
282
|
+
async init() {
|
|
283
|
+
if (this.initialized) {
|
|
284
|
+
logger.info({ agentId: this.agentId }, "Agent already initialized");
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
logger.info({
|
|
288
|
+
agentId: this.agentId,
|
|
289
|
+
agentCount: this.subAgents.length
|
|
290
|
+
}, "Initializing agent using new agent endpoint");
|
|
291
|
+
try {
|
|
292
|
+
await this.initializeAllTools();
|
|
293
|
+
await this.applyModelInheritance();
|
|
294
|
+
const agentDefinition = await this.toFullAgentDefinition();
|
|
295
|
+
logger.info({
|
|
296
|
+
agentId: this.agentId,
|
|
297
|
+
mode: "api-client",
|
|
298
|
+
apiUrl: this.baseURL
|
|
299
|
+
}, "Using API client to create/update agent");
|
|
300
|
+
const createdAgent = await updateFullAgentViaAPI(this.tenantId, this.projectId, this.baseURL, this.agentId, agentDefinition);
|
|
301
|
+
logger.info({
|
|
302
|
+
agentId: this.agentId,
|
|
303
|
+
agentCount: Object.keys(createdAgent.subAgents || {}).length
|
|
304
|
+
}, "Agent initialized successfully using agent endpoint");
|
|
305
|
+
this.initialized = true;
|
|
306
|
+
} catch (error) {
|
|
307
|
+
logger.error({
|
|
308
|
+
agentId: this.agentId,
|
|
309
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
310
|
+
}, "Failed to initialize agent using agent endpoint");
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Generate a response using the default agent
|
|
316
|
+
*/
|
|
317
|
+
async generate(input, options) {
|
|
318
|
+
await this._init();
|
|
319
|
+
if (!this.defaultSubAgent) throw new Error("No default agent configured for this agent");
|
|
320
|
+
logger.info({
|
|
321
|
+
agentId: this.agentId,
|
|
322
|
+
defaultSubAgent: this.defaultSubAgent.getName(),
|
|
323
|
+
conversationId: options?.conversationId
|
|
324
|
+
}, "Generating response with default agent");
|
|
325
|
+
return await this.executeWithBackend(input, options);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Stream a response using the default agent
|
|
329
|
+
*/
|
|
330
|
+
async stream(input, options) {
|
|
331
|
+
await this._init();
|
|
332
|
+
if (!this.defaultSubAgent) throw new Error("No default agent configured for this agent");
|
|
333
|
+
logger.info({
|
|
334
|
+
agentId: this.agentId,
|
|
335
|
+
defaultSubAgent: this.defaultSubAgent.getName(),
|
|
336
|
+
conversationId: options?.conversationId
|
|
337
|
+
}, "Streaming response with default agent");
|
|
338
|
+
const textStream = async function* (agent$1) {
|
|
339
|
+
const words = (await agent$1.executeWithBackend(input, options)).split(" ");
|
|
340
|
+
for (const word of words) yield `${word} `;
|
|
341
|
+
};
|
|
342
|
+
return { textStream: textStream(this) };
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Alias for stream() method for consistency with naming patterns
|
|
346
|
+
*/
|
|
347
|
+
async generateStream(input, options) {
|
|
348
|
+
return await this.stream(input, options);
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Run with a specific agent from the agent
|
|
352
|
+
*/
|
|
353
|
+
async runWith(subAgentId, input, options) {
|
|
354
|
+
await this._init();
|
|
355
|
+
const agent$1 = this.getSubAgent(subAgentId);
|
|
356
|
+
if (!agent$1) throw new Error(`Agent '${subAgentId}' not found in agent`);
|
|
357
|
+
logger.info({
|
|
358
|
+
agentId: this.agentId,
|
|
359
|
+
subAgentId,
|
|
360
|
+
conversationId: options?.conversationId
|
|
361
|
+
}, "Running with specific agent");
|
|
362
|
+
return {
|
|
363
|
+
finalOutput: await this.executeWithBackend(input, options),
|
|
364
|
+
agent: agent$1,
|
|
365
|
+
turnCount: 1,
|
|
366
|
+
usage: {
|
|
367
|
+
inputTokens: 0,
|
|
368
|
+
outputTokens: 0
|
|
369
|
+
},
|
|
370
|
+
metadata: {
|
|
371
|
+
toolCalls: [],
|
|
372
|
+
transfers: []
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Get an agent by name (unified method for all agent types)
|
|
378
|
+
*/
|
|
379
|
+
getSubAgent(name) {
|
|
380
|
+
return this.agentMap.get(name);
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Add an agent to the agent
|
|
384
|
+
*/
|
|
385
|
+
addSubAgent(agent$1) {
|
|
386
|
+
this.subAgents.push(agent$1);
|
|
387
|
+
this.agentMap.set(agent$1.getId(), agent$1);
|
|
388
|
+
if (this.models) this.propagateModelSettingsToAgent(agent$1);
|
|
389
|
+
logger.info({
|
|
390
|
+
agentId: this.agentId,
|
|
391
|
+
subAgentId: agent$1.getId()
|
|
392
|
+
}, "SubAgent added to agent");
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Remove an agent from the agent
|
|
396
|
+
*/
|
|
397
|
+
removeSubAgent(id) {
|
|
398
|
+
const agentToRemove = this.agentMap.get(id);
|
|
399
|
+
if (agentToRemove) {
|
|
400
|
+
this.agentMap.delete(agentToRemove.getId());
|
|
401
|
+
this.subAgents = this.subAgents.filter((agent$1) => agent$1.getId() !== agentToRemove.getId());
|
|
402
|
+
logger.info({
|
|
403
|
+
agentId: this.agentId,
|
|
404
|
+
subAgentId: agentToRemove.getId()
|
|
405
|
+
}, "Agent removed from agent");
|
|
406
|
+
return true;
|
|
407
|
+
}
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Get all agents in the agent
|
|
412
|
+
*/
|
|
413
|
+
getSubAgents() {
|
|
414
|
+
return this.subAgents;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Get all agent ids (unified method for all agent types)
|
|
418
|
+
*/
|
|
419
|
+
getSubAgentIds() {
|
|
420
|
+
return Array.from(this.agentMap.keys());
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Set the default agent
|
|
424
|
+
*/
|
|
425
|
+
setDefaultSubAgent(agent$1) {
|
|
426
|
+
this.defaultSubAgent = agent$1;
|
|
427
|
+
this.addSubAgent(agent$1);
|
|
428
|
+
logger.info({
|
|
429
|
+
agentId: this.agentId,
|
|
430
|
+
defaultSubAgent: agent$1.getId()
|
|
431
|
+
}, "Default agent updated");
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Get the default agent
|
|
435
|
+
*/
|
|
436
|
+
getDefaultSubAgent() {
|
|
437
|
+
return this.defaultSubAgent;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Get the agent ID
|
|
441
|
+
*/
|
|
442
|
+
getId() {
|
|
443
|
+
return this.agentId;
|
|
444
|
+
}
|
|
445
|
+
getName() {
|
|
446
|
+
return this.agentName;
|
|
447
|
+
}
|
|
448
|
+
getDescription() {
|
|
449
|
+
return this.agentDescription;
|
|
450
|
+
}
|
|
451
|
+
getTenantId() {
|
|
452
|
+
return this.tenantId;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Get the agent's model settingsuration
|
|
456
|
+
*/
|
|
457
|
+
getModels() {
|
|
458
|
+
return this.models;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Set the agent's model settingsuration
|
|
462
|
+
*/
|
|
463
|
+
setModels(models) {
|
|
464
|
+
this.models = models;
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Get the agent's prompt configuration
|
|
468
|
+
*/
|
|
469
|
+
getPrompt() {
|
|
470
|
+
return this.prompt;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Get the agent's stopWhen configuration
|
|
474
|
+
*/
|
|
475
|
+
getStopWhen() {
|
|
476
|
+
return this.stopWhen || { transferCountIs: 10 };
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Get the agent's status updates configuration
|
|
480
|
+
*/
|
|
481
|
+
getStatusUpdateSettings() {
|
|
482
|
+
return this.statusUpdateSettings;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Get the summarizer model from the agent's model settings
|
|
486
|
+
*/
|
|
487
|
+
getSummarizerModel() {
|
|
488
|
+
return this.models?.summarizer;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Get agent statistics
|
|
492
|
+
*/
|
|
493
|
+
getStats() {
|
|
494
|
+
return {
|
|
495
|
+
agentCount: this.subAgents.length,
|
|
496
|
+
defaultSubAgent: this.defaultSubAgent?.getName() || null,
|
|
497
|
+
initialized: this.initialized,
|
|
498
|
+
agentId: this.agentId,
|
|
499
|
+
tenantId: this.tenantId
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
with(options) {
|
|
503
|
+
return {
|
|
504
|
+
agent: this,
|
|
505
|
+
headers: options.headers
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Validate the agent configuration
|
|
510
|
+
*/
|
|
511
|
+
validate() {
|
|
512
|
+
const errors = [];
|
|
513
|
+
if (this.subAgents.length === 0) errors.push("Agent must contain at least one agent");
|
|
514
|
+
if (!this.defaultSubAgent) errors.push("Agent must have a default agent");
|
|
515
|
+
const names = /* @__PURE__ */ new Set();
|
|
516
|
+
for (const subAgent of this.subAgents) {
|
|
517
|
+
const name = subAgent.getName();
|
|
518
|
+
if (names.has(name)) errors.push(`Duplicate agent name: ${name}`);
|
|
519
|
+
names.add(name);
|
|
520
|
+
}
|
|
521
|
+
for (const subAgent of this.subAgents) {
|
|
522
|
+
const transfers = subAgent.getTransfers();
|
|
523
|
+
for (const transferAgent of transfers) if (!this.agentMap.has(transferAgent.getName())) errors.push(`Agent '${subAgent.getName()}' has transfer to '${transferAgent.getName()}' which is not in the agent`);
|
|
524
|
+
const delegates = subAgent.getDelegates();
|
|
525
|
+
for (const delegateAgent of delegates) if (this.isInternalAgent(delegateAgent)) {
|
|
526
|
+
if (!this.agentMap.has(delegateAgent.getName())) errors.push(`Agent '${subAgent.getName()}' has delegation to '${delegateAgent.getName()}' which is not in the agent`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return {
|
|
530
|
+
valid: errors.length === 0,
|
|
531
|
+
errors
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
async _init() {
|
|
535
|
+
if (!this.initialized) await this.init();
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Type guard to check if an agent is an internal AgentInterface
|
|
539
|
+
*/
|
|
540
|
+
isInternalAgent(agent$1) {
|
|
541
|
+
return "getTransfers" in agent$1 && typeof agent$1.getTransfers === "function";
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Get project-level model settingsuration defaults
|
|
545
|
+
*/
|
|
546
|
+
async getProjectModelDefaults() {
|
|
547
|
+
try {
|
|
548
|
+
return (await getFullProjectViaAPI(this.tenantId, this.projectId, this.baseURL))?.models;
|
|
549
|
+
} catch (error) {
|
|
550
|
+
logger.warn({
|
|
551
|
+
tenantId: this.tenantId,
|
|
552
|
+
projectId: this.projectId,
|
|
553
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
554
|
+
}, "Failed to get project model defaults");
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Get project-level stopWhen configuration defaults
|
|
560
|
+
*/
|
|
561
|
+
async getProjectStopWhenDefaults() {
|
|
562
|
+
try {
|
|
563
|
+
return (await getFullProjectViaAPI(this.tenantId, this.projectId, this.baseURL))?.stopWhen;
|
|
564
|
+
} catch (error) {
|
|
565
|
+
logger.warn({
|
|
566
|
+
tenantId: this.tenantId,
|
|
567
|
+
projectId: this.projectId,
|
|
568
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
569
|
+
}, "Failed to get project stopWhen defaults");
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Apply model inheritance hierarchy: Project -> Agent -> Agent
|
|
575
|
+
*/
|
|
576
|
+
async applyModelInheritance() {
|
|
577
|
+
const projectModels = await this.getProjectModelDefaults();
|
|
578
|
+
if (projectModels) {
|
|
579
|
+
if (!this.models) this.models = {};
|
|
580
|
+
if (!this.models.base && projectModels.base) this.models.base = projectModels.base;
|
|
581
|
+
if (!this.models.structuredOutput && projectModels.structuredOutput) this.models.structuredOutput = projectModels.structuredOutput;
|
|
582
|
+
if (!this.models.summarizer && projectModels.summarizer) this.models.summarizer = projectModels.summarizer;
|
|
583
|
+
}
|
|
584
|
+
await this.applyStopWhenInheritance();
|
|
585
|
+
for (const subAgent of this.subAgents) this.propagateModelSettingsToAgent(subAgent);
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Apply stopWhen inheritance hierarchy: Project -> Agent -> Agent
|
|
589
|
+
*/
|
|
590
|
+
async applyStopWhenInheritance() {
|
|
591
|
+
const projectStopWhen = await this.getProjectStopWhenDefaults();
|
|
592
|
+
if (!this.stopWhen) this.stopWhen = {};
|
|
593
|
+
if (this.stopWhen.transferCountIs === void 0 && projectStopWhen?.transferCountIs !== void 0) this.stopWhen.transferCountIs = projectStopWhen.transferCountIs;
|
|
594
|
+
if (this.stopWhen.transferCountIs === void 0) this.stopWhen.transferCountIs = 10;
|
|
595
|
+
if (projectStopWhen?.stepCountIs !== void 0) for (const subAgent of this.subAgents) {
|
|
596
|
+
if (!subAgent.config.stopWhen) subAgent.config.stopWhen = {};
|
|
597
|
+
if (subAgent.config.stopWhen.stepCountIs === void 0) subAgent.config.stopWhen.stepCountIs = projectStopWhen.stepCountIs;
|
|
598
|
+
}
|
|
599
|
+
logger.debug({
|
|
600
|
+
agentId: this.agentId,
|
|
601
|
+
agentStopWhen: this.stopWhen,
|
|
602
|
+
projectStopWhen
|
|
603
|
+
}, "Applied stopWhen inheritance from project to agent");
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Propagate agent-level model settings to agents (supporting partial inheritance)
|
|
607
|
+
*/
|
|
608
|
+
propagateModelSettingsToAgent(agent$1) {
|
|
609
|
+
if (this.models) {
|
|
610
|
+
if (!agent$1.config.models) agent$1.config.models = {};
|
|
611
|
+
if (!agent$1.config.models.base && this.models.base) agent$1.config.models.base = this.models.base;
|
|
612
|
+
if (!agent$1.config.models.structuredOutput && this.models.structuredOutput) agent$1.config.models.structuredOutput = this.models.structuredOutput;
|
|
613
|
+
if (!agent$1.config.models.summarizer && this.models.summarizer) agent$1.config.models.summarizer = this.models.summarizer;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Immediately propagate agent-level models to all agents during construction
|
|
618
|
+
*/
|
|
619
|
+
propagateImmediateModelSettings() {
|
|
620
|
+
for (const subAgent of this.subAgents) this.propagateModelSettingsToAgent(subAgent);
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Execute agent using the backend system instead of local runner
|
|
624
|
+
*/
|
|
625
|
+
async executeWithBackend(input, options) {
|
|
626
|
+
const normalizedMessages = this.normalizeMessages(input);
|
|
627
|
+
const url = `${this.baseURL}/tenants/${this.tenantId}/agent/${this.agentId}/v1/chat/completions`;
|
|
628
|
+
logger.info({ url }, "Executing with backend");
|
|
629
|
+
const requestBody = {
|
|
630
|
+
model: "gpt-4o-mini",
|
|
631
|
+
messages: normalizedMessages.map((msg) => ({
|
|
632
|
+
role: msg.role,
|
|
633
|
+
content: msg.content
|
|
634
|
+
})),
|
|
635
|
+
...options,
|
|
636
|
+
...options?.conversationId && { conversationId: options.conversationId },
|
|
637
|
+
...options?.customBodyParams && { ...options.customBodyParams },
|
|
638
|
+
stream: false
|
|
639
|
+
};
|
|
640
|
+
try {
|
|
641
|
+
const response = await fetch(url, {
|
|
642
|
+
method: "POST",
|
|
643
|
+
headers: {
|
|
644
|
+
"Content-Type": "application/json",
|
|
645
|
+
Accept: "application/json"
|
|
646
|
+
},
|
|
647
|
+
body: JSON.stringify(requestBody)
|
|
648
|
+
});
|
|
649
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
650
|
+
const responseText = await response.text();
|
|
651
|
+
if (responseText.startsWith("data:")) return this.parseStreamingResponse(responseText);
|
|
652
|
+
const data = JSON.parse(responseText);
|
|
653
|
+
return data.result || data.choices?.[0]?.message?.content || "";
|
|
654
|
+
} catch (error) {
|
|
655
|
+
throw new Error(`Agent execution failed: ${error.message || "Unknown error"}`);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Parse streaming response in SSE format
|
|
660
|
+
*/
|
|
661
|
+
parseStreamingResponse(text) {
|
|
662
|
+
const lines = text.split("\n");
|
|
663
|
+
let content = "";
|
|
664
|
+
for (const line of lines) if (line.startsWith("data: ")) {
|
|
665
|
+
const dataStr = line.slice(6);
|
|
666
|
+
if (dataStr === "[DONE]") break;
|
|
667
|
+
try {
|
|
668
|
+
const delta = JSON.parse(dataStr).choices?.[0]?.delta?.content;
|
|
669
|
+
if (delta) content += delta;
|
|
670
|
+
} catch (_e) {}
|
|
671
|
+
}
|
|
672
|
+
return content;
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Normalize input messages to the expected format
|
|
676
|
+
*/
|
|
677
|
+
normalizeMessages(input) {
|
|
678
|
+
if (typeof input === "string") return [{
|
|
679
|
+
role: "user",
|
|
680
|
+
content: input
|
|
681
|
+
}];
|
|
682
|
+
if (Array.isArray(input)) return input.map((msg) => typeof msg === "string" ? {
|
|
683
|
+
role: "user",
|
|
684
|
+
content: msg
|
|
685
|
+
} : msg);
|
|
686
|
+
return [input];
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
/**
|
|
690
|
+
* Helper function to create agent - OpenAI style
|
|
691
|
+
*/
|
|
692
|
+
function agent(config) {
|
|
693
|
+
return new Agent(config);
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Factory function to create agent from configuration file
|
|
697
|
+
*/
|
|
698
|
+
async function generateAgent(configPath) {
|
|
699
|
+
logger.info({ configPath }, "Loading agent configuration");
|
|
700
|
+
try {
|
|
701
|
+
const config = await import(configPath);
|
|
702
|
+
const agentObject = agent(config.default || config);
|
|
703
|
+
await agentObject.init();
|
|
704
|
+
logger.info({
|
|
705
|
+
configPath,
|
|
706
|
+
agentId: agentObject.getStats().agentId,
|
|
707
|
+
agentCount: agentObject.getStats().agentCount
|
|
708
|
+
}, "Agent generated successfully");
|
|
709
|
+
return agentObject;
|
|
710
|
+
} catch (error) {
|
|
711
|
+
logger.error({
|
|
712
|
+
configPath,
|
|
713
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
714
|
+
}, "Failed to generate agent from configuration");
|
|
715
|
+
throw error;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
//#endregion
|
|
720
|
+
export { Agent, agent, generateAgent };
|