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