@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.
Files changed (59) hide show
  1. package/dist/_virtual/rolldown_runtime.js +7 -0
  2. package/dist/agent.d.ts +186 -0
  3. package/dist/agent.js +720 -0
  4. package/dist/agentFullClient.d.ts +22 -0
  5. package/dist/agentFullClient.js +120 -0
  6. package/dist/artifact-component.d.ts +34 -0
  7. package/dist/artifact-component.js +104 -0
  8. package/dist/builderFunctions.d.ts +283 -0
  9. package/dist/builderFunctions.js +327 -0
  10. package/dist/builderFunctionsExperimental.d.ts +24 -0
  11. package/dist/builderFunctionsExperimental.js +27 -0
  12. package/dist/builders.d.ts +111 -0
  13. package/dist/builders.js +52 -0
  14. package/dist/credential-provider.d.ts +176 -0
  15. package/dist/credential-provider.js +237 -0
  16. package/dist/credential-ref.d.ts +60 -0
  17. package/dist/credential-ref.js +33 -0
  18. package/dist/data-component.d.ts +39 -0
  19. package/dist/data-component.js +109 -0
  20. package/dist/environment-settings.d.ts +27 -0
  21. package/dist/environment-settings.js +41 -0
  22. package/dist/external-agent.d.ts +64 -0
  23. package/dist/external-agent.js +156 -0
  24. package/dist/function-tool.d.ts +37 -0
  25. package/dist/function-tool.js +66 -0
  26. package/dist/index.d.ts +19 -1825
  27. package/dist/index.js +19 -4058
  28. package/dist/module-hosted-tool-manager.d.ts +40 -0
  29. package/dist/module-hosted-tool-manager.js +359 -0
  30. package/dist/project.d.ts +214 -0
  31. package/dist/project.js +615 -0
  32. package/dist/projectFullClient.d.ts +23 -0
  33. package/dist/projectFullClient.js +162 -0
  34. package/dist/runner.d.ts +41 -0
  35. package/dist/runner.js +145 -0
  36. package/dist/status-component.d.ts +22 -0
  37. package/dist/status-component.js +36 -0
  38. package/dist/subAgent.d.ts +52 -0
  39. package/dist/subAgent.js +616 -0
  40. package/dist/telemetry-provider.d.ts +218 -0
  41. package/dist/telemetry-provider.js +390 -0
  42. package/dist/tool.d.ts +53 -0
  43. package/dist/tool.js +130 -0
  44. package/dist/types.d.ts +296 -0
  45. package/dist/types.js +39 -0
  46. package/dist/utils/generateIdFromName.d.ts +9 -0
  47. package/dist/utils/generateIdFromName.js +12 -0
  48. package/dist/utils/getFunctionToolDeps.d.ts +17 -0
  49. package/dist/utils/getFunctionToolDeps.js +131 -0
  50. package/dist/utils/tool-normalization.d.ts +42 -0
  51. package/dist/utils/tool-normalization.js +41 -0
  52. package/dist/utils/validateFunction.d.ts +10 -0
  53. package/dist/utils/validateFunction.js +13 -0
  54. package/package.json +11 -16
  55. package/dist/index.cjs +0 -4147
  56. package/dist/index.d.cts +0 -1825
  57. package/dist/index.d.cts.map +0 -1
  58. package/dist/index.d.ts.map +0 -1
  59. package/dist/index.js.map +0 -1
package/dist/index.cjs DELETED
@@ -1,4147 +0,0 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
28
- let __inkeep_agents_core = require("@inkeep/agents-core");
29
- let __inkeep_agents_core_utils_schema_conversion = require("@inkeep/agents-core/utils/schema-conversion");
30
- let node_fs = require("node:fs");
31
- node_fs = __toESM(node_fs);
32
- let node_module = require("node:module");
33
- let node_path = require("node:path");
34
- node_path = __toESM(node_path);
35
- let __yarnpkg_lockfile = require("@yarnpkg/lockfile");
36
- __yarnpkg_lockfile = __toESM(__yarnpkg_lockfile);
37
- let js_yaml = require("js-yaml");
38
- js_yaml = __toESM(js_yaml);
39
- let typescript = require("typescript");
40
- typescript = __toESM(typescript);
41
- let zod = require("zod");
42
-
43
- //#region src/utils/generateIdFromName.ts
44
- /**
45
- * Generates a kebab-case ID from a name string
46
- * @param name - The name to convert
47
- * @returns A kebab-case ID
48
- */
49
- function generateIdFromName(name) {
50
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
51
- }
52
-
53
- //#endregion
54
- //#region src/artifact-component.ts
55
- const logger$12 = (0, __inkeep_agents_core.getLogger)("artifactComponent");
56
- var ArtifactComponent = class {
57
- config;
58
- baseURL;
59
- tenantId;
60
- projectId;
61
- initialized = false;
62
- id;
63
- constructor(config) {
64
- this.id = config.id || generateIdFromName(config.name);
65
- let processedProps;
66
- if (config.props && (0, __inkeep_agents_core_utils_schema_conversion.isZodSchema)(config.props)) processedProps = (0, __inkeep_agents_core_utils_schema_conversion.convertZodToJsonSchemaWithPreview)(config.props);
67
- else processedProps = config.props;
68
- this.config = {
69
- ...config,
70
- id: this.id,
71
- props: processedProps
72
- };
73
- this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
74
- this.tenantId = "default";
75
- this.projectId = "default";
76
- logger$12.info({
77
- artifactComponentId: this.getId(),
78
- artifactComponentName: config.name
79
- }, "ArtifactComponent constructor initialized");
80
- }
81
- setContext(tenantId, projectId, baseURL) {
82
- this.tenantId = tenantId;
83
- this.projectId = projectId;
84
- if (baseURL) this.baseURL = baseURL;
85
- }
86
- getId() {
87
- return this.id;
88
- }
89
- getName() {
90
- return this.config.name;
91
- }
92
- getDescription() {
93
- return this.config.description || "";
94
- }
95
- getProps() {
96
- return this.config.props;
97
- }
98
- async init() {
99
- if (this.initialized) return;
100
- try {
101
- await this.upsertArtifactComponent();
102
- logger$12.info({ artifactComponentId: this.getId() }, "ArtifactComponent initialized successfully");
103
- this.initialized = true;
104
- } catch (error) {
105
- logger$12.error({
106
- artifactComponentId: this.getId(),
107
- error: error instanceof Error ? error.message : "Unknown error"
108
- }, "Failed to initialize artifact component");
109
- throw error;
110
- }
111
- }
112
- async upsertArtifactComponent() {
113
- const artifactComponentData = {
114
- id: this.getId(),
115
- name: this.config.name,
116
- description: this.config.description,
117
- props: this.config.props
118
- };
119
- logger$12.info({ artifactComponentData }, "artifactComponentData for create/update");
120
- const updateResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/artifact-components/${this.getId()}`, {
121
- method: "PUT",
122
- headers: { "Content-Type": "application/json" },
123
- body: JSON.stringify(artifactComponentData)
124
- });
125
- logger$12.info({
126
- status: updateResponse.status,
127
- artifactComponentId: this.getId()
128
- }, "artifact component updateResponse");
129
- if (updateResponse.ok) {
130
- logger$12.info({ artifactComponentId: this.getId() }, "ArtifactComponent updated successfully");
131
- return;
132
- }
133
- if (updateResponse.status === 404) {
134
- logger$12.info({ artifactComponentId: this.getId() }, "ArtifactComponent not found, creating new artifact component");
135
- const createResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/artifact-components`, {
136
- method: "POST",
137
- headers: { "Content-Type": "application/json" },
138
- body: JSON.stringify(artifactComponentData)
139
- });
140
- if (!createResponse.ok) {
141
- const errorText$1 = await createResponse.text().catch(() => "Unknown error");
142
- throw new Error(`Failed to create artifact component: ${createResponse.status} ${createResponse.statusText} - ${errorText$1}`);
143
- }
144
- logger$12.info({ artifactComponentId: this.getId() }, "ArtifactComponent created successfully");
145
- return;
146
- }
147
- const errorText = await updateResponse.text().catch(() => "Unknown error");
148
- throw new Error(`Failed to update artifact component: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`);
149
- }
150
- };
151
-
152
- //#endregion
153
- //#region src/projectFullClient.ts
154
- /**
155
- * Client-side functions for interacting with the Full Project API
156
- * These functions make HTTP requests to the server instead of direct database calls
157
- */
158
- const logger$11 = (0, __inkeep_agents_core.getLogger)("projectFullClient");
159
- /**
160
- * Create a full project via HTTP API
161
- */
162
- async function createFullProjectViaAPI(tenantId, apiUrl, projectData, apiKey) {
163
- logger$11.info({
164
- tenantId,
165
- projectId: projectData.id,
166
- apiUrl
167
- }, "Creating full project via API");
168
- const url = `${apiUrl}/tenants/${tenantId}/project-full`;
169
- const headers = {};
170
- if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
171
- let response;
172
- try {
173
- response = await (0, __inkeep_agents_core.apiFetch)(url, {
174
- method: "POST",
175
- headers,
176
- body: JSON.stringify(projectData)
177
- });
178
- } catch (fetchError) {
179
- logger$11.error({
180
- error: fetchError instanceof Error ? fetchError.message : "Unknown fetch error",
181
- url,
182
- tenantId,
183
- projectId: projectData.id
184
- }, "Fetch request failed");
185
- throw fetchError;
186
- }
187
- if (!response.ok) {
188
- const errorMessage = parseError(await response.text()) ?? `Failed to create project: ${response.status} ${response.statusText}`;
189
- logger$11.error({
190
- status: response.status,
191
- error: errorMessage
192
- }, "Failed to create project via API");
193
- throw new Error(errorMessage);
194
- }
195
- const result = await response.json();
196
- logger$11.info({ projectId: projectData.id }, "Successfully created project via API");
197
- return result.data;
198
- }
199
- /**
200
- * Update a full project via HTTP API (upsert behavior)
201
- */
202
- async function updateFullProjectViaAPI(tenantId, apiUrl, projectId, projectData, apiKey) {
203
- logger$11.info({
204
- tenantId,
205
- projectId,
206
- apiUrl
207
- }, "Updating full project via API");
208
- const url = `${apiUrl}/tenants/${tenantId}/project-full/${projectId}`;
209
- const headers = {};
210
- if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
211
- let response;
212
- try {
213
- response = await (0, __inkeep_agents_core.apiFetch)(url, {
214
- method: "PUT",
215
- headers,
216
- body: JSON.stringify(projectData)
217
- });
218
- } catch (fetchError) {
219
- logger$11.error({
220
- error: fetchError instanceof Error ? fetchError.message : "Unknown fetch error",
221
- url,
222
- tenantId,
223
- projectId
224
- }, "Fetch request failed");
225
- throw fetchError;
226
- }
227
- if (!response.ok) {
228
- const errorMessage = parseError(await response.text()) ?? `Failed to update project: ${response.status} ${response.statusText}`;
229
- logger$11.error({
230
- status: response.status,
231
- error: errorMessage
232
- }, "Failed to update project via API");
233
- throw new Error(errorMessage);
234
- }
235
- const result = await response.json();
236
- logger$11.info({ projectId }, "Successfully updated project via API");
237
- return result.data;
238
- }
239
- /**
240
- * Get a full project via HTTP API
241
- */
242
- async function getFullProjectViaAPI(tenantId, apiUrl, projectId, apiKey) {
243
- logger$11.info({
244
- tenantId,
245
- projectId,
246
- apiUrl
247
- }, "Getting full project via API");
248
- const url = `${apiUrl}/tenants/${tenantId}/project-full/${projectId}`;
249
- const headers = {};
250
- if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
251
- const response = await (0, __inkeep_agents_core.apiFetch)(url, {
252
- method: "GET",
253
- headers
254
- });
255
- if (!response.ok) {
256
- if (response.status === 404) {
257
- logger$11.info({ projectId }, "Project not found");
258
- return null;
259
- }
260
- const errorMessage = parseError(await response.text()) ?? `Failed to get project: ${response.status} ${response.statusText}`;
261
- logger$11.error({
262
- status: response.status,
263
- error: errorMessage
264
- }, "Failed to get project via API");
265
- throw new Error(errorMessage);
266
- }
267
- const result = await response.json();
268
- logger$11.info({ projectId }, "Successfully retrieved project via API");
269
- return result.data;
270
- }
271
- /**
272
- * Delete a full project via HTTP API
273
- */
274
- async function deleteFullProjectViaAPI(tenantId, apiUrl, projectId, apiKey) {
275
- logger$11.info({
276
- tenantId,
277
- projectId,
278
- apiUrl
279
- }, "Deleting full project via API");
280
- const url = `${apiUrl}/tenants/${tenantId}/project-full/${projectId}`;
281
- const headers = {};
282
- if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
283
- const response = await (0, __inkeep_agents_core.apiFetch)(url, {
284
- method: "DELETE",
285
- headers
286
- });
287
- if (!response.ok) {
288
- const errorMessage = parseError(await response.text()) ?? `Failed to delete project: ${response.status} ${response.statusText}`;
289
- logger$11.error({
290
- status: response.status,
291
- error: errorMessage
292
- }, "Failed to delete project via API");
293
- throw new Error(errorMessage);
294
- }
295
- logger$11.info({ projectId }, "Successfully deleted project via API");
296
- }
297
- function parseError(errorText) {
298
- let result;
299
- try {
300
- const errorJson = JSON.parse(errorText);
301
- if (errorJson.error) {
302
- const { error } = errorJson;
303
- result = error?.message ?? error;
304
- }
305
- } catch {
306
- if (errorText) result = errorText;
307
- }
308
- return result;
309
- }
310
-
311
- //#endregion
312
- //#region src/agentFullClient.ts
313
- const logger$10 = (0, __inkeep_agents_core.getLogger)("agentFullClient");
314
- /**
315
- * Update a full agent via HTTP API (upsert behavior)
316
- */
317
- async function updateFullAgentViaAPI(tenantId, projectId, apiUrl, agentId, agentData) {
318
- logger$10.info({
319
- tenantId,
320
- projectId,
321
- agentId,
322
- apiUrl
323
- }, "Updating full agent via API");
324
- const url = `${apiUrl}/tenants/${tenantId}/projects/${projectId}/agent/${agentId}`;
325
- const response = await fetch(url, {
326
- method: "PUT",
327
- headers: { "Content-Type": "application/json" },
328
- body: JSON.stringify(agentData)
329
- });
330
- if (!response.ok) {
331
- const errorMessage = parseError(await response.text()) ?? `Failed to update agent: ${response.status} ${response.statusText}`;
332
- logger$10.error({
333
- status: response.status,
334
- error: errorMessage
335
- }, "Failed to update agent via API");
336
- throw new Error(errorMessage);
337
- }
338
- const result = await response.json();
339
- logger$10.info({ agentId }, "Successfully updated agent via API");
340
- return result.data;
341
- }
342
-
343
- //#endregion
344
- //#region src/utils/getFunctionToolDeps.ts
345
- const logger$9 = (0, __inkeep_agents_core.getLogger)("function-tool");
346
- const getFunctionToolDeps = (name, code) => {
347
- const { dependencies, warnings } = buildToolManifestFromCodeTS(code);
348
- if (warnings.length > 0) logger$9.warn({ warnings }, `FunctionTool dependencies warnings for ${name}`);
349
- return dependencies;
350
- };
351
- const NODE_BUILTINS = new Set(node_module.builtinModules.concat(node_module.builtinModules.map((m) => `node:${m}`)));
352
- const isExternal = (spec) => !spec.startsWith(".") && !spec.startsWith("/") && !NODE_BUILTINS.has(spec);
353
- const collapseSubpath = (spec) => {
354
- if (spec.startsWith("@")) {
355
- const [scope, name] = spec.split("/");
356
- return `${scope}/${name ?? ""}`;
357
- }
358
- return spec.split("/")[0];
359
- };
360
- const readJSON = (p) => JSON.parse(node_fs.default.readFileSync(p, "utf8"));
361
- const findUp = (start, file) => {
362
- let dir = node_path.default.resolve(start);
363
- if (node_fs.default.existsSync(dir) && node_fs.default.statSync(dir).isFile()) dir = node_path.default.dirname(dir);
364
- for (;;) {
365
- const candidate = node_path.default.join(dir, file);
366
- if (node_fs.default.existsSync(candidate)) return candidate;
367
- const parent = node_path.default.dirname(dir);
368
- if (parent === dir) return null;
369
- dir = parent;
370
- }
371
- };
372
- function collectDepsFromCodeTS(code) {
373
- const info = typescript.default.preProcessFile(code, true, true);
374
- const add = /* @__PURE__ */ new Set();
375
- const push = (spec) => {
376
- if (isExternal(spec)) add.add(collapseSubpath(spec));
377
- };
378
- for (const f of info.importedFiles) {
379
- const spec = f.fileName;
380
- if (spec) push(spec);
381
- }
382
- const requireLike = /(?:require|import)\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
383
- let m;
384
- while (m = requireLike.exec(code)) push(m[2]);
385
- return add;
386
- }
387
- function resolveInstalledVersion(pkg, projectRoot) {
388
- const pnpmLock = findUp(projectRoot, "pnpm-lock.yaml");
389
- if (pnpmLock) {
390
- const pkgs = js_yaml.load(node_fs.default.readFileSync(pnpmLock, "utf8"))?.packages ?? {};
391
- for (const key of Object.keys(pkgs)) if (key.startsWith(`${pkg}@`)) {
392
- const ver = key.slice(key.indexOf("@") + 1);
393
- if (ver) return { exact: String(ver) };
394
- }
395
- }
396
- const npmLock = findUp(projectRoot, "package-lock.json");
397
- if (npmLock) {
398
- const lock = readJSON(npmLock);
399
- if (lock.packages?.[`node_modules/${pkg}`]?.version) return { exact: String(lock.packages[`node_modules/${pkg}`].version) };
400
- if (lock.dependencies?.[pkg]?.version) return { exact: String(lock.dependencies[pkg].version) };
401
- }
402
- const yarnLock = findUp(projectRoot, "yarn.lock");
403
- if (yarnLock) {
404
- const parsed = __yarnpkg_lockfile.parse(node_fs.default.readFileSync(yarnLock, "utf8"));
405
- if (parsed.type === "success") {
406
- for (const [key, val] of Object.entries(parsed.object)) if (key === pkg || key.startsWith(`${pkg}@`)) {
407
- const ver = val.version;
408
- if (ver) return { exact: String(ver) };
409
- }
410
- }
411
- }
412
- const host = {
413
- fileExists: node_fs.default.existsSync,
414
- readFile: (p) => node_fs.default.readFileSync(p, "utf8"),
415
- realpath: (p) => node_fs.default.realpathSync.native?.(p) ?? node_fs.default.realpathSync(p),
416
- directoryExists: (d) => {
417
- try {
418
- return node_fs.default.statSync(d).isDirectory();
419
- } catch {
420
- return false;
421
- }
422
- },
423
- getCurrentDirectory: () => projectRoot,
424
- getDirectories: (d) => node_fs.default.readdirSync(d, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name)
425
- };
426
- const pkgJsonPath = typescript.default.resolveModuleName(`${pkg}/package.json`, node_path.default.join(projectRoot, "__fake.ts"), {}, host, typescript.default.ModuleKind.NodeNext)?.resolvedModule?.resolvedFileName ?? findUp(node_path.default.join(projectRoot, "node_modules", pkg), "package.json");
427
- if (pkgJsonPath && node_fs.default.existsSync(pkgJsonPath)) try {
428
- const version = readJSON(pkgJsonPath).version;
429
- if (version) return { exact: String(version) };
430
- } catch {}
431
- const hostPkg = findUp(projectRoot, "package.json");
432
- if (hostPkg) {
433
- const hostJson = readJSON(hostPkg);
434
- const range = hostJson.dependencies?.[pkg] ?? hostJson.devDependencies?.[pkg] ?? hostJson.optionalDependencies?.[pkg];
435
- if (range) return {
436
- range: String(range),
437
- unresolved: true
438
- };
439
- }
440
- return null;
441
- }
442
- function buildToolManifestFromCodeTS(code, projectRoot = process.cwd()) {
443
- const deps = collectDepsFromCodeTS(code);
444
- const warnings = [];
445
- const dependencies = {};
446
- for (const pkg of deps) try {
447
- const v = resolveInstalledVersion(pkg, projectRoot);
448
- if (!v) {
449
- warnings.push(`Could not resolve version for "${pkg}"`);
450
- continue;
451
- }
452
- if ("unresolved" in v) {
453
- warnings.push(`Using range for "${pkg}" -> ${v.range} (no lockfile / not installed)`);
454
- dependencies[pkg] = v.range;
455
- } else dependencies[pkg] = v.exact;
456
- } catch {
457
- dependencies[pkg] = false;
458
- }
459
- return {
460
- dependencies,
461
- warnings
462
- };
463
- }
464
-
465
- //#endregion
466
- //#region src/function-tool.ts
467
- const logger$8 = (0, __inkeep_agents_core.getLogger)("function-tool");
468
- var FunctionTool = class {
469
- config;
470
- id;
471
- constructor(config) {
472
- this.config = config;
473
- this.id = generateIdFromName(config.name);
474
- if (!config.dependencies) {
475
- const executeCode = typeof config.execute === "string" ? config.execute : config.execute.toString();
476
- const deps = getFunctionToolDeps(config.name, executeCode);
477
- for (const dep in deps) if (deps[dep] === false) {
478
- delete deps[dep];
479
- throw new Error(`Dependency \x1b[1;32m${dep}\x1b[0m used in function tool \x1b[1;32m${config.name}\x1b[0m is neither installed nor in dependencies object.`);
480
- }
481
- this.config.dependencies = deps;
482
- }
483
- logger$8.info({
484
- id: this.id,
485
- name: config.name
486
- }, "FunctionTool constructor initialized");
487
- }
488
- getId() {
489
- return this.id;
490
- }
491
- getName() {
492
- return this.config.name;
493
- }
494
- getDescription() {
495
- return this.config.description || "";
496
- }
497
- getInputSchema() {
498
- return this.config.inputSchema;
499
- }
500
- getDependencies() {
501
- return this.config.dependencies || {};
502
- }
503
- getExecuteFunction() {
504
- if (typeof this.config.execute === "string") throw new Error("Cannot get execute function from string-based function tool. Use serializeFunction() instead.");
505
- return this.config.execute;
506
- }
507
- serializeFunction() {
508
- const executeCode = typeof this.config.execute === "string" ? this.config.execute : this.config.execute.toString();
509
- return {
510
- id: this.id,
511
- inputSchema: this.config.inputSchema,
512
- executeCode,
513
- dependencies: this.config.dependencies || {}
514
- };
515
- }
516
- serializeTool() {
517
- return {
518
- id: this.id,
519
- name: this.config.name,
520
- description: this.config.description,
521
- functionId: this.id
522
- };
523
- }
524
- };
525
-
526
- //#endregion
527
- //#region src/agent.ts
528
- const logger$7 = (0, __inkeep_agents_core.getLogger)("agent");
529
- function resolveGetter$1(value) {
530
- if (typeof value === "function") return value();
531
- return value;
532
- }
533
- var Agent = class {
534
- subAgents = [];
535
- agentMap = /* @__PURE__ */ new Map();
536
- defaultSubAgent;
537
- baseURL;
538
- tenantId;
539
- projectId;
540
- agentId;
541
- agentName;
542
- agentDescription;
543
- initialized = false;
544
- contextConfig;
545
- credentials;
546
- models;
547
- statusUpdateSettings;
548
- prompt;
549
- stopWhen;
550
- constructor(config) {
551
- this.defaultSubAgent = config.defaultSubAgent;
552
- this.tenantId = "default";
553
- this.projectId = "default";
554
- this.agentId = config.id;
555
- this.agentName = config.name || this.agentId;
556
- this.agentDescription = config.description;
557
- this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
558
- this.contextConfig = config.contextConfig;
559
- this.credentials = resolveGetter$1(config.credentials);
560
- this.models = config.models;
561
- this.statusUpdateSettings = config.statusUpdates;
562
- this.prompt = config.prompt;
563
- this.stopWhen = config.stopWhen ? { transferCountIs: config.stopWhen.transferCountIs } : void 0;
564
- this.subAgents = resolveGetter$1(config.subAgents) || [];
565
- this.agentMap = new Map(this.subAgents.map((agent$1) => [agent$1.getId(), agent$1]));
566
- if (this.defaultSubAgent) {
567
- if (!this.subAgents.some((agent$1) => agent$1.getId() === this.defaultSubAgent?.getId())) this.subAgents.push(this.defaultSubAgent);
568
- this.agentMap.set(this.defaultSubAgent.getId(), this.defaultSubAgent);
569
- }
570
- if (this.models) this.propagateImmediateModelSettings();
571
- logger$7.info({
572
- agentId: this.agentId,
573
- tenantId: this.tenantId,
574
- agentCount: this.subAgents.length,
575
- defaultSubAgent: this.defaultSubAgent?.getName()
576
- }, "Agent created");
577
- }
578
- /**
579
- * Set or update the configuration (tenantId, projectId and apiUrl)
580
- * This is used by the CLI to inject configuration from inkeep.config.ts
581
- */
582
- setConfig(tenantId, projectId, apiUrl) {
583
- if (this.initialized) throw new Error("Cannot set config after agent has been initialized");
584
- this.tenantId = tenantId;
585
- this.projectId = projectId;
586
- this.baseURL = apiUrl;
587
- for (const subAgent$1 of this.subAgents) {
588
- if (subAgent$1.setContext) subAgent$1.setContext(tenantId, projectId, apiUrl);
589
- const tools = subAgent$1.getTools();
590
- for (const [_, toolInstance] of Object.entries(tools)) if (toolInstance && typeof toolInstance === "object") {
591
- if ("setContext" in toolInstance && typeof toolInstance.setContext === "function") toolInstance.setContext(tenantId, projectId, apiUrl);
592
- }
593
- }
594
- if (this.contextConfig?.setContext) this.contextConfig.setContext(tenantId, projectId, this.agentId, this.baseURL);
595
- logger$7.info({
596
- agentId: this.agentId,
597
- tenantId: this.tenantId,
598
- projectId: this.projectId,
599
- apiUrl: this.baseURL
600
- }, "Agent configuration updated");
601
- }
602
- /**
603
- * Convert the Agent to FullAgentDefinition format for the new agent endpoint
604
- */
605
- async toFullAgentDefinition() {
606
- const subAgentsObject = {};
607
- const externalAgentsObject = {};
608
- const functionToolsObject = {};
609
- const functionsObject = {};
610
- for (const subAgent$1 of this.subAgents) {
611
- const transfers = subAgent$1.getTransfers();
612
- const delegates = subAgent$1.getDelegates();
613
- const tools = [];
614
- const selectedToolsMapping = {};
615
- const headersMapping = {};
616
- const toolPoliciesMapping = {};
617
- const subAgentTools = subAgent$1.getTools();
618
- for (const [_toolName, toolInstance] of Object.entries(subAgentTools)) {
619
- const toolId = toolInstance.getId();
620
- if (toolInstance.selectedTools) selectedToolsMapping[toolId] = toolInstance.selectedTools;
621
- if (toolInstance.headers) headersMapping[toolId] = toolInstance.headers;
622
- if (toolInstance.toolPolicies) toolPoliciesMapping[toolId] = toolInstance.toolPolicies;
623
- tools.push(toolId);
624
- if (toolInstance.constructor.name === "FunctionTool" && toolInstance instanceof FunctionTool) {
625
- if (!functionsObject[toolId]) functionsObject[toolId] = toolInstance.serializeFunction();
626
- if (!functionToolsObject[toolId]) {
627
- const toolData = toolInstance.serializeTool();
628
- functionToolsObject[toolId] = {
629
- id: toolData.id,
630
- name: toolData.name,
631
- description: toolData.description,
632
- functionId: toolData.functionId,
633
- agentId: this.agentId
634
- };
635
- }
636
- }
637
- }
638
- const subAgentExternalAgents = subAgent$1.getExternalAgentDelegates();
639
- for (const externalAgentDelegate of subAgentExternalAgents) {
640
- const externalAgent$1 = externalAgentDelegate.externalAgent;
641
- externalAgentsObject[externalAgent$1.getId()] = {
642
- id: externalAgent$1.getId(),
643
- name: externalAgent$1.getName(),
644
- description: externalAgent$1.getDescription(),
645
- baseUrl: externalAgent$1.getBaseUrl(),
646
- credentialReferenceId: externalAgent$1.getCredentialReferenceId(),
647
- type: "external"
648
- };
649
- }
650
- const dataComponents = [];
651
- const subAgentDataComponents = subAgent$1.getDataComponents();
652
- if (subAgentDataComponents) for (const dataComponent$1 of subAgentDataComponents) {
653
- const dataComponentId = dataComponent$1.id || dataComponent$1.name.toLowerCase().replace(/\s+/g, "-");
654
- dataComponents.push(dataComponentId);
655
- }
656
- const artifactComponents = [];
657
- const subAgentArtifactComponents = subAgent$1.getArtifactComponents();
658
- if (subAgentArtifactComponents) for (const artifactComponent$1 of subAgentArtifactComponents) {
659
- const artifactComponentId = artifactComponent$1.id || artifactComponent$1.name.toLowerCase().replace(/\s+/g, "-");
660
- artifactComponents.push(artifactComponentId);
661
- }
662
- const canUse = tools.map((toolId) => ({
663
- toolId,
664
- toolSelection: selectedToolsMapping[toolId] || null,
665
- headers: headersMapping[toolId] || null,
666
- toolPolicies: toolPoliciesMapping[toolId] || null
667
- }));
668
- subAgentsObject[subAgent$1.getId()] = {
669
- id: subAgent$1.getId(),
670
- name: subAgent$1.getName(),
671
- description: subAgent$1.config.description || "",
672
- prompt: subAgent$1.getInstructions(),
673
- models: subAgent$1.config.models,
674
- stopWhen: subAgent$1.config.stopWhen,
675
- canTransferTo: transfers.map((h) => h.getId()),
676
- canDelegateTo: delegates.map((d) => {
677
- if (typeof d === "object" && "externalAgent" in d) return {
678
- externalAgentId: d.externalAgent.getId(),
679
- ...d.headers && { headers: d.headers }
680
- };
681
- if (typeof d === "object" && "agent" in d) return {
682
- agentId: d.agent.getId(),
683
- ...d.headers && { headers: d.headers }
684
- };
685
- return d.getId();
686
- }),
687
- canUse,
688
- dataComponents: dataComponents.length > 0 ? dataComponents : void 0,
689
- artifactComponents: artifactComponents.length > 0 ? artifactComponents : void 0,
690
- type: "internal"
691
- };
692
- }
693
- const processedStatusUpdates = this.statusUpdateSettings ? {
694
- ...this.statusUpdateSettings,
695
- statusComponents: this.statusUpdateSettings.statusComponents?.map((comp) => {
696
- if (comp && typeof comp.getType === "function") return {
697
- type: comp.getType(),
698
- description: comp.getDescription(),
699
- detailsSchema: comp.getDetailsSchema()
700
- };
701
- if (comp && typeof comp === "object" && comp.detailsSchema && (0, __inkeep_agents_core_utils_schema_conversion.isZodSchema)(comp.detailsSchema)) {
702
- const jsonSchema = (0, __inkeep_agents_core_utils_schema_conversion.convertZodToJsonSchema)(comp.detailsSchema);
703
- return {
704
- type: comp.type,
705
- description: comp.description,
706
- detailsSchema: {
707
- type: "object",
708
- properties: jsonSchema.properties || {},
709
- required: jsonSchema.required || void 0
710
- }
711
- };
712
- }
713
- return comp;
714
- })
715
- } : void 0;
716
- const agentToolsObject = {};
717
- for (const subAgent$1 of this.subAgents) {
718
- const subAgentTools = subAgent$1.getTools();
719
- for (const [_toolName, toolInstance] of Object.entries(subAgentTools)) {
720
- const toolId = toolInstance.getId();
721
- if (toolInstance.constructor.name !== "FunctionTool") {
722
- if (!agentToolsObject[toolId]) {
723
- if ("config" in toolInstance && "serverUrl" in toolInstance.config) {
724
- const mcpTool$1 = toolInstance;
725
- agentToolsObject[toolId] = {
726
- id: toolId,
727
- name: toolInstance.getName(),
728
- description: null,
729
- config: {
730
- type: "mcp",
731
- mcp: {
732
- server: { url: mcpTool$1.config.serverUrl },
733
- transport: mcpTool$1.config.transport,
734
- activeTools: mcpTool$1.config.activeTools
735
- }
736
- },
737
- credentialReferenceId: null
738
- };
739
- }
740
- }
741
- }
742
- }
743
- }
744
- return {
745
- id: this.agentId,
746
- name: this.agentName,
747
- description: this.agentDescription,
748
- defaultSubAgentId: this.defaultSubAgent?.getId() || "",
749
- subAgents: subAgentsObject,
750
- externalAgents: externalAgentsObject,
751
- contextConfig: this.contextConfig?.toObject(),
752
- ...Object.keys(functionToolsObject).length > 0 && { functionTools: functionToolsObject },
753
- ...Object.keys(functionsObject).length > 0 && { functions: functionsObject },
754
- models: this.models,
755
- stopWhen: this.stopWhen,
756
- statusUpdates: processedStatusUpdates,
757
- prompt: this.prompt,
758
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
759
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
760
- };
761
- }
762
- /**
763
- * Initialize all tools in all agents (especially IPCTools that need MCP server URLs)
764
- */
765
- async initializeAllTools() {
766
- logger$7.info({ agentId: this.agentId }, "Initializing all tools in agent");
767
- const toolInitPromises = [];
768
- for (const subAgent$1 of this.subAgents) {
769
- const agentTools = subAgent$1.getTools();
770
- for (const [toolName, toolInstance] of Object.entries(agentTools)) if (toolInstance && typeof toolInstance === "object") {
771
- if (typeof toolInstance.init === "function") toolInitPromises.push((async () => {
772
- try {
773
- const skipDbRegistration = toolInstance.constructor.name === "IPCTool" || toolInstance.constructor.name === "HostedTool" || toolInstance.constructor.name === "Tool";
774
- if (typeof toolInstance.init === "function") if (skipDbRegistration) await toolInstance.init({ skipDatabaseRegistration: true });
775
- else await toolInstance.init();
776
- logger$7.debug({
777
- subAgentId: subAgent$1.getId(),
778
- toolName,
779
- toolType: toolInstance.constructor.name,
780
- skipDbRegistration
781
- }, "Tool initialized successfully");
782
- } catch (error) {
783
- logger$7.error({
784
- subAgentId: subAgent$1.getId(),
785
- toolName,
786
- error: error instanceof Error ? error.message : "Unknown error"
787
- }, "Failed to initialize tool");
788
- throw error;
789
- }
790
- })());
791
- }
792
- }
793
- await Promise.all(toolInitPromises);
794
- logger$7.info({
795
- agentId: this.agentId,
796
- toolCount: toolInitPromises.length
797
- }, "All tools initialized successfully");
798
- }
799
- /**
800
- * Initialize the agent and all agents in the backend using the new agent endpoint
801
- */
802
- async init() {
803
- if (this.initialized) {
804
- logger$7.info({ agentId: this.agentId }, "Agent already initialized");
805
- return;
806
- }
807
- logger$7.info({
808
- agentId: this.agentId,
809
- agentCount: this.subAgents.length
810
- }, "Initializing agent using new agent endpoint");
811
- try {
812
- await this.initializeAllTools();
813
- await this.applyModelInheritance();
814
- const agentDefinition = await this.toFullAgentDefinition();
815
- logger$7.info({
816
- agentId: this.agentId,
817
- mode: "api-client",
818
- apiUrl: this.baseURL
819
- }, "Using API client to create/update agent");
820
- const createdAgent = await updateFullAgentViaAPI(this.tenantId, this.projectId, this.baseURL, this.agentId, agentDefinition);
821
- logger$7.info({
822
- agentId: this.agentId,
823
- agentCount: Object.keys(createdAgent.subAgents || {}).length
824
- }, "Agent initialized successfully using agent endpoint");
825
- this.initialized = true;
826
- } catch (error) {
827
- logger$7.error({
828
- agentId: this.agentId,
829
- error: error instanceof Error ? error.message : "Unknown error"
830
- }, "Failed to initialize agent using agent endpoint");
831
- throw error;
832
- }
833
- }
834
- /**
835
- * Generate a response using the default agent
836
- */
837
- async generate(input, options) {
838
- await this._init();
839
- if (!this.defaultSubAgent) throw new Error("No default agent configured for this agent");
840
- logger$7.info({
841
- agentId: this.agentId,
842
- defaultSubAgent: this.defaultSubAgent.getName(),
843
- conversationId: options?.conversationId
844
- }, "Generating response with default agent");
845
- return await this.executeWithBackend(input, options);
846
- }
847
- /**
848
- * Stream a response using the default agent
849
- */
850
- async stream(input, options) {
851
- await this._init();
852
- if (!this.defaultSubAgent) throw new Error("No default agent configured for this agent");
853
- logger$7.info({
854
- agentId: this.agentId,
855
- defaultSubAgent: this.defaultSubAgent.getName(),
856
- conversationId: options?.conversationId
857
- }, "Streaming response with default agent");
858
- const textStream = async function* (agent$1) {
859
- const words = (await agent$1.executeWithBackend(input, options)).split(" ");
860
- for (const word of words) yield `${word} `;
861
- };
862
- return { textStream: textStream(this) };
863
- }
864
- /**
865
- * Alias for stream() method for consistency with naming patterns
866
- */
867
- async generateStream(input, options) {
868
- return await this.stream(input, options);
869
- }
870
- /**
871
- * Run with a specific agent from the agent
872
- */
873
- async runWith(subAgentId, input, options) {
874
- await this._init();
875
- const agent$1 = this.getSubAgent(subAgentId);
876
- if (!agent$1) throw new Error(`Agent '${subAgentId}' not found in agent`);
877
- logger$7.info({
878
- agentId: this.agentId,
879
- subAgentId,
880
- conversationId: options?.conversationId
881
- }, "Running with specific agent");
882
- return {
883
- finalOutput: await this.executeWithBackend(input, options),
884
- agent: agent$1,
885
- turnCount: 1,
886
- usage: {
887
- inputTokens: 0,
888
- outputTokens: 0
889
- },
890
- metadata: {
891
- toolCalls: [],
892
- transfers: []
893
- }
894
- };
895
- }
896
- /**
897
- * Get an agent by name (unified method for all agent types)
898
- */
899
- getSubAgent(name) {
900
- return this.agentMap.get(name);
901
- }
902
- /**
903
- * Add an agent to the agent
904
- */
905
- addSubAgent(agent$1) {
906
- this.subAgents.push(agent$1);
907
- this.agentMap.set(agent$1.getId(), agent$1);
908
- if (this.models) this.propagateModelSettingsToAgent(agent$1);
909
- logger$7.info({
910
- agentId: this.agentId,
911
- subAgentId: agent$1.getId()
912
- }, "SubAgent added to agent");
913
- }
914
- /**
915
- * Remove an agent from the agent
916
- */
917
- removeSubAgent(id) {
918
- const agentToRemove = this.agentMap.get(id);
919
- if (agentToRemove) {
920
- this.agentMap.delete(agentToRemove.getId());
921
- this.subAgents = this.subAgents.filter((agent$1) => agent$1.getId() !== agentToRemove.getId());
922
- logger$7.info({
923
- agentId: this.agentId,
924
- subAgentId: agentToRemove.getId()
925
- }, "Agent removed from agent");
926
- return true;
927
- }
928
- return false;
929
- }
930
- /**
931
- * Get all agents in the agent
932
- */
933
- getSubAgents() {
934
- return this.subAgents;
935
- }
936
- /**
937
- * Get all agent ids (unified method for all agent types)
938
- */
939
- getSubAgentIds() {
940
- return Array.from(this.agentMap.keys());
941
- }
942
- /**
943
- * Set the default agent
944
- */
945
- setDefaultSubAgent(agent$1) {
946
- this.defaultSubAgent = agent$1;
947
- this.addSubAgent(agent$1);
948
- logger$7.info({
949
- agentId: this.agentId,
950
- defaultSubAgent: agent$1.getId()
951
- }, "Default agent updated");
952
- }
953
- /**
954
- * Get the default agent
955
- */
956
- getDefaultSubAgent() {
957
- return this.defaultSubAgent;
958
- }
959
- /**
960
- * Get the agent ID
961
- */
962
- getId() {
963
- return this.agentId;
964
- }
965
- getName() {
966
- return this.agentName;
967
- }
968
- getDescription() {
969
- return this.agentDescription;
970
- }
971
- getTenantId() {
972
- return this.tenantId;
973
- }
974
- /**
975
- * Get the agent's model settingsuration
976
- */
977
- getModels() {
978
- return this.models;
979
- }
980
- /**
981
- * Set the agent's model settingsuration
982
- */
983
- setModels(models) {
984
- this.models = models;
985
- }
986
- /**
987
- * Get the agent's prompt configuration
988
- */
989
- getPrompt() {
990
- return this.prompt;
991
- }
992
- /**
993
- * Get the agent's stopWhen configuration
994
- */
995
- getStopWhen() {
996
- return this.stopWhen || { transferCountIs: 10 };
997
- }
998
- /**
999
- * Get the agent's status updates configuration
1000
- */
1001
- getStatusUpdateSettings() {
1002
- return this.statusUpdateSettings;
1003
- }
1004
- /**
1005
- * Get the summarizer model from the agent's model settings
1006
- */
1007
- getSummarizerModel() {
1008
- return this.models?.summarizer;
1009
- }
1010
- /**
1011
- * Get agent statistics
1012
- */
1013
- getStats() {
1014
- return {
1015
- agentCount: this.subAgents.length,
1016
- defaultSubAgent: this.defaultSubAgent?.getName() || null,
1017
- initialized: this.initialized,
1018
- agentId: this.agentId,
1019
- tenantId: this.tenantId
1020
- };
1021
- }
1022
- with(options) {
1023
- return {
1024
- agent: this,
1025
- headers: options.headers
1026
- };
1027
- }
1028
- /**
1029
- * Validate the agent configuration
1030
- */
1031
- validate() {
1032
- const errors = [];
1033
- if (this.subAgents.length === 0) errors.push("Agent must contain at least one agent");
1034
- if (!this.defaultSubAgent) errors.push("Agent must have a default agent");
1035
- const names = /* @__PURE__ */ new Set();
1036
- for (const subAgent$1 of this.subAgents) {
1037
- const name = subAgent$1.getName();
1038
- if (names.has(name)) errors.push(`Duplicate agent name: ${name}`);
1039
- names.add(name);
1040
- }
1041
- for (const subAgent$1 of this.subAgents) {
1042
- const transfers = subAgent$1.getTransfers();
1043
- for (const transferAgent of transfers) if (!this.agentMap.has(transferAgent.getName())) errors.push(`Agent '${subAgent$1.getName()}' has transfer to '${transferAgent.getName()}' which is not in the agent`);
1044
- const delegates = subAgent$1.getDelegates();
1045
- for (const delegateAgent of delegates) if (this.isInternalAgent(delegateAgent)) {
1046
- if (!this.agentMap.has(delegateAgent.getName())) errors.push(`Agent '${subAgent$1.getName()}' has delegation to '${delegateAgent.getName()}' which is not in the agent`);
1047
- }
1048
- }
1049
- return {
1050
- valid: errors.length === 0,
1051
- errors
1052
- };
1053
- }
1054
- async _init() {
1055
- if (!this.initialized) await this.init();
1056
- }
1057
- /**
1058
- * Type guard to check if an agent is an internal AgentInterface
1059
- */
1060
- isInternalAgent(agent$1) {
1061
- return "getTransfers" in agent$1 && typeof agent$1.getTransfers === "function";
1062
- }
1063
- /**
1064
- * Get project-level model settingsuration defaults
1065
- */
1066
- async getProjectModelDefaults() {
1067
- try {
1068
- return (await getFullProjectViaAPI(this.tenantId, this.projectId, this.baseURL))?.models;
1069
- } catch (error) {
1070
- logger$7.warn({
1071
- tenantId: this.tenantId,
1072
- projectId: this.projectId,
1073
- error: error instanceof Error ? error.message : "Unknown error"
1074
- }, "Failed to get project model defaults");
1075
- return;
1076
- }
1077
- }
1078
- /**
1079
- * Get project-level stopWhen configuration defaults
1080
- */
1081
- async getProjectStopWhenDefaults() {
1082
- try {
1083
- return (await getFullProjectViaAPI(this.tenantId, this.projectId, this.baseURL))?.stopWhen;
1084
- } catch (error) {
1085
- logger$7.warn({
1086
- tenantId: this.tenantId,
1087
- projectId: this.projectId,
1088
- error: error instanceof Error ? error.message : "Unknown error"
1089
- }, "Failed to get project stopWhen defaults");
1090
- return;
1091
- }
1092
- }
1093
- /**
1094
- * Apply model inheritance hierarchy: Project -> Agent -> Agent
1095
- */
1096
- async applyModelInheritance() {
1097
- const projectModels = await this.getProjectModelDefaults();
1098
- if (projectModels) {
1099
- if (!this.models) this.models = {};
1100
- if (!this.models.base && projectModels.base) this.models.base = projectModels.base;
1101
- if (!this.models.structuredOutput && projectModels.structuredOutput) this.models.structuredOutput = projectModels.structuredOutput;
1102
- if (!this.models.summarizer && projectModels.summarizer) this.models.summarizer = projectModels.summarizer;
1103
- }
1104
- await this.applyStopWhenInheritance();
1105
- for (const subAgent$1 of this.subAgents) this.propagateModelSettingsToAgent(subAgent$1);
1106
- }
1107
- /**
1108
- * Apply stopWhen inheritance hierarchy: Project -> Agent -> Agent
1109
- */
1110
- async applyStopWhenInheritance() {
1111
- const projectStopWhen = await this.getProjectStopWhenDefaults();
1112
- if (!this.stopWhen) this.stopWhen = {};
1113
- if (this.stopWhen.transferCountIs === void 0 && projectStopWhen?.transferCountIs !== void 0) this.stopWhen.transferCountIs = projectStopWhen.transferCountIs;
1114
- if (this.stopWhen.transferCountIs === void 0) this.stopWhen.transferCountIs = 10;
1115
- if (projectStopWhen?.stepCountIs !== void 0) for (const subAgent$1 of this.subAgents) {
1116
- if (!subAgent$1.config.stopWhen) subAgent$1.config.stopWhen = {};
1117
- if (subAgent$1.config.stopWhen.stepCountIs === void 0) subAgent$1.config.stopWhen.stepCountIs = projectStopWhen.stepCountIs;
1118
- }
1119
- logger$7.debug({
1120
- agentId: this.agentId,
1121
- agentStopWhen: this.stopWhen,
1122
- projectStopWhen
1123
- }, "Applied stopWhen inheritance from project to agent");
1124
- }
1125
- /**
1126
- * Propagate agent-level model settings to agents (supporting partial inheritance)
1127
- */
1128
- propagateModelSettingsToAgent(agent$1) {
1129
- if (this.models) {
1130
- if (!agent$1.config.models) agent$1.config.models = {};
1131
- if (!agent$1.config.models.base && this.models.base) agent$1.config.models.base = this.models.base;
1132
- if (!agent$1.config.models.structuredOutput && this.models.structuredOutput) agent$1.config.models.structuredOutput = this.models.structuredOutput;
1133
- if (!agent$1.config.models.summarizer && this.models.summarizer) agent$1.config.models.summarizer = this.models.summarizer;
1134
- }
1135
- }
1136
- /**
1137
- * Immediately propagate agent-level models to all agents during construction
1138
- */
1139
- propagateImmediateModelSettings() {
1140
- for (const subAgent$1 of this.subAgents) this.propagateModelSettingsToAgent(subAgent$1);
1141
- }
1142
- /**
1143
- * Execute agent using the backend system instead of local runner
1144
- */
1145
- async executeWithBackend(input, options) {
1146
- const normalizedMessages = this.normalizeMessages(input);
1147
- const url = `${this.baseURL}/tenants/${this.tenantId}/agent/${this.agentId}/v1/chat/completions`;
1148
- logger$7.info({ url }, "Executing with backend");
1149
- const requestBody = {
1150
- model: "gpt-4o-mini",
1151
- messages: normalizedMessages.map((msg) => ({
1152
- role: msg.role,
1153
- content: msg.content
1154
- })),
1155
- ...options,
1156
- ...options?.conversationId && { conversationId: options.conversationId },
1157
- ...options?.customBodyParams && { ...options.customBodyParams },
1158
- stream: false
1159
- };
1160
- try {
1161
- const response = await fetch(url, {
1162
- method: "POST",
1163
- headers: {
1164
- "Content-Type": "application/json",
1165
- Accept: "application/json"
1166
- },
1167
- body: JSON.stringify(requestBody)
1168
- });
1169
- if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1170
- const responseText = await response.text();
1171
- if (responseText.startsWith("data:")) return this.parseStreamingResponse(responseText);
1172
- const data = JSON.parse(responseText);
1173
- return data.result || data.choices?.[0]?.message?.content || "";
1174
- } catch (error) {
1175
- throw new Error(`Agent execution failed: ${error.message || "Unknown error"}`);
1176
- }
1177
- }
1178
- /**
1179
- * Parse streaming response in SSE format
1180
- */
1181
- parseStreamingResponse(text) {
1182
- const lines = text.split("\n");
1183
- let content = "";
1184
- for (const line of lines) if (line.startsWith("data: ")) {
1185
- const dataStr = line.slice(6);
1186
- if (dataStr === "[DONE]") break;
1187
- try {
1188
- const delta = JSON.parse(dataStr).choices?.[0]?.delta?.content;
1189
- if (delta) content += delta;
1190
- } catch (_e) {}
1191
- }
1192
- return content;
1193
- }
1194
- /**
1195
- * Normalize input messages to the expected format
1196
- */
1197
- normalizeMessages(input) {
1198
- if (typeof input === "string") return [{
1199
- role: "user",
1200
- content: input
1201
- }];
1202
- if (Array.isArray(input)) return input.map((msg) => typeof msg === "string" ? {
1203
- role: "user",
1204
- content: msg
1205
- } : msg);
1206
- return [input];
1207
- }
1208
- };
1209
-
1210
- //#endregion
1211
- //#region src/data-component.ts
1212
- const logger$6 = (0, __inkeep_agents_core.getLogger)("dataComponent");
1213
- var DataComponent = class {
1214
- config;
1215
- baseURL;
1216
- tenantId;
1217
- projectId;
1218
- initialized = false;
1219
- id;
1220
- constructor(config) {
1221
- this.id = config.id || generateIdFromName(config.name);
1222
- let processedProps;
1223
- if (config.props && (0, __inkeep_agents_core_utils_schema_conversion.isZodSchema)(config.props)) processedProps = (0, __inkeep_agents_core_utils_schema_conversion.convertZodToJsonSchema)(config.props);
1224
- else processedProps = config.props;
1225
- this.config = {
1226
- ...config,
1227
- id: this.id,
1228
- props: processedProps,
1229
- render: config.render || null
1230
- };
1231
- this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
1232
- this.tenantId = "default";
1233
- this.projectId = "default";
1234
- logger$6.info({
1235
- dataComponentId: this.getId(),
1236
- dataComponentName: config.name
1237
- }, "DataComponent constructor initialized");
1238
- }
1239
- setContext(tenantId, projectId, baseURL) {
1240
- this.tenantId = tenantId;
1241
- this.projectId = projectId;
1242
- if (baseURL) this.baseURL = baseURL;
1243
- }
1244
- getId() {
1245
- return this.id;
1246
- }
1247
- getName() {
1248
- return this.config.name;
1249
- }
1250
- getDescription() {
1251
- return this.config.description || "";
1252
- }
1253
- getProps() {
1254
- return this.config.props;
1255
- }
1256
- getRender() {
1257
- return this.config.render;
1258
- }
1259
- async init() {
1260
- if (this.initialized) return;
1261
- try {
1262
- await this.upsertDataComponent();
1263
- logger$6.info({ dataComponentId: this.getId() }, "DataComponent initialized successfully");
1264
- this.initialized = true;
1265
- } catch (error) {
1266
- logger$6.error({
1267
- dataComponentId: this.getId(),
1268
- error: error instanceof Error ? error.message : "Unknown error"
1269
- }, "Failed to initialize data component");
1270
- throw error;
1271
- }
1272
- }
1273
- async upsertDataComponent() {
1274
- const dataComponentData = {
1275
- id: this.getId(),
1276
- name: this.config.name,
1277
- description: this.config.description,
1278
- props: this.config.props,
1279
- render: this.config.render
1280
- };
1281
- logger$6.info({ dataComponentData }, "dataComponentData for create/update");
1282
- const updateResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/data-components/${this.getId()}`, {
1283
- method: "PUT",
1284
- headers: { "Content-Type": "application/json" },
1285
- body: JSON.stringify(dataComponentData)
1286
- });
1287
- logger$6.info({
1288
- status: updateResponse.status,
1289
- dataComponentId: this.getId()
1290
- }, "data component updateResponse");
1291
- if (updateResponse.ok) {
1292
- logger$6.info({ dataComponentId: this.getId() }, "DataComponent updated successfully");
1293
- return;
1294
- }
1295
- if (updateResponse.status === 404) {
1296
- logger$6.info({ dataComponentId: this.getId() }, "DataComponent not found, creating new data component");
1297
- const createResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/data-components`, {
1298
- method: "POST",
1299
- headers: { "Content-Type": "application/json" },
1300
- body: JSON.stringify(dataComponentData)
1301
- });
1302
- if (!createResponse.ok) {
1303
- const errorText$1 = await createResponse.text().catch(() => "Unknown error");
1304
- throw new Error(`Failed to create data component: ${createResponse.status} ${createResponse.statusText} - ${errorText$1}`);
1305
- }
1306
- logger$6.info({ dataComponentId: this.getId() }, "DataComponent created successfully");
1307
- return;
1308
- }
1309
- const errorText = await updateResponse.text().catch(() => "Unknown error");
1310
- throw new Error(`Failed to update data component: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`);
1311
- }
1312
- };
1313
-
1314
- //#endregion
1315
- //#region src/project.ts
1316
- const logger$5 = (0, __inkeep_agents_core.getLogger)("project");
1317
- /**
1318
- * Project class for managing agent projects
1319
- *
1320
- * Projects are the top-level organizational unit that contains Agents, Sub Agents, and shared configurations.
1321
- * They provide model inheritance and execution limits that cascade down to Agents and Sub Agents.
1322
- *
1323
- * @example
1324
- * ```typescript
1325
- * const myProject = new Project({
1326
- * id: 'customer-support-project',
1327
- * name: 'Customer Support System',
1328
- * description: 'Multi-agent customer support system',
1329
- * models: {
1330
- * base: { model: 'gpt-4.1-mini' },
1331
- * structuredOutput: { model: 'gpt-4.1' }
1332
- * },
1333
- * stopWhen: {
1334
- * transferCountIs: 10,
1335
- * stepCountIs: 50
1336
- * }
1337
- * });
1338
- *
1339
- * await myProject.init();
1340
- * ```
1341
- */
1342
- var Project = class {
1343
- __type = "project";
1344
- projectId;
1345
- projectName;
1346
- projectDescription;
1347
- tenantId;
1348
- baseURL;
1349
- apiKey;
1350
- initialized = false;
1351
- models;
1352
- stopWhen;
1353
- agents = [];
1354
- agentMap = /* @__PURE__ */ new Map();
1355
- credentialReferences = [];
1356
- projectTools = [];
1357
- projectDataComponents = [];
1358
- projectArtifactComponents = [];
1359
- projectExternalAgents = [];
1360
- externalAgentMap = /* @__PURE__ */ new Map();
1361
- constructor(config) {
1362
- this.projectId = config.id;
1363
- this.projectName = config.name;
1364
- this.projectDescription = config.description;
1365
- this.tenantId = process.env.INKEEP_TENANT_ID || "default";
1366
- this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
1367
- this.models = config.models;
1368
- this.stopWhen = config.stopWhen;
1369
- if (config.agents) {
1370
- this.agents = config.agents();
1371
- this.agentMap = new Map(this.agents.map((agent$1) => [agent$1.getId(), agent$1]));
1372
- for (const agent$1 of this.agents) agent$1.setConfig(this.tenantId, this.projectId, this.baseURL);
1373
- }
1374
- if (config.tools) this.projectTools = config.tools();
1375
- if (config.dataComponents) this.projectDataComponents = config.dataComponents();
1376
- if (config.artifactComponents) this.projectArtifactComponents = config.artifactComponents();
1377
- if (config.credentialReferences) this.credentialReferences = config.credentialReferences();
1378
- if (config.externalAgents) {
1379
- this.projectExternalAgents = config.externalAgents();
1380
- this.externalAgentMap = new Map(this.projectExternalAgents.map((externalAgent$1) => [externalAgent$1.getId(), externalAgent$1]));
1381
- }
1382
- logger$5.info({
1383
- projectId: this.projectId,
1384
- tenantId: this.tenantId,
1385
- agentCount: this.agents.length
1386
- }, "Project created");
1387
- }
1388
- /**
1389
- * Set or update the configuration (tenantId and apiUrl)
1390
- * This is used by the CLI to inject configuration from inkeep.config.ts
1391
- */
1392
- setConfig(tenantId, apiUrl, models, apiKey) {
1393
- if (this.initialized) throw new Error("Cannot set config after project has been initialized");
1394
- this.tenantId = tenantId;
1395
- this.baseURL = apiUrl;
1396
- this.apiKey = apiKey;
1397
- if (models) this.models = models;
1398
- for (const agent$1 of this.agents) agent$1.setConfig(tenantId, this.projectId, apiUrl);
1399
- logger$5.info({
1400
- projectId: this.projectId,
1401
- tenantId: this.tenantId,
1402
- apiUrl: this.baseURL,
1403
- hasModels: !!this.models,
1404
- hasApiKey: !!this.apiKey
1405
- }, "Project configuration updated");
1406
- }
1407
- /**
1408
- * Set credential references for the project
1409
- * This is used by the CLI to inject environment-specific credentials
1410
- */
1411
- setCredentials(credentials) {
1412
- this.credentialReferences = Object.values(credentials);
1413
- logger$5.info({
1414
- projectId: this.projectId,
1415
- credentialCount: this.credentialReferences?.length || 0
1416
- }, "Project credentials updated");
1417
- }
1418
- /**
1419
- * Initialize the project and create/update it in the backend using full project approach
1420
- */
1421
- async init() {
1422
- if (this.initialized) {
1423
- logger$5.info({ projectId: this.projectId }, "Project already initialized");
1424
- return;
1425
- }
1426
- logger$5.info({
1427
- projectId: this.projectId,
1428
- tenantId: this.tenantId,
1429
- agentCount: this.agents.length
1430
- }, "Initializing project using full project endpoint");
1431
- try {
1432
- const projectDefinition = await this.toFullProjectDefinition();
1433
- logger$5.info({
1434
- projectId: this.projectId,
1435
- mode: "api-client",
1436
- apiUrl: this.baseURL
1437
- }, "Using API client to create/update full project");
1438
- const createdProject = await updateFullProjectViaAPI(this.tenantId, this.baseURL, this.projectId, projectDefinition, this.apiKey);
1439
- this.initialized = true;
1440
- logger$5.info({
1441
- projectId: this.projectId,
1442
- tenantId: this.tenantId,
1443
- agentCount: Object.keys(createdProject.agent || {}).length
1444
- }, "Project initialized successfully using full project endpoint");
1445
- } catch (error) {
1446
- logger$5.error({
1447
- projectId: this.projectId,
1448
- error: error instanceof Error ? error.message : "Unknown error"
1449
- }, "Failed to initialize project using full project endpoint");
1450
- throw error;
1451
- }
1452
- }
1453
- /**
1454
- * Get the project ID
1455
- */
1456
- getId() {
1457
- return this.projectId;
1458
- }
1459
- /**
1460
- * Get the project name
1461
- */
1462
- getName() {
1463
- return this.projectName;
1464
- }
1465
- /**
1466
- * Get the project description
1467
- */
1468
- getDescription() {
1469
- return this.projectDescription;
1470
- }
1471
- /**
1472
- * Get the tenant ID
1473
- */
1474
- getTenantId() {
1475
- return this.tenantId;
1476
- }
1477
- /**
1478
- * Get the project's model configuration
1479
- */
1480
- getModels() {
1481
- return this.models;
1482
- }
1483
- /**
1484
- * Set the project's model configuration
1485
- */
1486
- setModels(models) {
1487
- this.models = models;
1488
- }
1489
- /**
1490
- * Get the project's stopWhen configuration
1491
- */
1492
- getStopWhen() {
1493
- return this.stopWhen;
1494
- }
1495
- /**
1496
- * Set the project's stopWhen configuration
1497
- */
1498
- setStopWhen(stopWhen) {
1499
- this.stopWhen = stopWhen;
1500
- }
1501
- /**
1502
- * Get credential tracking information
1503
- */
1504
- async getCredentialTracking() {
1505
- const credentials = (await this.toFullProjectDefinition()).credentialReferences || {};
1506
- const usage = {};
1507
- for (const [credId, credData] of Object.entries(credentials)) if (credData.usedBy) usage[credId] = credData.usedBy;
1508
- return {
1509
- credentials,
1510
- usage
1511
- };
1512
- }
1513
- async getFullDefinition() {
1514
- return await this.toFullProjectDefinition();
1515
- }
1516
- /**
1517
- * Get all agent in the project
1518
- */
1519
- getAgents() {
1520
- return this.agents;
1521
- }
1522
- /**
1523
- * Get all external agents in the project
1524
- */
1525
- getExternalAgents() {
1526
- return this.projectExternalAgents;
1527
- }
1528
- /**
1529
- * Get an external agent by ID
1530
- */
1531
- getExternalAgent(id) {
1532
- return this.externalAgentMap.get(id);
1533
- }
1534
- /**
1535
- * Add an external agent to the project
1536
- */
1537
- addExternalAgent(externalAgent$1) {
1538
- this.projectExternalAgents.push(externalAgent$1);
1539
- this.externalAgentMap.set(externalAgent$1.getId(), externalAgent$1);
1540
- }
1541
- /**
1542
- * Remove an external agent from the project
1543
- */
1544
- removeExternalAgent(id) {
1545
- if (this.externalAgentMap.get(id)) {
1546
- this.externalAgentMap.delete(id);
1547
- this.projectExternalAgents = this.projectExternalAgents.filter((externalAgent$1) => externalAgent$1.getId() !== id);
1548
- logger$5.info({
1549
- projectId: this.projectId,
1550
- externalAgentId: id
1551
- }, "External agent removed from project");
1552
- return true;
1553
- }
1554
- return false;
1555
- }
1556
- /**
1557
- * Get an agent by ID
1558
- */
1559
- getAgent(id) {
1560
- return this.agentMap.get(id);
1561
- }
1562
- /**
1563
- * Add an agent to the project
1564
- */
1565
- addAgent(agent$1) {
1566
- this.agents.push(agent$1);
1567
- this.agentMap.set(agent$1.getId(), agent$1);
1568
- agent$1.setConfig(this.tenantId, this.projectId, this.baseURL);
1569
- logger$5.info({
1570
- projectId: this.projectId,
1571
- agentId: agent$1.getId()
1572
- }, "Agent added to project");
1573
- }
1574
- /**
1575
- * Remove an agent from the project
1576
- */
1577
- removeAgent(id) {
1578
- if (this.agentMap.get(id)) {
1579
- this.agentMap.delete(id);
1580
- this.agents = this.agents.filter((agent$1) => agent$1.getId() !== id);
1581
- logger$5.info({
1582
- projectId: this.projectId,
1583
- agentId: id
1584
- }, "Agent removed from project");
1585
- return true;
1586
- }
1587
- return false;
1588
- }
1589
- /**
1590
- * Get project statistics
1591
- */
1592
- getStats() {
1593
- return {
1594
- projectId: this.projectId,
1595
- tenantId: this.tenantId,
1596
- agentCount: this.agents.length,
1597
- initialized: this.initialized
1598
- };
1599
- }
1600
- /**
1601
- * Validate the project configuration
1602
- */
1603
- validate() {
1604
- const errors = [];
1605
- if (!this.projectId) errors.push("Project must have an ID");
1606
- if (!this.projectName) errors.push("Project must have a name");
1607
- const agentIds = /* @__PURE__ */ new Set();
1608
- for (const agent$1 of this.agents) {
1609
- const id = agent$1.getId();
1610
- if (agentIds.has(id)) errors.push(`Duplicate agent ID: ${id}`);
1611
- agentIds.add(id);
1612
- }
1613
- for (const agent$1 of this.agents) {
1614
- const agentValidation = agent$1.validate();
1615
- if (!agentValidation.valid) errors.push(...agentValidation.errors.map((error) => `Agent '${agent$1.getId()}': ${error}`));
1616
- }
1617
- return {
1618
- valid: errors.length === 0,
1619
- errors
1620
- };
1621
- }
1622
- /**
1623
- * Convert the Project to FullProjectDefinition format
1624
- */
1625
- async toFullProjectDefinition() {
1626
- const agentsObject = {};
1627
- const toolsObject = {};
1628
- const functionToolsObject = {};
1629
- const functionsObject = {};
1630
- const dataComponentsObject = {};
1631
- const artifactComponentsObject = {};
1632
- const credentialReferencesObject = {};
1633
- const externalAgentsObject = {};
1634
- const credentialUsageMap = {};
1635
- for (const agent$1 of this.agents) {
1636
- logger$5.info({ agentId: agent$1.getId() }, "Agent id");
1637
- const agentDefinition = await agent$1.toFullAgentDefinition();
1638
- agentsObject[agent$1.getId()] = agentDefinition;
1639
- const agentCredentials = agent$1.credentials;
1640
- if (agentCredentials && Array.isArray(agentCredentials)) for (const credential$1 of agentCredentials) {
1641
- if (credential$1?.__type === "credential-ref") continue;
1642
- if (credential$1?.id) {
1643
- if (!credentialReferencesObject[credential$1.id]) {
1644
- credentialReferencesObject[credential$1.id] = {
1645
- id: credential$1.id,
1646
- name: credential$1.name,
1647
- type: credential$1.type,
1648
- credentialStoreId: credential$1.credentialStoreId,
1649
- retrievalParams: credential$1.retrievalParams
1650
- };
1651
- credentialUsageMap[credential$1.id] = [];
1652
- }
1653
- credentialUsageMap[credential$1.id].push({
1654
- type: "agent",
1655
- id: agent$1.getId()
1656
- });
1657
- }
1658
- }
1659
- const agentContextConfig = agent$1.contextConfig;
1660
- if (agentContextConfig) {
1661
- const contextVariables = agentContextConfig.getContextVariables?.() || agentContextConfig.contextVariables;
1662
- if (contextVariables) {
1663
- for (const [key, variable] of Object.entries(contextVariables)) if (variable?.credential) {
1664
- const credential$1 = variable.credential;
1665
- let credId;
1666
- if (credential$1.__type === "credential-ref") {
1667
- credId = credential$1.id;
1668
- if (credId && this.credentialReferences) {
1669
- const resolvedCred = this.credentialReferences.find((c) => c.id === credId);
1670
- if (resolvedCred && !credentialReferencesObject[credId]) {
1671
- credentialReferencesObject[credId] = resolvedCred;
1672
- credentialUsageMap[credId] = [];
1673
- }
1674
- }
1675
- } else if (credential$1.id) {
1676
- credId = credential$1.id;
1677
- if (credId && !credentialReferencesObject[credId]) {
1678
- credentialReferencesObject[credId] = credential$1;
1679
- credentialUsageMap[credId] = [];
1680
- }
1681
- }
1682
- if (credId) {
1683
- if (!credentialUsageMap[credId]) credentialUsageMap[credId] = [];
1684
- credentialUsageMap[credId].push({
1685
- type: "contextVariable",
1686
- id: key,
1687
- agentId: agent$1.getId()
1688
- });
1689
- }
1690
- } else if (variable?.credentialReferenceId) {
1691
- const credId = variable.credentialReferenceId;
1692
- if (!credentialUsageMap[credId]) credentialUsageMap[credId] = [];
1693
- credentialUsageMap[credId].push({
1694
- type: "contextVariable",
1695
- id: key,
1696
- agentId: agent$1.getId()
1697
- });
1698
- }
1699
- }
1700
- }
1701
- for (const subAgent$1 of agent$1.getSubAgents()) {
1702
- const agentTools = subAgent$1.getTools();
1703
- for (const [, toolInstance] of Object.entries(agentTools)) {
1704
- const actualTool = toolInstance;
1705
- const toolId = actualTool.getId();
1706
- if (actualTool.constructor.name === "FunctionTool" && actualTool instanceof FunctionTool) {
1707
- if (!functionsObject[toolId]) functionsObject[toolId] = actualTool.serializeFunction();
1708
- if (!functionToolsObject[toolId]) {
1709
- const toolData = actualTool.serializeTool();
1710
- functionToolsObject[toolId] = {
1711
- id: toolData.id,
1712
- name: toolData.name,
1713
- description: toolData.description,
1714
- functionId: toolData.functionId
1715
- };
1716
- }
1717
- } else if (!toolsObject[toolId]) {
1718
- if ("config" in actualTool && "serverUrl" in actualTool.config) {
1719
- const mcpTool$1 = actualTool;
1720
- const toolConfig = {
1721
- type: "mcp",
1722
- mcp: {
1723
- server: { url: mcpTool$1.config.serverUrl },
1724
- transport: mcpTool$1.config.transport,
1725
- activeTools: mcpTool$1.config.activeTools
1726
- }
1727
- };
1728
- const toolData = {
1729
- id: toolId,
1730
- name: actualTool.getName(),
1731
- config: toolConfig
1732
- };
1733
- if (mcpTool$1.config?.imageUrl) toolData.imageUrl = mcpTool$1.config.imageUrl;
1734
- if (mcpTool$1.config?.headers) toolData.headers = mcpTool$1.config.headers;
1735
- if ("getCredentialReferenceId" in actualTool) {
1736
- const credentialId = actualTool.getCredentialReferenceId();
1737
- if (credentialId) toolData.credentialReferenceId = credentialId;
1738
- }
1739
- if ("credential" in mcpTool$1.config && mcpTool$1.config.credential) {
1740
- const credential$1 = mcpTool$1.config.credential;
1741
- if (credential$1?.id && credential$1.__type !== "credential-ref") {
1742
- if (!credentialReferencesObject[credential$1.id]) {
1743
- credentialReferencesObject[credential$1.id] = {
1744
- id: credential$1.id,
1745
- name: credential$1.name,
1746
- type: credential$1.type,
1747
- credentialStoreId: credential$1.credentialStoreId,
1748
- retrievalParams: credential$1.retrievalParams
1749
- };
1750
- credentialUsageMap[credential$1.id] = [];
1751
- }
1752
- credentialUsageMap[credential$1.id].push({
1753
- type: "tool",
1754
- id: toolId
1755
- });
1756
- }
1757
- }
1758
- toolsObject[toolId] = toolData;
1759
- }
1760
- }
1761
- }
1762
- const subAgentDataComponents = subAgent$1.getDataComponents?.();
1763
- if (subAgentDataComponents) for (const dataComponent$1 of subAgentDataComponents) {
1764
- let dataComponentId;
1765
- let dataComponentName;
1766
- let dataComponentDescription;
1767
- let dataComponentProps;
1768
- let dataComponentRender;
1769
- if (dataComponent$1.getId) {
1770
- dataComponentId = dataComponent$1.getId();
1771
- dataComponentName = dataComponent$1.getName();
1772
- dataComponentDescription = dataComponent$1.getDescription() || "";
1773
- dataComponentProps = dataComponent$1.getProps() || {};
1774
- dataComponentRender = dataComponent$1.getRender?.() || null;
1775
- } else {
1776
- dataComponentId = dataComponent$1.id || (dataComponent$1.name ? dataComponent$1.name.toLowerCase().replace(/\s+/g, "-") : "");
1777
- dataComponentName = dataComponent$1.name || "";
1778
- dataComponentDescription = dataComponent$1.description || "";
1779
- dataComponentProps = dataComponent$1.props || {};
1780
- dataComponentRender = dataComponent$1.render || null;
1781
- }
1782
- if (!dataComponentsObject[dataComponentId] && dataComponentName) dataComponentsObject[dataComponentId] = {
1783
- id: dataComponentId,
1784
- name: dataComponentName,
1785
- description: dataComponentDescription,
1786
- props: dataComponentProps,
1787
- render: dataComponentRender
1788
- };
1789
- }
1790
- const subAgentArtifactComponents = subAgent$1.getArtifactComponents();
1791
- if (subAgentArtifactComponents) for (const artifactComponent$1 of subAgentArtifactComponents) {
1792
- let artifactComponentId;
1793
- let artifactComponentName;
1794
- let artifactComponentDescription;
1795
- let artifactComponentProps;
1796
- if ("getId" in artifactComponent$1 && typeof artifactComponent$1.getId === "function") {
1797
- const component = artifactComponent$1;
1798
- artifactComponentId = component.getId();
1799
- artifactComponentName = component.getName();
1800
- artifactComponentDescription = component.getDescription() || "";
1801
- artifactComponentProps = component.getProps() || {};
1802
- } else {
1803
- artifactComponentId = artifactComponent$1.id || (artifactComponent$1.name ? artifactComponent$1.name.toLowerCase().replace(/\s+/g, "-") : "");
1804
- artifactComponentName = artifactComponent$1.name || "";
1805
- artifactComponentDescription = artifactComponent$1.description || "";
1806
- artifactComponentProps = artifactComponent$1.props || {};
1807
- }
1808
- if (!artifactComponentsObject[artifactComponentId] && artifactComponentName) artifactComponentsObject[artifactComponentId] = {
1809
- id: artifactComponentId,
1810
- name: artifactComponentName,
1811
- description: artifactComponentDescription,
1812
- props: artifactComponentProps
1813
- };
1814
- }
1815
- const subAgentExternalAgents = subAgent$1.getExternalAgentDelegates();
1816
- if (subAgentExternalAgents) for (const externalAgentDelegate of subAgentExternalAgents) {
1817
- const externalAgent$1 = externalAgentDelegate.externalAgent;
1818
- const credential$1 = externalAgent$1.getCredentialReference();
1819
- if (credential$1) {
1820
- if (!credentialReferencesObject[credential$1.id]) {
1821
- credentialReferencesObject[credential$1.id] = {
1822
- id: credential$1.id,
1823
- name: credential$1.name,
1824
- type: credential$1.type,
1825
- credentialStoreId: credential$1.credentialStoreId,
1826
- retrievalParams: credential$1.retrievalParams
1827
- };
1828
- credentialUsageMap[credential$1.id] = [];
1829
- }
1830
- logger$5.info({ credentialId: credential$1.id }, "Credential id in external agent");
1831
- credentialUsageMap[credential$1.id].push({
1832
- type: "externalAgent",
1833
- id: externalAgent$1.getId()
1834
- });
1835
- }
1836
- logger$5.info({ externalAgentId: externalAgent$1.getId() }, "External agent id");
1837
- externalAgentsObject[externalAgent$1.getId()] = {
1838
- id: externalAgent$1.getId(),
1839
- name: externalAgent$1.getName(),
1840
- description: externalAgent$1.getDescription(),
1841
- baseUrl: externalAgent$1.getBaseUrl(),
1842
- credentialReferenceId: externalAgent$1.getCredentialReferenceId()
1843
- };
1844
- }
1845
- }
1846
- }
1847
- logger$5.info({ externalAgentsObject }, "External agents object");
1848
- for (const tool of this.projectTools) {
1849
- const toolId = tool.getId();
1850
- if (!toolsObject[toolId]) {
1851
- const toolConfig = {
1852
- type: "mcp",
1853
- mcp: {
1854
- server: { url: tool.config.serverUrl },
1855
- transport: tool.config.transport,
1856
- activeTools: tool.config.activeTools
1857
- }
1858
- };
1859
- const toolData = {
1860
- id: toolId,
1861
- name: tool.getName(),
1862
- config: toolConfig
1863
- };
1864
- if (tool.config?.imageUrl) toolData.imageUrl = tool.config.imageUrl;
1865
- if (tool.config?.headers) toolData.headers = tool.config.headers;
1866
- const credentialId = tool.getCredentialReferenceId();
1867
- if (credentialId) toolData.credentialReferenceId = credentialId;
1868
- toolsObject[toolId] = toolData;
1869
- }
1870
- }
1871
- for (const dataComponent$1 of this.projectDataComponents) {
1872
- const dataComponentId = dataComponent$1.getId();
1873
- const dataComponentName = dataComponent$1.getName();
1874
- const dataComponentDescription = dataComponent$1.getDescription() || "";
1875
- const dataComponentProps = dataComponent$1.getProps() || {};
1876
- if (!dataComponentsObject[dataComponentId] && dataComponentName) dataComponentsObject[dataComponentId] = {
1877
- id: dataComponentId,
1878
- name: dataComponentName,
1879
- description: dataComponentDescription,
1880
- props: dataComponentProps
1881
- };
1882
- }
1883
- for (const artifactComponent$1 of this.projectArtifactComponents) {
1884
- const artifactComponentId = artifactComponent$1.getId();
1885
- const artifactComponentName = artifactComponent$1.getName();
1886
- const artifactComponentDescription = artifactComponent$1.getDescription() || "";
1887
- const artifactComponentProps = artifactComponent$1.getProps() || {};
1888
- if (!artifactComponentsObject[artifactComponentId] && artifactComponentName) artifactComponentsObject[artifactComponentId] = {
1889
- id: artifactComponentId,
1890
- name: artifactComponentName,
1891
- description: artifactComponentDescription,
1892
- props: artifactComponentProps
1893
- };
1894
- }
1895
- if (this.credentialReferences && this.credentialReferences.length > 0) {
1896
- for (const credential$1 of this.credentialReferences) if (credential$1.id) {
1897
- if (!credentialReferencesObject[credential$1.id]) {
1898
- credentialReferencesObject[credential$1.id] = credential$1;
1899
- credentialUsageMap[credential$1.id] = [];
1900
- }
1901
- }
1902
- }
1903
- for (const [credId, usages] of Object.entries(credentialUsageMap)) if (credentialReferencesObject[credId]) credentialReferencesObject[credId].usedBy = usages;
1904
- return {
1905
- id: this.projectId,
1906
- name: this.projectName,
1907
- description: this.projectDescription || "",
1908
- models: this.models,
1909
- stopWhen: this.stopWhen,
1910
- agents: agentsObject,
1911
- tools: toolsObject,
1912
- functionTools: Object.keys(functionToolsObject).length > 0 ? functionToolsObject : void 0,
1913
- functions: Object.keys(functionsObject).length > 0 ? functionsObject : void 0,
1914
- dataComponents: Object.keys(dataComponentsObject).length > 0 ? dataComponentsObject : void 0,
1915
- artifactComponents: Object.keys(artifactComponentsObject).length > 0 ? artifactComponentsObject : void 0,
1916
- externalAgents: Object.keys(externalAgentsObject).length > 0 ? externalAgentsObject : void 0,
1917
- credentialReferences: Object.keys(credentialReferencesObject).length > 0 ? credentialReferencesObject : void 0,
1918
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1919
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1920
- };
1921
- }
1922
- };
1923
-
1924
- //#endregion
1925
- //#region src/status-component.ts
1926
- const logger$4 = (0, __inkeep_agents_core.getLogger)("statusComponent");
1927
- var StatusComponent = class {
1928
- config;
1929
- constructor(config) {
1930
- let processedDetailsSchema;
1931
- if (config.detailsSchema && (0, __inkeep_agents_core_utils_schema_conversion.isZodSchema)(config.detailsSchema)) {
1932
- const jsonSchema = (0, __inkeep_agents_core_utils_schema_conversion.convertZodToJsonSchema)(config.detailsSchema);
1933
- processedDetailsSchema = {
1934
- type: "object",
1935
- properties: jsonSchema.properties || {},
1936
- required: jsonSchema.required || void 0
1937
- };
1938
- } else processedDetailsSchema = config.detailsSchema;
1939
- this.config = {
1940
- ...config,
1941
- detailsSchema: processedDetailsSchema
1942
- };
1943
- logger$4.info({ statusComponentType: config.type }, "StatusComponent constructor initialized");
1944
- }
1945
- getType() {
1946
- return this.config.type;
1947
- }
1948
- getDescription() {
1949
- return this.config.description;
1950
- }
1951
- getDetailsSchema() {
1952
- return this.config.detailsSchema;
1953
- }
1954
- };
1955
-
1956
- //#endregion
1957
- //#region src/tool.ts
1958
- const logger$3 = (0, __inkeep_agents_core.getLogger)("tool");
1959
- var Tool = class {
1960
- config;
1961
- baseURL;
1962
- tenantId;
1963
- initialized = false;
1964
- projectId;
1965
- constructor(config) {
1966
- this.config = config;
1967
- this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
1968
- this.tenantId = "default";
1969
- this.projectId = "default";
1970
- logger$3.info({
1971
- Id: this.getId(),
1972
- Name: config.name
1973
- }, "Tool constructor initialized");
1974
- }
1975
- setContext(tenantId, projectId, baseURL) {
1976
- this.tenantId = tenantId;
1977
- this.projectId = projectId;
1978
- if (baseURL) this.baseURL = baseURL;
1979
- }
1980
- getId() {
1981
- return this.config.id;
1982
- }
1983
- getName() {
1984
- return this.config.name;
1985
- }
1986
- getDescription() {
1987
- return this.config.description || "";
1988
- }
1989
- getServerUrl() {
1990
- return this.config.serverUrl;
1991
- }
1992
- getActiveTools() {
1993
- return this.config.activeTools;
1994
- }
1995
- getCredentialReferenceId() {
1996
- return this.config.credential?.id;
1997
- }
1998
- async init(options) {
1999
- if (this.initialized) return;
2000
- try {
2001
- if (!options?.skipDatabaseRegistration) await this.upsertTool();
2002
- logger$3.info({ toolId: this.getId() }, "Tool initialized successfully");
2003
- this.initialized = true;
2004
- } catch (error) {
2005
- logger$3.error({
2006
- toolId: this.getId(),
2007
- error: error instanceof Error ? error.message : "Unknown error"
2008
- }, "Failed to initialize tool");
2009
- throw error;
2010
- }
2011
- }
2012
- async upsertTool() {
2013
- const toolDataForUpdate = {
2014
- id: this.getId(),
2015
- name: this.config.name,
2016
- credentialReferenceId: this.config.credential?.id ?? null,
2017
- headers: this.config.headers ?? null,
2018
- imageUrl: this.config.imageUrl,
2019
- config: {
2020
- type: "mcp",
2021
- mcp: {
2022
- server: { url: this.config.serverUrl },
2023
- transport: this.config.transport,
2024
- activeTools: this.config.activeTools
2025
- }
2026
- }
2027
- };
2028
- const toolDataForCreate = { ...toolDataForUpdate };
2029
- logger$3.info({ toolDataForCreate }, "toolDataForCreate");
2030
- const updateResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/tools/${this.getId()}`, {
2031
- method: "PUT",
2032
- headers: { "Content-Type": "application/json" },
2033
- body: JSON.stringify(toolDataForUpdate)
2034
- });
2035
- logger$3.info({ updateResponse }, "tool updateResponse");
2036
- if (updateResponse.ok) {
2037
- logger$3.info({ toolId: this.getId() }, "Tool updated successfully");
2038
- return;
2039
- }
2040
- if (updateResponse.status === 404) {
2041
- logger$3.info({ toolId: this.getId() }, "Tool not found, creating new tool");
2042
- const createResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/tools`, {
2043
- method: "POST",
2044
- headers: { "Content-Type": "application/json" },
2045
- body: JSON.stringify(toolDataForCreate)
2046
- });
2047
- if (!createResponse.ok) throw new Error(`Failed to create tool: ${createResponse.status}`);
2048
- logger$3.info({ toolId: this.getId() }, "Tool created successfully");
2049
- return;
2050
- }
2051
- throw new Error(`Failed to update tool: ${updateResponse.status}`);
2052
- }
2053
- /**
2054
- * Creates a new AgentMcpConfig with the given configuration.
2055
- *
2056
- * @param config - The configuration for the AgentMcpConfig
2057
- * @returns A new AgentMcpConfig
2058
- *
2059
- * example:
2060
- * ```typescript
2061
- * const tool = new Tool({
2062
- * id: 'tool-id',
2063
- * name: 'Tool Name',
2064
- * serverUrl: 'https://example.com/mcp',
2065
- * });
2066
- * const agentMcpConfig = tool.with({ selectedTools: ['tool-1', 'tool-2'], headers: { 'Authorization': 'Bearer token' } });
2067
- * ```
2068
- */
2069
- with(config) {
2070
- const { selectedTools, toolPolicies } = (0, __inkeep_agents_core.normalizeToolSelections)(config.selectedTools ?? void 0);
2071
- const isUnspecified = config.selectedTools === void 0 || config.selectedTools === null;
2072
- const resolvedSelectedTools = isUnspecified ? void 0 : selectedTools;
2073
- const resolvedToolPolicies = isUnspecified || Object.keys(toolPolicies).length === 0 ? void 0 : toolPolicies;
2074
- return {
2075
- server: this,
2076
- selectedTools: resolvedSelectedTools,
2077
- headers: config.headers,
2078
- toolPolicies: resolvedToolPolicies
2079
- };
2080
- }
2081
- };
2082
-
2083
- //#endregion
2084
- //#region src/utils/tool-normalization.ts
2085
- /**
2086
- * Type guard to check if a value is an AgentMcpConfig
2087
- */
2088
- function isAgentMcpConfig(value) {
2089
- return value !== null && typeof value === "object" && "server" in value && value.server && typeof value.server === "object";
2090
- }
2091
- /**
2092
- * Type guard to check if a value is a Tool instance
2093
- */
2094
- function isTool(value) {
2095
- return value !== null && typeof value === "object" && "config" in value && (typeof value.getId === "function" || "id" in value);
2096
- }
2097
- /**
2098
- * Safely extracts tool information from AgentCanUseType with proper typing
2099
- */
2100
- function normalizeAgentCanUseType(value, fallbackName) {
2101
- if (isAgentMcpConfig(value)) return {
2102
- tool: value.server,
2103
- toolId: value.server.getId(),
2104
- selectedTools: value.selectedTools,
2105
- headers: value.headers,
2106
- toolPolicies: value.toolPolicies,
2107
- isWrapped: true
2108
- };
2109
- if (isTool(value)) return {
2110
- tool: value,
2111
- toolId: value.getId?.() || value.id || fallbackName || "unknown",
2112
- isWrapped: false
2113
- };
2114
- throw new Error(`Invalid AgentCanUseType: expected Tool or AgentMcpConfig, got ${typeof value}`);
2115
- }
2116
-
2117
- //#endregion
2118
- //#region src/subAgent.ts
2119
- const logger$2 = (0, __inkeep_agents_core.getLogger)("agent");
2120
- function resolveGetter(value) {
2121
- if (typeof value === "function") return value();
2122
- return value;
2123
- }
2124
- var SubAgent = class {
2125
- config;
2126
- type = "internal";
2127
- baseURL;
2128
- tenantId;
2129
- projectId;
2130
- initialized = false;
2131
- constructor(config) {
2132
- this.config = {
2133
- ...config,
2134
- type: "internal"
2135
- };
2136
- this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
2137
- this.tenantId = "default";
2138
- this.projectId = "default";
2139
- logger$2.info({
2140
- tenantId: this.tenantId,
2141
- subAgentId: this.config.id,
2142
- agentName: config.name
2143
- }, "Agent constructor initialized");
2144
- }
2145
- setContext(tenantId, projectId, baseURL) {
2146
- this.tenantId = tenantId;
2147
- this.projectId = projectId;
2148
- if (baseURL) this.baseURL = baseURL;
2149
- }
2150
- getId() {
2151
- return this.config.id;
2152
- }
2153
- getName() {
2154
- return this.config.name;
2155
- }
2156
- getInstructions() {
2157
- return this.config.prompt || "";
2158
- }
2159
- /**
2160
- * Get the agent's description (the human-readable description field)
2161
- */
2162
- getDescription() {
2163
- return this.config.description || "";
2164
- }
2165
- getTools() {
2166
- const tools = resolveGetter(this.config.canUse);
2167
- if (!tools) return {};
2168
- if (!Array.isArray(tools)) throw new Error("tools getter must return an array");
2169
- const toolRecord = {};
2170
- for (const tool of tools) if (tool && typeof tool === "object") {
2171
- let id;
2172
- let toolInstance;
2173
- if (isAgentMcpConfig(tool)) {
2174
- id = tool.server.getId();
2175
- toolInstance = tool.server;
2176
- toolInstance.selectedTools = tool.selectedTools;
2177
- toolInstance.headers = tool.headers;
2178
- toolInstance.toolPolicies = tool.toolPolicies;
2179
- } else {
2180
- toolInstance = tool;
2181
- id = toolInstance.getId();
2182
- }
2183
- if (id) toolRecord[id] = toolInstance;
2184
- }
2185
- return toolRecord;
2186
- }
2187
- getModels() {
2188
- return this.config.models;
2189
- }
2190
- setModels(models) {
2191
- this.config.models = models;
2192
- }
2193
- getTransfers() {
2194
- return typeof this.config.canTransferTo === "function" ? this.config.canTransferTo() : [];
2195
- }
2196
- getSubAgentDelegates() {
2197
- return typeof this.config.canDelegateTo === "function" ? this.config.canDelegateTo().filter((delegate) => {
2198
- if (typeof delegate === "object" && "externalAgent" in delegate) return false;
2199
- if (typeof delegate === "object" && "agent" in delegate) return false;
2200
- if (typeof delegate === "object" && "toFullAgentDefinition" in delegate) return false;
2201
- if (typeof delegate === "object" && "type" in delegate && delegate.type === "external") return false;
2202
- return true;
2203
- }) : [];
2204
- }
2205
- getExternalAgentDelegates() {
2206
- if (typeof this.config.canDelegateTo !== "function") return [];
2207
- return this.config.canDelegateTo().filter((delegate) => {
2208
- if (typeof delegate === "object" && "externalAgent" in delegate) return true;
2209
- if (typeof delegate === "object" && "type" in delegate && delegate.type === "external") return true;
2210
- return false;
2211
- }).map((delegate) => {
2212
- if ("externalAgent" in delegate) return delegate;
2213
- return {
2214
- externalAgent: delegate,
2215
- headers: void 0
2216
- };
2217
- });
2218
- }
2219
- getTeamAgentDelegates() {
2220
- if (typeof this.config.canDelegateTo !== "function") return [];
2221
- return this.config.canDelegateTo().filter((delegate) => {
2222
- if (typeof delegate === "object" && "agent" in delegate) return true;
2223
- if (typeof delegate === "object" && "toFullAgentDefinition" in delegate) return true;
2224
- return false;
2225
- }).map((delegate) => {
2226
- if ("agent" in delegate) return delegate;
2227
- return {
2228
- agent: delegate,
2229
- headers: void 0
2230
- };
2231
- });
2232
- }
2233
- getDelegates() {
2234
- return [
2235
- ...this.getSubAgentDelegates(),
2236
- ...this.getTeamAgentDelegates(),
2237
- ...this.getExternalAgentDelegates()
2238
- ];
2239
- }
2240
- getDataComponents() {
2241
- return (resolveGetter(this.config.dataComponents) || []).map((comp) => {
2242
- if (comp && typeof comp.getId === "function") return {
2243
- id: comp.getId(),
2244
- name: comp.getName(),
2245
- description: comp.getDescription(),
2246
- props: comp.getProps(),
2247
- render: comp.getRender?.() || null
2248
- };
2249
- if (comp && typeof comp === "object" && comp.props && (0, __inkeep_agents_core_utils_schema_conversion.isZodSchema)(comp.props)) return {
2250
- id: comp.id,
2251
- name: comp.name,
2252
- description: comp.description,
2253
- props: (0, __inkeep_agents_core_utils_schema_conversion.convertZodToJsonSchemaWithPreview)(comp.props),
2254
- render: comp.render || null
2255
- };
2256
- return comp;
2257
- });
2258
- }
2259
- getArtifactComponents() {
2260
- return (resolveGetter(this.config.artifactComponents) || []).map((comp) => {
2261
- if (comp && typeof comp.getId === "function") return {
2262
- id: comp.getId(),
2263
- name: comp.getName(),
2264
- description: comp.getDescription(),
2265
- props: comp.getProps?.() || comp.props
2266
- };
2267
- if (comp && typeof comp === "object" && comp.props && (0, __inkeep_agents_core_utils_schema_conversion.isZodSchema)(comp.props)) return {
2268
- id: comp.id,
2269
- name: comp.name,
2270
- description: comp.description,
2271
- props: (0, __inkeep_agents_core_utils_schema_conversion.convertZodToJsonSchemaWithPreview)(comp.props)
2272
- };
2273
- return comp;
2274
- });
2275
- }
2276
- addTool(_name, tool) {
2277
- const existingTools = this.config.canUse ? this.config.canUse() : [];
2278
- this.config.canUse = () => [...existingTools, tool];
2279
- }
2280
- addTransfer(...agents) {
2281
- if (typeof this.config.canTransferTo === "function") {
2282
- const existingTransfers = this.config.canTransferTo;
2283
- this.config.canTransferTo = () => [...existingTransfers(), ...agents];
2284
- } else this.config.canTransferTo = () => agents;
2285
- }
2286
- addDelegate(...agents) {
2287
- if (typeof this.config.canDelegateTo === "function") {
2288
- const existingDelegates = this.config.canDelegateTo;
2289
- this.config.canDelegateTo = () => [...existingDelegates(), ...agents];
2290
- } else this.config.canDelegateTo = () => agents;
2291
- }
2292
- async init() {
2293
- if (this.initialized) return;
2294
- try {
2295
- await this.upsertAgent();
2296
- await this.loadDataComponents();
2297
- await this.loadArtifactComponents();
2298
- await this.saveToolsAndRelations();
2299
- await this.saveDataComponents();
2300
- await this.saveArtifactComponents();
2301
- logger$2.info({ subAgentId: this.getId() }, "Agent initialized successfully");
2302
- this.initialized = true;
2303
- } catch (error) {
2304
- logger$2.error({
2305
- subAgentId: this.getId(),
2306
- error: error instanceof Error ? error.message : "Unknown error"
2307
- }, "Failed to initialize agent");
2308
- throw error;
2309
- }
2310
- }
2311
- async upsertAgent() {
2312
- const agentData = {
2313
- id: this.getId(),
2314
- name: this.config.name,
2315
- description: this.config.description || "",
2316
- prompt: this.config.prompt || "",
2317
- conversationHistoryConfig: this.config.conversationHistoryConfig,
2318
- models: this.config.models,
2319
- stopWhen: this.config.stopWhen
2320
- };
2321
- const updateResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/agents/${this.getId()}`, {
2322
- method: "PUT",
2323
- headers: { "Content-Type": "application/json" },
2324
- body: JSON.stringify(agentData)
2325
- });
2326
- if (updateResponse.ok) {
2327
- logger$2.info({ subAgentId: this.getId() }, "Agent updated successfully");
2328
- return;
2329
- }
2330
- if (updateResponse.status === 404) {
2331
- logger$2.info({ subAgentId: this.getId() }, "Agent not found, creating new agent");
2332
- const createResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/agents`, {
2333
- method: "POST",
2334
- headers: { "Content-Type": "application/json" },
2335
- body: JSON.stringify(agentData)
2336
- });
2337
- if (!createResponse.ok) {
2338
- const errorText$1 = await createResponse.text().catch(() => "Unknown error");
2339
- throw new Error(`Failed to create agent: ${createResponse.status} ${createResponse.statusText} - ${errorText$1}`);
2340
- }
2341
- logger$2.info({ subAgentId: this.getId() }, "Agent created successfully");
2342
- return;
2343
- }
2344
- const errorText = await updateResponse.text().catch(() => "Unknown error");
2345
- throw new Error(`Failed to update agent: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`);
2346
- }
2347
- async saveToolsAndRelations() {
2348
- if (this.config.canUse) {
2349
- const tools = resolveGetter(this.config.canUse);
2350
- if (tools && Array.isArray(tools)) for (let i = 0; i < tools.length; i++) {
2351
- const toolConfig = tools[i];
2352
- try {
2353
- const normalizedTool = normalizeAgentCanUseType(toolConfig, `tool-${i}`);
2354
- await this.createTool(normalizedTool.toolId, toolConfig);
2355
- } catch (error) {
2356
- logger$2.error({
2357
- toolId: isAgentMcpConfig(toolConfig) ? toolConfig.server.getId() : toolConfig.getId?.(),
2358
- error: error instanceof Error ? error.message : "Unknown error"
2359
- }, "Tool creation failed");
2360
- throw error;
2361
- }
2362
- }
2363
- }
2364
- }
2365
- async saveDataComponents() {
2366
- logger$2.info({ dataComponents: this.config.dataComponents }, "dataComponents and config");
2367
- const components = resolveGetter(this.config.dataComponents);
2368
- if (components) for (const dataComponent$1 of components) {
2369
- const plainComponent = dataComponent$1 && typeof dataComponent$1.getId === "function" ? {
2370
- id: dataComponent$1.getId(),
2371
- name: dataComponent$1.getName(),
2372
- description: dataComponent$1.getDescription(),
2373
- props: dataComponent$1.getProps()
2374
- } : dataComponent$1;
2375
- await this.createDataComponent(plainComponent);
2376
- }
2377
- }
2378
- async saveArtifactComponents() {
2379
- logger$2.info({ artifactComponents: this.config.artifactComponents }, "artifactComponents and config");
2380
- const components = resolveGetter(this.config.artifactComponents);
2381
- if (components) for (const artifactComponent$1 of components) {
2382
- const plainComponent = artifactComponent$1 && typeof artifactComponent$1.getId === "function" ? {
2383
- id: artifactComponent$1.getId(),
2384
- name: artifactComponent$1.getName(),
2385
- description: artifactComponent$1.getDescription(),
2386
- props: artifactComponent$1.getProps?.() || artifactComponent$1.props
2387
- } : artifactComponent$1;
2388
- await this.createArtifactComponent(plainComponent);
2389
- }
2390
- }
2391
- async loadDataComponents() {
2392
- try {
2393
- const dbDataComponents = [].map((component) => ({
2394
- id: component.id,
2395
- name: component.name,
2396
- description: component.description,
2397
- props: component.props,
2398
- createdAt: component.createdAt,
2399
- updatedAt: component.updatedAt
2400
- }));
2401
- const configComponents = resolveGetter(this.config.dataComponents) || [];
2402
- const normalizedConfigComponents = configComponents.map((comp) => {
2403
- if (comp && typeof comp.getId === "function") return {
2404
- id: comp.getId(),
2405
- name: comp.getName(),
2406
- description: comp.getDescription(),
2407
- props: comp.getProps()
2408
- };
2409
- return comp;
2410
- });
2411
- const uniqueComponents = [...dbDataComponents, ...normalizedConfigComponents].reduce((acc, component) => {
2412
- const componentId = typeof component.getId === "function" ? component.getId() : component.id;
2413
- const existingIndex = acc.findIndex((c) => {
2414
- return (typeof c.getId === "function" ? c.getId() : c.id) === componentId;
2415
- });
2416
- if (existingIndex >= 0) acc[existingIndex] = component;
2417
- else acc.push(component);
2418
- return acc;
2419
- }, []);
2420
- this.config.dataComponents = () => uniqueComponents;
2421
- logger$2.info({
2422
- subAgentId: this.getId(),
2423
- dbComponentCount: dbDataComponents.length,
2424
- configComponentCount: configComponents.length,
2425
- totalComponentCount: uniqueComponents.length
2426
- }, "Loaded and merged data components");
2427
- } catch (error) {
2428
- logger$2.error({
2429
- subAgentId: this.getId(),
2430
- error: error instanceof Error ? error.message : "Unknown error"
2431
- }, "Failed to load data components from database");
2432
- }
2433
- }
2434
- async loadArtifactComponents() {
2435
- try {
2436
- const dbArtifactComponents = [].map((component) => ({
2437
- id: component.id,
2438
- name: component.name,
2439
- description: component.description,
2440
- props: component.props,
2441
- createdAt: component.createdAt,
2442
- updatedAt: component.updatedAt
2443
- }));
2444
- const configComponents = resolveGetter(this.config.artifactComponents) || [];
2445
- const normalizedConfigComponents = configComponents.map((comp) => {
2446
- if (comp && typeof comp.getId === "function") return {
2447
- id: comp.getId(),
2448
- name: comp.getName(),
2449
- description: comp.getDescription(),
2450
- props: comp.getProps?.() || comp.props
2451
- };
2452
- return comp;
2453
- });
2454
- const uniqueComponents = [...dbArtifactComponents, ...normalizedConfigComponents].reduce((acc, component) => {
2455
- const componentId = typeof component.getId === "function" ? component.getId() : component.id;
2456
- const existingIndex = acc.findIndex((c) => {
2457
- return (typeof c.getId === "function" ? c.getId() : c.id) === componentId;
2458
- });
2459
- if (existingIndex >= 0) acc[existingIndex] = component;
2460
- else acc.push(component);
2461
- return acc;
2462
- }, []);
2463
- this.config.artifactComponents = () => uniqueComponents;
2464
- logger$2.info({
2465
- subAgentId: this.getId(),
2466
- dbComponentCount: dbArtifactComponents.length,
2467
- configComponentCount: configComponents.length,
2468
- totalComponentCount: uniqueComponents.length
2469
- }, "Loaded and merged artifact components");
2470
- } catch (error) {
2471
- logger$2.error({
2472
- subAgentId: this.getId(),
2473
- error: error instanceof Error ? error.message : "Unknown error"
2474
- }, "Failed to load artifact components from database");
2475
- }
2476
- }
2477
- async createFunctionTool(toolId, functionTool$1) {
2478
- try {
2479
- const functionData = functionTool$1.serializeFunction();
2480
- const toolData = functionTool$1.serializeTool();
2481
- const functionUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/projects/${this.projectId}/functions`;
2482
- logger$2.info({
2483
- agentId: this.getId(),
2484
- toolId,
2485
- functionUrl
2486
- }, "Attempting to create global function");
2487
- const functionResponse = await fetch(functionUrl, {
2488
- method: "POST",
2489
- headers: { "Content-Type": "application/json" },
2490
- body: JSON.stringify({
2491
- id: functionData.id,
2492
- inputSchema: functionData.inputSchema,
2493
- executeCode: functionData.executeCode,
2494
- dependencies: functionData.dependencies
2495
- })
2496
- });
2497
- logger$2.info({
2498
- agentId: this.getId(),
2499
- toolId,
2500
- functionStatus: functionResponse.status,
2501
- functionStatusText: functionResponse.statusText
2502
- }, "Function creation response received");
2503
- if (!functionResponse.ok) {
2504
- const errorText = await functionResponse.text();
2505
- logger$2.error({
2506
- agentId: this.getId(),
2507
- toolId,
2508
- functionStatus: functionResponse.status,
2509
- functionStatusText: functionResponse.statusText,
2510
- errorText
2511
- }, "Function creation failed");
2512
- throw new Error(`Failed to create function: ${functionResponse.status} ${errorText}`);
2513
- }
2514
- const toolUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/projects/${this.projectId}/tools`;
2515
- logger$2.info({
2516
- agentId: this.getId(),
2517
- toolId,
2518
- toolUrl
2519
- }, "Attempting to create function tool");
2520
- const toolResponse = await fetch(toolUrl, {
2521
- method: "POST",
2522
- headers: { "Content-Type": "application/json" },
2523
- body: JSON.stringify({
2524
- id: toolData.id,
2525
- name: toolData.name,
2526
- description: toolData.description,
2527
- functionId: toolData.functionId,
2528
- config: { type: "function" }
2529
- })
2530
- });
2531
- logger$2.info({
2532
- agentId: this.getId(),
2533
- toolId,
2534
- toolStatus: toolResponse.status,
2535
- toolStatusText: toolResponse.statusText
2536
- }, "Tool creation response received");
2537
- if (!toolResponse.ok) {
2538
- const errorText = await toolResponse.text();
2539
- logger$2.error({
2540
- agentId: this.getId(),
2541
- toolId,
2542
- toolStatus: toolResponse.status,
2543
- toolStatusText: toolResponse.statusText,
2544
- errorText
2545
- }, "Tool creation failed");
2546
- throw new Error(`Failed to create tool: ${toolResponse.status} ${errorText}`);
2547
- }
2548
- await this.createAgentToolRelation(toolData.id);
2549
- logger$2.info({
2550
- agentId: this.getId(),
2551
- functionId: functionData.id,
2552
- toolId: toolData.id
2553
- }, "Function and tool created successfully");
2554
- } catch (error) {
2555
- logger$2.error({
2556
- agentId: this.getId(),
2557
- toolId,
2558
- error: error instanceof Error ? error.message : "Unknown error",
2559
- stack: error instanceof Error ? error.stack : void 0
2560
- }, "Failed to create function tool");
2561
- throw error;
2562
- }
2563
- }
2564
- async createTool(toolId, toolConfig) {
2565
- try {
2566
- if (toolConfig instanceof FunctionTool) {
2567
- await this.createFunctionTool(toolId, toolConfig);
2568
- return;
2569
- }
2570
- if (toolConfig.type === "function") {
2571
- logger$2.info({
2572
- subAgentId: this.getId(),
2573
- toolId
2574
- }, "Skipping function tool creation - will be handled at runtime");
2575
- return;
2576
- }
2577
- let tool;
2578
- let selectedTools;
2579
- let headers;
2580
- let toolPolicies;
2581
- try {
2582
- const normalizedTool = normalizeAgentCanUseType(toolConfig, toolId);
2583
- tool = normalizedTool.tool;
2584
- selectedTools = normalizedTool.selectedTools;
2585
- headers = normalizedTool.headers;
2586
- toolPolicies = normalizedTool.toolPolicies;
2587
- tool.setContext(this.tenantId, this.projectId);
2588
- await tool.init();
2589
- } catch (_) {
2590
- tool = new Tool({
2591
- id: toolId,
2592
- name: toolConfig.name || toolId,
2593
- description: toolConfig.description || `MCP tool: ${toolId}`,
2594
- serverUrl: toolConfig.config?.serverUrl || toolConfig.serverUrl || "http://localhost:3000",
2595
- activeTools: toolConfig.config?.mcp?.activeTools,
2596
- credential: toolConfig.credential
2597
- });
2598
- tool.setContext(this.tenantId, this.projectId);
2599
- await tool.init();
2600
- }
2601
- await this.createAgentToolRelation(tool.getId(), selectedTools, headers, toolPolicies);
2602
- logger$2.info({
2603
- subAgentId: this.getId(),
2604
- toolId: tool.getId()
2605
- }, "Tool created and linked to agent");
2606
- } catch (error) {
2607
- logger$2.error({
2608
- subAgentId: this.getId(),
2609
- toolId,
2610
- error: error instanceof Error ? error.message : "Unknown error"
2611
- }, "Failed to create tool");
2612
- throw error;
2613
- }
2614
- }
2615
- async createDataComponent(dataComponent$1) {
2616
- try {
2617
- const dc = new DataComponent({
2618
- id: dataComponent$1.id,
2619
- name: dataComponent$1.name,
2620
- description: dataComponent$1.description,
2621
- props: dataComponent$1.props,
2622
- render: dataComponent$1.render
2623
- });
2624
- dc.setContext(this.tenantId, this.projectId);
2625
- await dc.init();
2626
- await this.createAgentDataComponentRelation(dc.getId());
2627
- logger$2.info({
2628
- subAgentId: this.getId(),
2629
- dataComponentId: dc.getId()
2630
- }, "DataComponent created and linked to agent");
2631
- } catch (error) {
2632
- logger$2.error({
2633
- subAgentId: this.getId(),
2634
- dataComponentName: dataComponent$1.name,
2635
- error: error instanceof Error ? error.message : "Unknown error"
2636
- }, "Failed to create data component");
2637
- throw error;
2638
- }
2639
- }
2640
- async createArtifactComponent(artifactComponent$1) {
2641
- try {
2642
- const ac = new ArtifactComponent({
2643
- id: artifactComponent$1.id,
2644
- name: artifactComponent$1.name,
2645
- description: artifactComponent$1.description,
2646
- props: artifactComponent$1.props
2647
- });
2648
- ac.setContext(this.tenantId, this.projectId);
2649
- await ac.init();
2650
- await this.createAgentArtifactComponentRelation(ac.getId());
2651
- logger$2.info({
2652
- subAgentId: this.getId(),
2653
- artifactComponentId: ac.getId()
2654
- }, "ArtifactComponent created and linked to agent");
2655
- } catch (error) {
2656
- logger$2.error({
2657
- subAgentId: this.getId(),
2658
- artifactComponentName: artifactComponent$1.name,
2659
- error: error instanceof Error ? error.message : "Unknown error"
2660
- }, "Failed to create artifact component");
2661
- throw error;
2662
- }
2663
- }
2664
- async createAgentDataComponentRelation(dataComponentId) {
2665
- const relationResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/agent-data-components`, {
2666
- method: "POST",
2667
- headers: { "Content-Type": "application/json" },
2668
- body: JSON.stringify({
2669
- id: `${this.getId()}-dc-${dataComponentId}`,
2670
- tenantId: this.tenantId,
2671
- subAgentId: this.getId(),
2672
- dataComponentId
2673
- })
2674
- });
2675
- if (!relationResponse.ok) throw new Error(`Failed to create agent-dataComponent relation: ${relationResponse.status} ${relationResponse.statusText}`);
2676
- logger$2.info({
2677
- subAgentId: this.getId(),
2678
- dataComponentId
2679
- }, "Created agent-dataComponent relation");
2680
- }
2681
- async createAgentArtifactComponentRelation(artifactComponentId) {
2682
- const relationResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/agent-artifact-components`, {
2683
- method: "POST",
2684
- headers: { "Content-Type": "application/json" },
2685
- body: JSON.stringify({
2686
- id: crypto.randomUUID(),
2687
- tenantId: this.tenantId,
2688
- subAgentId: this.getId(),
2689
- artifactComponentId
2690
- })
2691
- });
2692
- if (!relationResponse.ok) throw new Error(`Failed to create agent-artifactComponent relation: ${relationResponse.status} ${relationResponse.statusText}`);
2693
- logger$2.info({
2694
- subAgentId: this.getId(),
2695
- artifactComponentId
2696
- }, "Created agent-artifactComponent relation");
2697
- }
2698
- async createAgentToolRelation(toolId, selectedTools, headers, toolPolicies) {
2699
- const relationData = {
2700
- id: `${this.getId()}-tool-${toolId}`,
2701
- tenantId: this.tenantId,
2702
- projectId: this.projectId,
2703
- subAgentId: this.getId(),
2704
- toolId
2705
- };
2706
- if (selectedTools !== void 0) relationData.selectedTools = selectedTools;
2707
- if (headers !== void 0) relationData.headers = headers;
2708
- if (toolPolicies !== void 0 && Object.keys(toolPolicies).length > 0) relationData.toolPolicies = toolPolicies;
2709
- const relationResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/agent-tool-relations`, {
2710
- method: "POST",
2711
- headers: { "Content-Type": "application/json" },
2712
- body: JSON.stringify(relationData)
2713
- });
2714
- if (!relationResponse.ok) {
2715
- const errorBody = await relationResponse.text().catch(() => "Unknown error");
2716
- throw new Error(`Failed to create agent-tool relation: ${relationResponse.status} - ${errorBody}`);
2717
- }
2718
- }
2719
- };
2720
-
2721
- //#endregion
2722
- //#region src/builderFunctions.ts
2723
- /**
2724
- * Helper function to create agent - OpenAI style
2725
- */
2726
- function agent(config) {
2727
- return new Agent(config);
2728
- }
2729
- /**
2730
- * Helper function to create projects - OpenAI style
2731
- *
2732
- * Projects are the top-level organizational unit that contains Agents, Sub Agents, and shared configurations.
2733
- * They provide model inheritance and execution limits that cascade down to Agents and Sub Agents.
2734
- *
2735
- * @param config - Project configuration
2736
- * @returns A new Project instance
2737
- *
2738
- * @example
2739
- * ```typescript
2740
- * const customerSupport = project({
2741
- * id: 'customer-support-project',
2742
- * name: 'Customer Support System',
2743
- * description: 'Multi-agent customer support system',
2744
- * models: {
2745
- * base: { model: 'gpt-4.1-mini' },
2746
- * structuredOutput: { model: 'gpt-4.1' }
2747
- * },
2748
- * stopWhen: {
2749
- * transferCountIs: 10,
2750
- * stepCountIs: 50
2751
- * },
2752
- * agent: () => [
2753
- * agent({
2754
- * id: 'support-agent',
2755
- * name: 'Support Agent',
2756
- * // ... agent config
2757
- * })
2758
- * ]
2759
- * });
2760
- * ```
2761
- */
2762
- function project(config) {
2763
- return new Project(config);
2764
- }
2765
- /**
2766
- * Creates a new agent with stable ID enforcement.
2767
- *
2768
- * Agents require explicit stable IDs to ensure consistency across deployments.
2769
- * This is different from tools which auto-generate IDs from their names.
2770
- *
2771
- * @param config - Agent configuration including required stable ID
2772
- * @returns A new SubAgent instance
2773
- * @throws {Error} If config.id is not provided
2774
- *
2775
- * @example
2776
- * ```typescript
2777
- * const myAgent = agent({
2778
- * id: 'customer-support-agent',
2779
- * name: 'Customer Support',
2780
- * prompt: 'Help customers with their questions'
2781
- * });
2782
- * ```
2783
- */
2784
- function subAgent(config) {
2785
- if (!config.id) throw new Error("Sub-Agent ID is required. Sub-Agents must have stable IDs for consistency across deployments.");
2786
- return new SubAgent(config);
2787
- }
2788
- /**
2789
- * Creates a credential reference for authentication.
2790
- *
2791
- * Credentials are used to authenticate with external services.
2792
- * They should be stored securely and referenced by ID.
2793
- *
2794
- * @param config - Credential configuration
2795
- * @returns A validated credential reference
2796
- *
2797
- * @example
2798
- * ```typescript
2799
- * const apiCredential = credential({
2800
- * id: 'github-token',
2801
- * name: 'GitHub Token',
2802
- * type: 'bearer',
2803
- * value: process.env.GITHUB_TOKEN
2804
- * });
2805
- * ```
2806
- */
2807
- function credential(config) {
2808
- try {
2809
- return __inkeep_agents_core.CredentialReferenceApiInsertSchema.parse(config);
2810
- } catch (error) {
2811
- if (error instanceof Error) {
2812
- const credId = config.id || "unknown";
2813
- throw new Error(`Invalid credential '${credId}': ${error.message}`);
2814
- }
2815
- throw error;
2816
- }
2817
- }
2818
- /**
2819
- * Creates an MCP (Model Context Protocol) server for tool functionality.
2820
- *
2821
- * MCP servers provide tool functionality through a standardized protocol.
2822
- * They can be remote services accessed via HTTP/WebSocket.
2823
- *
2824
- * @param config - MCP server configuration
2825
- * @returns A Tool instance configured as an MCP server
2826
- * @throws {Error} If serverUrl is not provided
2827
- *
2828
- * @example
2829
- * ```typescript
2830
- * // Remote MCP server
2831
- * const apiServer = mcpServer({
2832
- * name: 'external_api',
2833
- * description: 'External API service',
2834
- * serverUrl: 'https://api.example.com/mcp'
2835
- * });
2836
- *
2837
- * // With authentication
2838
- * const secureServer = mcpServer({
2839
- * name: 'secure_api',
2840
- * description: 'Secure API service',
2841
- * serverUrl: 'https://secure.example.com/mcp',
2842
- * credential: credential({
2843
- * id: 'api-key',
2844
- * name: 'API Key',
2845
- * type: 'bearer',
2846
- * value: process.env.API_KEY
2847
- * })
2848
- * });
2849
- * ```
2850
- */
2851
- function mcpServer(config) {
2852
- if (!config.serverUrl) throw new Error("MCP server requires a serverUrl");
2853
- return new Tool({
2854
- id: config.id || generateIdFromName(config.name),
2855
- name: config.name,
2856
- description: config.description,
2857
- serverUrl: config.serverUrl,
2858
- credential: config.credential,
2859
- activeTools: config.activeTools,
2860
- headers: config.headers,
2861
- imageUrl: config.imageUrl,
2862
- transport: config.transport ? { type: config.transport } : void 0
2863
- });
2864
- }
2865
- /**
2866
- * Creates an MCP tool from a raw configuration object.
2867
- *
2868
- * This is a low-level builder for advanced use cases where you need
2869
- * full control over the MCPToolConfig. For most cases, use `mcpServer()`.
2870
- *
2871
- * @param config - Complete MCP tool configuration
2872
- * @returns A Tool instance
2873
- *
2874
- * @example
2875
- * ```typescript
2876
- * const customTool = mcpTool({
2877
- * id: 'custom-tool',
2878
- * name: 'Custom Tool',
2879
- * serverUrl: 'https://example.com/mcp',
2880
- * transport: { type: 'stdio' }
2881
- * });
2882
- * ```
2883
- */
2884
- function mcpTool(config) {
2885
- const configWithId = {
2886
- ...config,
2887
- id: config.id || generateIdFromName(config.name)
2888
- };
2889
- return new Tool(__inkeep_agents_core.MCPToolConfigSchema.parse(configWithId));
2890
- }
2891
- /**
2892
- * Creates an artifact component with automatic ID generation.
2893
- *
2894
- * Artifact components represent structured UI components that can
2895
- * be rendered with different levels of detail (summary vs full).
2896
- *
2897
- * @param config - Artifact component configuration
2898
- * @returns An ArtifactComponent instance
2899
- *
2900
- * @example
2901
- * ```typescript
2902
- * const productCard = artifactComponent({
2903
- * name: 'Product Card',
2904
- * description: 'Display product information',
2905
- * props: {
2906
- * type: 'object',
2907
- * properties: {
2908
- * title: { type: 'string', inPreview: true },
2909
- * price: { type: 'string', inPreview: true },
2910
- * description: { type: 'string' },
2911
- * image: { type: 'string' }
2912
- * }
2913
- * }
2914
- * });
2915
- * ```
2916
- */
2917
- function artifactComponent(config) {
2918
- return new ArtifactComponent({
2919
- ...config,
2920
- id: config.id || generateIdFromName(config.name)
2921
- });
2922
- }
2923
- /**
2924
- * Creates a data component with automatic ID generation.
2925
- *
2926
- * Data components represent structured data that can be
2927
- * passed between agents or used in processing.
2928
- *
2929
- * @param config - Data component configuration
2930
- * @returns A DataComponent instance
2931
- *
2932
- * @example
2933
- * ```typescript
2934
- * const userProfile = dataComponent({
2935
- * name: 'User Profile',
2936
- * description: 'User profile data',
2937
- * props: {
2938
- * userId: '123',
2939
- * name: 'John Doe',
2940
- * email: 'john@example.com'
2941
- * }
2942
- * });
2943
- * ```
2944
- */
2945
- function dataComponent(config) {
2946
- return new DataComponent({
2947
- ...config,
2948
- id: config.id || generateIdFromName(config.name)
2949
- });
2950
- }
2951
- /**
2952
- * Creates a status component for structured status updates.
2953
- *
2954
- * Status components define the structure of status updates
2955
- * that agents can generate during long-running operations.
2956
- *
2957
- * @param config - Status component configuration
2958
- * @returns A StatusComponent instance
2959
- *
2960
- * @example
2961
- * ```typescript
2962
- * import { z } from 'zod';
2963
- *
2964
- * const toolCallStatus = statusComponent({
2965
- * type: 'tool_call_summary',
2966
- * description: 'Summary of a tool execution',
2967
- * detailsSchema: z.object({
2968
- * tool_name: z.string(),
2969
- * summary: z.string(),
2970
- * status: z.enum(['success', 'error', 'in_progress'])
2971
- * })
2972
- * });
2973
- * ```
2974
- */
2975
- function statusComponent(config) {
2976
- return new StatusComponent(config);
2977
- }
2978
- /**
2979
- * (deprecated in favor of mcpTool.with()) Creates an agent MCP configuration.
2980
- *
2981
- * Agent MCP configurations are used to configure the MCP server for an agent.
2982
- *
2983
- * @param config - Agent MCP configuration
2984
- * @returns An AgentMcpConfig instance
2985
- */
2986
- function agentMcp(config) {
2987
- return {
2988
- server: config.server,
2989
- selectedTools: config.selectedTools,
2990
- headers: config.headers
2991
- };
2992
- }
2993
- /**
2994
- * Creates a function tool that executes user-defined code in a sandboxed environment.
2995
- *
2996
- * Function tools allow users to define custom logic that runs securely in isolated
2997
- * environments. Dependencies are installed automatically in the sandbox.
2998
- *
2999
- * @param config - Function tool configuration
3000
- * @returns A FunctionTool instance
3001
- *
3002
- * @example
3003
- * ```typescript
3004
- * const calculatorTool = functionTool({
3005
- * name: 'calculator',
3006
- * description: 'Performs basic math operations',
3007
- * inputSchema: {
3008
- * type: 'object',
3009
- * properties: {
3010
- * operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'] },
3011
- * a: { type: 'number' },
3012
- * b: { type: 'number' }
3013
- * },
3014
- * required: ['operation', 'a', 'b']
3015
- * },
3016
- * dependencies: {
3017
- * 'lodash': '^4.17.21'
3018
- * },
3019
- * execute: async (params) => {
3020
- * const { operation, a, b } = params;
3021
- * switch (operation) {
3022
- * case 'add': return { result: a + b };
3023
- * case 'subtract': return { result: a - b };
3024
- * case 'multiply': return { result: a * b };
3025
- * case 'divide': return { result: a / b };
3026
- * default: throw new Error(`Unknown operation: ${operation}`);
3027
- * }
3028
- * }
3029
- * });
3030
- * ```
3031
- */
3032
- function functionTool(config) {
3033
- return new FunctionTool(config);
3034
- }
3035
-
3036
- //#endregion
3037
- //#region src/utils/validateFunction.ts
3038
- /**
3039
- * Validates that a value is a function
3040
- * @param value - The value to check
3041
- * @param name - The name of the parameter (for error messages)
3042
- * @throws {Error} If the value is not a function
3043
- */
3044
- function validateFunction(value, name) {
3045
- if (typeof value !== "function") throw new Error(`${name} must be a function`);
3046
- }
3047
-
3048
- //#endregion
3049
- //#region src/builders.ts
3050
- /**
3051
- * Schema for transfer configuration (excluding function properties)
3052
- */
3053
- const TransferConfigSchema = zod.z.object({
3054
- agent: zod.z.instanceof(SubAgent),
3055
- description: zod.z.string().optional()
3056
- });
3057
- /**
3058
- * Creates a transfer configuration for agent transfers.
3059
- *
3060
- * Transfers allow one agent to hand off control to another agent
3061
- * based on optional conditions.
3062
- *
3063
- * @param targetAgent - The agent to transfer to
3064
- * @param description - Optional description of when/why to transfer
3065
- * @param condition - Optional function to determine if transfer should occur
3066
- * @returns A validated transfer configuration
3067
- *
3068
- * @example
3069
- * ```typescript
3070
- * // Simple transfer
3071
- * const transfer = transfer(supportAgent, 'Transfer to support');
3072
- *
3073
- * // Conditional transfer
3074
- * const conditionalHandoff = transfer(
3075
- * specialistAgent,
3076
- * 'Transfer to specialist for complex issues',
3077
- * (context) => context.complexity > 0.8
3078
- * );
3079
- * ```
3080
- */
3081
- function transfer(targetAgent, description, condition) {
3082
- if (condition !== void 0) validateFunction(condition, "condition");
3083
- const config = {
3084
- agent: targetAgent,
3085
- description: description || `Hand off to ${targetAgent.getName()}`,
3086
- condition
3087
- };
3088
- TransferConfigSchema.parse({
3089
- agent: config.agent,
3090
- description: config.description
3091
- });
3092
- return config;
3093
- }
3094
-
3095
- //#endregion
3096
- //#region src/credential-provider.ts
3097
- /**
3098
- * Default configuration using memory store
3099
- */
3100
- const DEFAULT_CONFIG = {
3101
- type: "memory",
3102
- id: "memory-default"
3103
- };
3104
- /**
3105
- * Simple in-memory credential store implementation
3106
- * Automatically loads from environment variables as fallback
3107
- */
3108
- var InMemoryStore = class {
3109
- id;
3110
- type = "memory";
3111
- credentials = /* @__PURE__ */ new Map();
3112
- constructor(id = "memory-default") {
3113
- this.id = id;
3114
- }
3115
- async get(key) {
3116
- const credential$1 = this.credentials.get(key);
3117
- if (!credential$1) {
3118
- const envValue = process.env[key];
3119
- if (envValue) {
3120
- this.credentials.set(key, envValue);
3121
- return envValue;
3122
- }
3123
- return null;
3124
- }
3125
- return credential$1;
3126
- }
3127
- async set(key, value, _metadata) {
3128
- this.credentials.set(key, value);
3129
- }
3130
- async has(key) {
3131
- return this.credentials.has(key) || !!process.env[key];
3132
- }
3133
- async delete(key) {
3134
- return this.credentials.delete(key);
3135
- }
3136
- async checkAvailability() {
3137
- return { available: true };
3138
- }
3139
- };
3140
- /**
3141
- * InkeepCredentialProvider - Unified credential management for Inkeep SDK
3142
- *
3143
- * Provides a clean abstraction over various credential storage backends.
3144
- * Cloud customers can use simple memory-based storage, while advanced
3145
- * users can integrate with OAuth providers like Nango.
3146
- *
3147
- * @example
3148
- * ```typescript
3149
- * // Default memory-based storage
3150
- * const provider = new InkeepCredentialProvider()
3151
- *
3152
- * // Store and retrieve credentials
3153
- * await provider.set('my-api-key', 'secret-value')
3154
- * const key = await provider.get('my-api-key')
3155
- *
3156
- * // Use environment variables automatically
3157
- * process.env.MY_TOKEN = 'env-token'
3158
- * const token = await provider.get('MY_TOKEN') // Returns 'env-token'
3159
- * ```
3160
- */
3161
- var InkeepCredentialProvider = class {
3162
- store;
3163
- constructor(config = DEFAULT_CONFIG) {
3164
- this.store = this.createStore(config);
3165
- }
3166
- /**
3167
- * Create the appropriate store based on configuration
3168
- */
3169
- createStore(config) {
3170
- switch (config.type) {
3171
- case "memory": return new InMemoryStore(config.id);
3172
- case "keychain": return this.createKeychainStore(config);
3173
- case "nango": return this.createNangoStore(config);
3174
- case "custom": return config.store;
3175
- default: throw new Error(`Unknown credential provider type: ${config.type}`);
3176
- }
3177
- }
3178
- /**
3179
- * Create keychain store with dynamic import
3180
- */
3181
- createKeychainStore(config) {
3182
- const storeId = config.id || "keychain-default";
3183
- return {
3184
- id: storeId,
3185
- type: "keychain",
3186
- get: async (key) => {
3187
- const { createKeyChainStore } = await import("@inkeep/agents-core/credential-stores");
3188
- return createKeyChainStore(storeId).get(key);
3189
- },
3190
- set: async (key, value, metadata) => {
3191
- const { createKeyChainStore } = await import("@inkeep/agents-core/credential-stores");
3192
- return createKeyChainStore(storeId).set(key, value, metadata);
3193
- },
3194
- has: async (key) => {
3195
- const { createKeyChainStore } = await import("@inkeep/agents-core/credential-stores");
3196
- return createKeyChainStore(storeId).has(key);
3197
- },
3198
- delete: async (key) => {
3199
- const { createKeyChainStore } = await import("@inkeep/agents-core/credential-stores");
3200
- return createKeyChainStore(storeId).delete(key);
3201
- },
3202
- checkAvailability: async () => {
3203
- try {
3204
- const { createKeyChainStore } = await import("@inkeep/agents-core/credential-stores");
3205
- return createKeyChainStore(storeId).checkAvailability();
3206
- } catch {
3207
- return {
3208
- available: false,
3209
- reason: "Keychain store requires keytar package to be installed"
3210
- };
3211
- }
3212
- }
3213
- };
3214
- }
3215
- /**
3216
- * Create Nango store with dynamic import
3217
- */
3218
- createNangoStore(config) {
3219
- const storeId = config.id || "nango-default";
3220
- const secretKey = config.secretKey;
3221
- const apiUrl = config.apiUrl;
3222
- return {
3223
- id: storeId,
3224
- type: "nango",
3225
- get: async (key) => {
3226
- const { createNangoCredentialStore } = await import("@inkeep/agents-core/credential-stores");
3227
- return createNangoCredentialStore(storeId, {
3228
- secretKey,
3229
- apiUrl
3230
- }).get(key);
3231
- },
3232
- set: async (key, value, metadata) => {
3233
- const { createNangoCredentialStore } = await import("@inkeep/agents-core/credential-stores");
3234
- return createNangoCredentialStore(storeId, {
3235
- secretKey,
3236
- apiUrl
3237
- }).set(key, value, metadata);
3238
- },
3239
- has: async (key) => {
3240
- const { createNangoCredentialStore } = await import("@inkeep/agents-core/credential-stores");
3241
- return createNangoCredentialStore(storeId, {
3242
- secretKey,
3243
- apiUrl
3244
- }).has(key);
3245
- },
3246
- delete: async (key) => {
3247
- const { createNangoCredentialStore } = await import("@inkeep/agents-core/credential-stores");
3248
- return createNangoCredentialStore(storeId, {
3249
- secretKey,
3250
- apiUrl
3251
- }).delete(key);
3252
- },
3253
- checkAvailability: async () => {
3254
- try {
3255
- const { createNangoCredentialStore } = await import("@inkeep/agents-core/credential-stores");
3256
- return createNangoCredentialStore(storeId, {
3257
- secretKey,
3258
- apiUrl
3259
- }).checkAvailability();
3260
- } catch (error) {
3261
- return {
3262
- available: false,
3263
- reason: error instanceof Error ? error.message : "Nango store requires @nangohq/node package and NANGO_SECRET_KEY"
3264
- };
3265
- }
3266
- }
3267
- };
3268
- }
3269
- get id() {
3270
- return this.store.id;
3271
- }
3272
- get type() {
3273
- return this.store.type;
3274
- }
3275
- /**
3276
- * Get a credential by key
3277
- * @param key - The credential key
3278
- * @returns The credential value or null if not found
3279
- */
3280
- async get(key) {
3281
- return this.store.get(key);
3282
- }
3283
- /**
3284
- * Set a credential
3285
- * @param key - The credential key
3286
- * @param value - The credential value
3287
- * @param metadata - Optional metadata
3288
- */
3289
- async set(key, value, metadata) {
3290
- return this.store.set(key, value, metadata);
3291
- }
3292
- /**
3293
- * Check if a credential exists
3294
- * @param key - The credential key
3295
- * @returns True if the credential exists
3296
- */
3297
- async has(key) {
3298
- return this.store.has(key);
3299
- }
3300
- /**
3301
- * Delete a credential
3302
- * @param key - The credential key
3303
- * @returns True if the credential was deleted
3304
- */
3305
- async delete(key) {
3306
- return this.store.delete(key);
3307
- }
3308
- /**
3309
- * Check if the credential store is available and functional
3310
- * @returns Availability status
3311
- */
3312
- async checkAvailability() {
3313
- return this.store.checkAvailability();
3314
- }
3315
- /**
3316
- * Get the underlying store (for advanced use cases)
3317
- */
3318
- getStore() {
3319
- return this.store;
3320
- }
3321
- };
3322
- /**
3323
- * Factory function to create an InkeepCredentialProvider
3324
- * @param config - Configuration options
3325
- * @returns A new InkeepCredentialProvider instance
3326
- */
3327
- function createCredentialProvider(config = DEFAULT_CONFIG) {
3328
- return new InkeepCredentialProvider(config);
3329
- }
3330
-
3331
- //#endregion
3332
- //#region src/credential-ref.ts
3333
- /**
3334
- * Create a reference to a credential by its ID.
3335
- * The credential must be defined in the environment files.
3336
- *
3337
- * @param id - The ID of the credential to reference
3338
- * @returns A credential reference that will be resolved at push time
3339
- *
3340
- * @example
3341
- * ```typescript
3342
- * const apiKeyRef = credentialRef('api-key');
3343
- *
3344
- * const fetchDef = fetchDefinition({
3345
- * credential: apiKeyRef,
3346
- * // ...
3347
- * });
3348
- * ```
3349
- */
3350
- function credentialRef(id) {
3351
- return {
3352
- __type: "credential-ref",
3353
- id
3354
- };
3355
- }
3356
- /**
3357
- * Type guard to check if a value is a credential reference
3358
- */
3359
- function isCredentialReference(value) {
3360
- return value && typeof value === "object" && value.__type === "credential-ref";
3361
- }
3362
-
3363
- //#endregion
3364
- //#region src/environment-settings.ts
3365
- /**
3366
- * Create a setting helper with TypeScript autocomplete
3367
- */
3368
- function createEnvironmentSettings(environments) {
3369
- return {
3370
- getEnvironmentCredential: (key) => {
3371
- const currentEnv = process.env.INKEEP_ENV || "development";
3372
- const env = environments[currentEnv];
3373
- if (!env) throw new Error(`Environment '${currentEnv}' not found. Available: ${Object.keys(environments).join(", ")}`);
3374
- const credential$1 = env.credentials?.[key];
3375
- if (!credential$1) throw new Error(`Credential '${String(key)}' not found in environment '${currentEnv}'`);
3376
- return credential$1;
3377
- },
3378
- getEnvironmentMcp: (key) => {
3379
- const currentEnv = process.env.INKEEP_ENV || "development";
3380
- const env = environments[currentEnv];
3381
- if (!env) throw new Error(`Environment '${currentEnv}' not found. Available: ${Object.keys(environments).join(", ")}`);
3382
- const mcpServer$1 = env.mcpServers?.[key];
3383
- if (!mcpServer$1) throw new Error(`MCP Server '${String(key)}' not found in environment '${currentEnv}'`);
3384
- return mcpServer$1;
3385
- },
3386
- getEnvironmentSetting: (key) => {
3387
- const currentEnv = process.env.INKEEP_ENV || "development";
3388
- const env = environments[currentEnv];
3389
- if (!env) throw new Error(`Environment '${currentEnv}' not found. Available: ${Object.keys(environments).join(", ")}`);
3390
- const credential$1 = env.credentials?.[key];
3391
- if (!credential$1) throw new Error(`Credential '${String(key)}' not found in environment '${currentEnv}'`);
3392
- return credential$1;
3393
- }
3394
- };
3395
- }
3396
- /**
3397
- * Create type-safe environment configurations
3398
- */
3399
- function registerEnvironmentSettings(config) {
3400
- return config;
3401
- }
3402
-
3403
- //#endregion
3404
- //#region src/external-agent.ts
3405
- const logger$1 = (0, __inkeep_agents_core.getLogger)("external-agent-builder");
3406
- var ExternalAgent = class {
3407
- config;
3408
- type = "external";
3409
- initialized = false;
3410
- tenantId;
3411
- projectId;
3412
- baseURL;
3413
- constructor(config) {
3414
- this.config = {
3415
- ...config,
3416
- type: "external"
3417
- };
3418
- this.tenantId = "default";
3419
- this.projectId = "default";
3420
- this.baseURL = this.config.baseUrl;
3421
- logger$1.debug({
3422
- externalAgentName: this.config.name,
3423
- baseUrl: this.config.baseUrl,
3424
- tenantId: this.tenantId
3425
- }, "External Agent constructor initialized");
3426
- }
3427
- /**
3428
- * Initialize the external agent by upserting it in the database
3429
- */
3430
- async init() {
3431
- if (this.initialized) return;
3432
- try {
3433
- await this.upsertExternalAgent();
3434
- logger$1.info({ externalSubAgentId: this.getId() }, "External agent initialized successfully");
3435
- this.initialized = true;
3436
- } catch (error) {
3437
- logger$1.error({
3438
- externalSubAgentId: this.getId(),
3439
- error: error instanceof Error ? error.message : "Unknown error"
3440
- }, "Failed to initialize external agent");
3441
- throw error;
3442
- }
3443
- }
3444
- setContext(tenantId, projectId) {
3445
- this.tenantId = tenantId;
3446
- this.projectId = projectId;
3447
- }
3448
- getId() {
3449
- return this.config.id;
3450
- }
3451
- with(options) {
3452
- return {
3453
- externalAgent: this,
3454
- headers: options.headers
3455
- };
3456
- }
3457
- async upsertExternalAgent() {
3458
- const externalAgentData = {
3459
- id: this.getId(),
3460
- name: this.config.name,
3461
- description: this.config.description,
3462
- baseUrl: this.config.baseUrl,
3463
- credentialReferenceId: this.config.credentialReference?.id || void 0
3464
- };
3465
- const updateResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/external-agents/${this.getId()}`, {
3466
- method: "PUT",
3467
- headers: { "Content-Type": "application/json" },
3468
- body: JSON.stringify(externalAgentData)
3469
- });
3470
- if (updateResponse.ok) {
3471
- logger$1.info({ externalSubAgentId: this.getId() }, "External agent updated successfully");
3472
- return;
3473
- }
3474
- if (updateResponse.status === 404) {
3475
- logger$1.info({ externalSubAgentId: this.getId() }, "External agent not found, creating new external agent");
3476
- const createResponse = await fetch(`${this.baseURL}/tenants/${this.tenantId}/projects/${this.projectId}/external-agents`, {
3477
- method: "POST",
3478
- headers: { "Content-Type": "application/json" },
3479
- body: JSON.stringify(externalAgentData)
3480
- });
3481
- if (!createResponse.ok) {
3482
- const errorText$1 = await createResponse.text().catch(() => "Unknown error");
3483
- throw new Error(`Failed to create external agent: ${createResponse.status} ${createResponse.statusText} - ${errorText$1}`);
3484
- }
3485
- logger$1.info({ externalSubAgentId: this.getId() }, "External agent created successfully");
3486
- return;
3487
- }
3488
- const errorText = await updateResponse.text().catch(() => "Unknown error");
3489
- throw new Error(`Failed to update external agent: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`);
3490
- }
3491
- /**
3492
- * Get the external agent configuration
3493
- */
3494
- getConfig() {
3495
- return { ...this.config };
3496
- }
3497
- /**
3498
- * Get the external agent name
3499
- */
3500
- getName() {
3501
- return this.config.name;
3502
- }
3503
- /**
3504
- * Get the external agent base URL
3505
- */
3506
- getBaseUrl() {
3507
- return this.config.baseUrl;
3508
- }
3509
- /**
3510
- * Get the tenant ID
3511
- */
3512
- getTenantId() {
3513
- return this.tenantId;
3514
- }
3515
- getDescription() {
3516
- return this.config.description || "";
3517
- }
3518
- getCredentialReferenceId() {
3519
- return this.config.credentialReference?.id || void 0;
3520
- }
3521
- getCredentialReference() {
3522
- return this.config.credentialReference || void 0;
3523
- }
3524
- };
3525
- /**
3526
- * Factory function to create external agents - follows the same pattern as agent()
3527
- */
3528
- function externalAgent(config) {
3529
- return new ExternalAgent(config);
3530
- }
3531
- /**
3532
- * Helper function to create multiple external agents
3533
- */
3534
- function externalAgents(configs) {
3535
- const builders = {};
3536
- for (const [name, config] of Object.entries(configs)) builders[name] = externalAgent(config);
3537
- return builders;
3538
- }
3539
-
3540
- //#endregion
3541
- //#region src/types.ts
3542
- var AgentError = class extends Error {
3543
- constructor(message, code, details) {
3544
- super(message);
3545
- this.code = code;
3546
- this.details = details;
3547
- this.name = "AgentError";
3548
- }
3549
- };
3550
- var MaxTurnsExceededError = class extends AgentError {
3551
- constructor(maxTurns) {
3552
- super(`Maximum turns (${maxTurns}) exceeded`);
3553
- this.code = "MAX_TURNS_EXCEEDED";
3554
- }
3555
- };
3556
-
3557
- //#endregion
3558
- //#region src/runner.ts
3559
- const logger = (0, __inkeep_agents_core.getLogger)("runner");
3560
- var Runner = class Runner {
3561
- /**
3562
- * Run an agent until completion, handling transfers and tool calls
3563
- * Similar to OpenAI's Runner.run() pattern
3564
- * NOTE: This now requires an agent instead of an agent
3565
- */
3566
- static async run(agent$1, messages, options) {
3567
- const maxTurns = options?.maxTurns || 10;
3568
- let turnCount = 0;
3569
- const messageHistory = Runner.normalizeToMessageHistory(messages);
3570
- const allToolCalls = [];
3571
- logger.info({
3572
- agentId: agent$1.getId(),
3573
- defaultSubAgent: agent$1.getDefaultSubAgent()?.getName(),
3574
- maxTurns,
3575
- initialMessageCount: messageHistory.length
3576
- }, "Starting agent run");
3577
- while (turnCount < maxTurns) {
3578
- logger.debug({
3579
- agentId: agent$1.getId(),
3580
- turnCount,
3581
- messageHistoryLength: messageHistory.length
3582
- }, "Starting turn");
3583
- const response = await agent$1.generate(messageHistory, options);
3584
- turnCount++;
3585
- logger.info({
3586
- agentId: agent$1.getId(),
3587
- turnCount,
3588
- responseLength: response.length
3589
- }, "Agent generation completed");
3590
- return {
3591
- finalOutput: response,
3592
- agent: agent$1.getDefaultSubAgent() || {},
3593
- turnCount,
3594
- usage: {
3595
- inputTokens: 0,
3596
- outputTokens: 0
3597
- },
3598
- metadata: {
3599
- toolCalls: allToolCalls,
3600
- transfers: []
3601
- }
3602
- };
3603
- }
3604
- logger.error({
3605
- agentId: agent$1.getId(),
3606
- maxTurns,
3607
- finalTurnCount: turnCount
3608
- }, "Maximum turns exceeded");
3609
- throw new MaxTurnsExceededError(maxTurns);
3610
- }
3611
- /**
3612
- * Stream an agent's response
3613
- */
3614
- static async stream(agent$1, messages, options) {
3615
- logger.info({
3616
- agentId: agent$1.getId(),
3617
- defaultSubAgent: agent$1.getDefaultSubAgent()?.getName()
3618
- }, "Starting agent stream");
3619
- return agent$1.stream(messages, options);
3620
- }
3621
- /**
3622
- * Execute multiple agent in parallel and return the first successful result
3623
- */
3624
- static async raceAgents(agent$1, messages, options) {
3625
- if (agent$1.length === 0) throw new Error("No agent provided for race");
3626
- logger.info({
3627
- agentCount: agent$1.length,
3628
- agentIds: agent$1.map((g) => g.getId())
3629
- }, "Starting agent race");
3630
- const promises = agent$1.map(async (agent$2, index) => {
3631
- try {
3632
- return {
3633
- ...await Runner.run(agent$2, messages, options),
3634
- raceIndex: index
3635
- };
3636
- } catch (error) {
3637
- logger.error({
3638
- agentId: agent$2.getId(),
3639
- error: error instanceof Error ? error.message : "Unknown error"
3640
- }, "Agent failed in race");
3641
- throw error;
3642
- }
3643
- });
3644
- const result = await Promise.race(promises);
3645
- logger.info({
3646
- winningAgentId: result.agentId || "unknown",
3647
- raceIndex: result.raceIndex
3648
- }, "Agent race completed");
3649
- return result;
3650
- }
3651
- static normalizeToMessageHistory(messages) {
3652
- if (typeof messages === "string") return [{
3653
- role: "user",
3654
- content: messages
3655
- }];
3656
- if (Array.isArray(messages)) return messages.map((msg) => typeof msg === "string" ? {
3657
- role: "user",
3658
- content: msg
3659
- } : msg);
3660
- return [messages];
3661
- }
3662
- /**
3663
- * Validate agent configuration before running
3664
- */
3665
- static validateAgent(agent$1) {
3666
- const errors = [];
3667
- if (!agent$1.getId()) errors.push("Agent ID is required");
3668
- const defaultSubAgent = agent$1.getDefaultSubAgent();
3669
- if (!defaultSubAgent) errors.push("Default agent is required");
3670
- else if (!defaultSubAgent.getName()) errors.push("Default agent name is required");
3671
- const subAgents = agent$1.getSubAgents();
3672
- if (subAgents.length === 0) errors.push("Agent must contain at least one subagent");
3673
- for (const subAgent$1 of subAgents) if (!subAgent$1.getName()) errors.push(`Agent missing name`);
3674
- return {
3675
- valid: errors.length === 0,
3676
- errors
3677
- };
3678
- }
3679
- /**
3680
- * Get execution statistics for an agent
3681
- */
3682
- static async getExecutionStats(agent$1, messages, options) {
3683
- const subAgents = agent$1.getSubAgents();
3684
- const defaultSubAgent = agent$1.getDefaultSubAgent();
3685
- const messageCount = Array.isArray(messages) ? messages.length : 1;
3686
- return {
3687
- estimatedTurns: Math.min(Math.max(messageCount, 1), options?.maxTurns || 10),
3688
- estimatedTokens: messageCount * 100,
3689
- subAgentCount: subAgents.length,
3690
- defaultSubAgent: defaultSubAgent?.getName()
3691
- };
3692
- }
3693
- };
3694
- const run = Runner.run.bind(Runner);
3695
- const stream = Runner.stream.bind(Runner);
3696
- const raceAgents = Runner.raceAgents.bind(Runner);
3697
-
3698
- //#endregion
3699
- //#region src/telemetry-provider.ts
3700
- /**
3701
- * TelemetryProvider - Abstraction for Telemetry/Observability
3702
- *
3703
- * This module provides a clean abstraction over telemetry implementations.
3704
- * Cloud customers can use this without needing to install or configure
3705
- * OpenTelemetry or Signoz directly.
3706
- *
3707
- * Telemetry is OPT-IN - if not configured, a no-op provider is used.
3708
- *
3709
- * @example
3710
- * ```typescript
3711
- * // Opt-in to telemetry with default console logger
3712
- * import { InkeepTelemetryProvider, createConsoleTelemetryProvider } from '@inkeep/agents-sdk'
3713
- *
3714
- * const telemetry = createConsoleTelemetryProvider()
3715
- *
3716
- * // Or with OpenTelemetry (requires @opentelemetry packages)
3717
- * const telemetry = createOpenTelemetryProvider({
3718
- * serviceName: 'my-agent',
3719
- * endpoint: 'http://localhost:4318'
3720
- * })
3721
- * ```
3722
- */
3723
- /**
3724
- * Span status codes
3725
- */
3726
- const SpanStatus = {
3727
- OK: "ok",
3728
- ERROR: "error",
3729
- UNSET: "unset"
3730
- };
3731
- /**
3732
- * No-op span implementation
3733
- */
3734
- const createNoOpSpan = () => ({
3735
- setAttributes: function() {
3736
- return this;
3737
- },
3738
- setAttribute: function() {
3739
- return this;
3740
- },
3741
- recordException: function() {
3742
- return this;
3743
- },
3744
- setStatus: function() {
3745
- return this;
3746
- },
3747
- addEvent: function() {
3748
- return this;
3749
- },
3750
- end: () => {},
3751
- isRecording: () => false,
3752
- updateName: function() {
3753
- return this;
3754
- }
3755
- });
3756
- /**
3757
- * No-op tracer implementation
3758
- */
3759
- const createNoOpTracer = () => ({
3760
- startActiveSpan(_name, arg1, arg2) {
3761
- const fn = typeof arg1 === "function" ? arg1 : arg2;
3762
- if (!fn) throw new Error("No callback function provided");
3763
- return fn(createNoOpSpan());
3764
- },
3765
- startSpan(_name, _options) {
3766
- return createNoOpSpan();
3767
- }
3768
- });
3769
- /**
3770
- * No-op logger implementation
3771
- */
3772
- const createNoOpLogger = () => ({
3773
- debug: () => {},
3774
- info: () => {},
3775
- warn: () => {},
3776
- error: () => {}
3777
- });
3778
- /**
3779
- * No-op metrics implementation
3780
- */
3781
- const createNoOpMetrics = () => ({
3782
- increment: () => {},
3783
- gauge: () => {},
3784
- histogram: () => {}
3785
- });
3786
- /**
3787
- * No-op telemetry provider (default)
3788
- */
3789
- var NoOpTelemetryProvider = class {
3790
- getTracer(_name, _version) {
3791
- return createNoOpTracer();
3792
- }
3793
- getLogger(_name) {
3794
- return createNoOpLogger();
3795
- }
3796
- getMetrics(_name) {
3797
- return createNoOpMetrics();
3798
- }
3799
- async shutdown() {}
3800
- isEnabled() {
3801
- return false;
3802
- }
3803
- };
3804
- /**
3805
- * Console-based telemetry provider for development/debugging
3806
- */
3807
- var ConsoleTelemetryProvider = class {
3808
- serviceName;
3809
- constructor(serviceName = "inkeep-agent") {
3810
- this.serviceName = serviceName;
3811
- }
3812
- getTracer(name, _version) {
3813
- const serviceName = this.serviceName;
3814
- const createConsoleSpan = (spanName) => {
3815
- const startTime = Date.now();
3816
- const attributes = {};
3817
- const events = [];
3818
- return {
3819
- setAttributes: function(attrs) {
3820
- Object.assign(attributes, attrs);
3821
- return this;
3822
- },
3823
- setAttribute: function(key, value) {
3824
- attributes[key] = value;
3825
- return this;
3826
- },
3827
- recordException: function(error) {
3828
- console.error(`[${serviceName}:${name}] Exception in ${spanName}:`, error.message);
3829
- return this;
3830
- },
3831
- setStatus: function(status, message) {
3832
- if (status === SpanStatus.ERROR) console.error(`[${serviceName}:${name}] ${spanName} ERROR:`, message);
3833
- return this;
3834
- },
3835
- addEvent: function(eventName, eventAttrs) {
3836
- events.push({
3837
- name: eventName,
3838
- attributes: eventAttrs
3839
- });
3840
- return this;
3841
- },
3842
- end: () => {
3843
- const duration = Date.now() - startTime;
3844
- console.log(`[${serviceName}:${name}] ${spanName} completed in ${duration}ms`, {
3845
- attributes,
3846
- events
3847
- });
3848
- },
3849
- isRecording: () => true,
3850
- updateName: function(newName) {
3851
- console.log(`[${serviceName}:${name}] Span renamed: ${spanName} -> ${newName}`);
3852
- return this;
3853
- }
3854
- };
3855
- };
3856
- return {
3857
- startActiveSpan(spanName, arg1, arg2) {
3858
- const fn = typeof arg1 === "function" ? arg1 : arg2;
3859
- if (!fn) throw new Error("No callback function provided");
3860
- const span = createConsoleSpan(spanName);
3861
- try {
3862
- return fn(span);
3863
- } finally {
3864
- span.end();
3865
- }
3866
- },
3867
- startSpan(spanName, _options) {
3868
- return createConsoleSpan(spanName);
3869
- }
3870
- };
3871
- }
3872
- getLogger(name) {
3873
- const prefix = `[${this.serviceName}:${name}]`;
3874
- return {
3875
- debug: (message, context) => console.debug(prefix, message, context),
3876
- info: (message, context) => console.info(prefix, message, context),
3877
- warn: (message, context) => console.warn(prefix, message, context),
3878
- error: (message, context) => console.error(prefix, message, context)
3879
- };
3880
- }
3881
- getMetrics(name) {
3882
- const prefix = `[${this.serviceName}:${name}]`;
3883
- return {
3884
- increment: (metricName, value = 1, attributes) => console.log(`${prefix} COUNTER ${metricName}: +${value}`, attributes),
3885
- gauge: (metricName, value, attributes) => console.log(`${prefix} GAUGE ${metricName}: ${value}`, attributes),
3886
- histogram: (metricName, value, attributes) => console.log(`${prefix} HISTOGRAM ${metricName}: ${value}`, attributes)
3887
- };
3888
- }
3889
- async shutdown() {
3890
- console.log(`[${this.serviceName}] Telemetry provider shutting down`);
3891
- }
3892
- isEnabled() {
3893
- return true;
3894
- }
3895
- };
3896
- let globalProvider = new NoOpTelemetryProvider();
3897
- /**
3898
- * InkeepTelemetryProvider - Main telemetry management class
3899
- *
3900
- * Provides a unified interface for telemetry across the SDK.
3901
- * Telemetry is OPT-IN - by default, a no-op provider is used.
3902
- */
3903
- var InkeepTelemetryProvider = class {
3904
- provider;
3905
- constructor(config = {}) {
3906
- if (config.provider) this.provider = config.provider;
3907
- else if (config.enabled) this.provider = new ConsoleTelemetryProvider(config.serviceName);
3908
- else this.provider = new NoOpTelemetryProvider();
3909
- }
3910
- /**
3911
- * Get a tracer for creating spans
3912
- */
3913
- getTracer(name, version) {
3914
- return this.provider.getTracer(name, version);
3915
- }
3916
- /**
3917
- * Get a logger for structured logging
3918
- */
3919
- getLogger(name) {
3920
- return this.provider.getLogger(name);
3921
- }
3922
- /**
3923
- * Get metrics recorder
3924
- */
3925
- getMetrics(name) {
3926
- return this.provider.getMetrics(name);
3927
- }
3928
- /**
3929
- * Check if telemetry is enabled
3930
- */
3931
- isEnabled() {
3932
- return this.provider.isEnabled();
3933
- }
3934
- /**
3935
- * Shutdown the provider
3936
- */
3937
- async shutdown() {
3938
- return this.provider.shutdown();
3939
- }
3940
- /**
3941
- * Get the underlying provider
3942
- */
3943
- getProvider() {
3944
- return this.provider;
3945
- }
3946
- /**
3947
- * Set as the global telemetry provider
3948
- */
3949
- setAsGlobal() {
3950
- globalProvider = this.provider;
3951
- }
3952
- };
3953
- /**
3954
- * Get the global telemetry provider
3955
- */
3956
- function getGlobalTelemetryProvider() {
3957
- return globalProvider;
3958
- }
3959
- /**
3960
- * Set the global telemetry provider
3961
- */
3962
- function setGlobalTelemetryProvider(provider) {
3963
- globalProvider = provider;
3964
- }
3965
- /**
3966
- * Create a no-op telemetry provider (default, does nothing)
3967
- */
3968
- function createNoOpTelemetryProvider() {
3969
- return new InkeepTelemetryProvider({ enabled: false });
3970
- }
3971
- /**
3972
- * Create a console-based telemetry provider for development
3973
- */
3974
- function createConsoleTelemetryProvider(serviceName) {
3975
- return new InkeepTelemetryProvider({
3976
- enabled: true,
3977
- serviceName,
3978
- provider: new ConsoleTelemetryProvider(serviceName)
3979
- });
3980
- }
3981
- /**
3982
- * Wrap an OpenTelemetry span in our TelemetrySpan interface
3983
- */
3984
- function wrapOtelSpan(otelSpan) {
3985
- return {
3986
- setAttributes: function(attributes) {
3987
- otelSpan.setAttributes(attributes);
3988
- return this;
3989
- },
3990
- setAttribute: function(key, value) {
3991
- otelSpan.setAttribute(key, value);
3992
- return this;
3993
- },
3994
- recordException: function(error) {
3995
- otelSpan.recordException(error);
3996
- return this;
3997
- },
3998
- setStatus: function(status, message) {
3999
- const statusCode = status === SpanStatus.ERROR ? 2 : status === SpanStatus.OK ? 1 : 0;
4000
- otelSpan.setStatus({
4001
- code: statusCode,
4002
- message
4003
- });
4004
- return this;
4005
- },
4006
- addEvent: function(name, attributes) {
4007
- otelSpan.addEvent(name, attributes);
4008
- return this;
4009
- },
4010
- end: () => otelSpan.end(),
4011
- isRecording: () => otelSpan.isRecording(),
4012
- updateName: function(name) {
4013
- otelSpan.updateName(name);
4014
- return this;
4015
- }
4016
- };
4017
- }
4018
- /**
4019
- * Check if OpenTelemetry is available
4020
- */
4021
- function isOpenTelemetryAvailable() {
4022
- try {
4023
- require.resolve("@opentelemetry/api");
4024
- return true;
4025
- } catch {
4026
- return false;
4027
- }
4028
- }
4029
- /**
4030
- * Load OpenTelemetry module dynamically
4031
- */
4032
- async function loadOpenTelemetryModule() {
4033
- return new Function("specifier", "return import(specifier)")("@opentelemetry/api");
4034
- }
4035
- /**
4036
- * Create an OpenTelemetry-based provider
4037
- *
4038
- * Note: Requires @opentelemetry packages to be installed
4039
- */
4040
- async function createOpenTelemetryProvider(config) {
4041
- if (!isOpenTelemetryAvailable()) {
4042
- console.warn("OpenTelemetry packages not installed. Install with: npm install @opentelemetry/api @opentelemetry/sdk-node");
4043
- return createNoOpTelemetryProvider();
4044
- }
4045
- try {
4046
- const { trace } = await loadOpenTelemetryModule();
4047
- return new InkeepTelemetryProvider({
4048
- enabled: true,
4049
- provider: {
4050
- getTracer(name, version) {
4051
- const otelTracer = trace.getTracer(name, version);
4052
- return {
4053
- startActiveSpan(spanName, arg1, arg2) {
4054
- const fn = typeof arg1 === "function" ? arg1 : arg2;
4055
- const options = typeof arg1 === "object" ? arg1 : void 0;
4056
- if (!fn) throw new Error("No callback function provided");
4057
- return otelTracer.startActiveSpan(spanName, options?.attributes ? { attributes: options.attributes } : {}, (otelSpan) => {
4058
- return fn(wrapOtelSpan(otelSpan));
4059
- });
4060
- },
4061
- startSpan(spanName, options) {
4062
- return wrapOtelSpan(otelTracer.startSpan(spanName, options?.attributes ? { attributes: options.attributes } : {}));
4063
- }
4064
- };
4065
- },
4066
- getLogger(name) {
4067
- return new ConsoleTelemetryProvider(config.serviceName).getLogger(name);
4068
- },
4069
- getMetrics(_name) {
4070
- return createNoOpMetrics();
4071
- },
4072
- async shutdown() {},
4073
- isEnabled() {
4074
- return true;
4075
- }
4076
- }
4077
- });
4078
- } catch (error) {
4079
- console.warn("Failed to initialize OpenTelemetry:", error instanceof Error ? error.message : "Unknown error");
4080
- return createNoOpTelemetryProvider();
4081
- }
4082
- }
4083
-
4084
- //#endregion
4085
- Object.defineProperty(exports, 'ANTHROPIC_MODELS', {
4086
- enumerable: true,
4087
- get: function () {
4088
- return __inkeep_agents_core.ANTHROPIC_MODELS;
4089
- }
4090
- });
4091
- exports.ArtifactComponent = ArtifactComponent;
4092
- exports.ConsoleTelemetryProvider = ConsoleTelemetryProvider;
4093
- exports.DataComponent = DataComponent;
4094
- exports.ExternalAgent = ExternalAgent;
4095
- exports.FunctionTool = FunctionTool;
4096
- Object.defineProperty(exports, 'GOOGLE_MODELS', {
4097
- enumerable: true,
4098
- get: function () {
4099
- return __inkeep_agents_core.GOOGLE_MODELS;
4100
- }
4101
- });
4102
- exports.InkeepCredentialProvider = InkeepCredentialProvider;
4103
- exports.InkeepTelemetryProvider = InkeepTelemetryProvider;
4104
- exports.NoOpTelemetryProvider = NoOpTelemetryProvider;
4105
- Object.defineProperty(exports, 'OPENAI_MODELS', {
4106
- enumerable: true,
4107
- get: function () {
4108
- return __inkeep_agents_core.OPENAI_MODELS;
4109
- }
4110
- });
4111
- exports.Project = Project;
4112
- exports.Runner = Runner;
4113
- exports.SpanStatus = SpanStatus;
4114
- exports.StatusComponent = StatusComponent;
4115
- exports.SubAgent = SubAgent;
4116
- exports.Tool = Tool;
4117
- exports.agent = agent;
4118
- exports.agentMcp = agentMcp;
4119
- exports.artifactComponent = artifactComponent;
4120
- exports.createConsoleTelemetryProvider = createConsoleTelemetryProvider;
4121
- exports.createCredentialProvider = createCredentialProvider;
4122
- exports.createEnvironmentSettings = createEnvironmentSettings;
4123
- exports.createFullProjectViaAPI = createFullProjectViaAPI;
4124
- exports.createNoOpTelemetryProvider = createNoOpTelemetryProvider;
4125
- exports.createOpenTelemetryProvider = createOpenTelemetryProvider;
4126
- exports.credential = credential;
4127
- exports.credentialRef = credentialRef;
4128
- exports.dataComponent = dataComponent;
4129
- exports.deleteFullProjectViaAPI = deleteFullProjectViaAPI;
4130
- exports.externalAgent = externalAgent;
4131
- exports.externalAgents = externalAgents;
4132
- exports.functionTool = functionTool;
4133
- exports.getFullProjectViaAPI = getFullProjectViaAPI;
4134
- exports.getGlobalTelemetryProvider = getGlobalTelemetryProvider;
4135
- exports.isCredentialReference = isCredentialReference;
4136
- exports.mcpServer = mcpServer;
4137
- exports.mcpTool = mcpTool;
4138
- exports.project = project;
4139
- exports.raceAgents = raceAgents;
4140
- exports.registerEnvironmentSettings = registerEnvironmentSettings;
4141
- exports.run = run;
4142
- exports.setGlobalTelemetryProvider = setGlobalTelemetryProvider;
4143
- exports.statusComponent = statusComponent;
4144
- exports.stream = stream;
4145
- exports.subAgent = subAgent;
4146
- exports.transfer = transfer;
4147
- exports.updateFullProjectViaAPI = updateFullProjectViaAPI;