@inkeep/agents-sdk 0.0.0-dev-20250910233133 → 0.0.0-dev-20250910233151

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 (61) hide show
  1. package/dist/chunk-SMQ7HFDN.js +146 -0
  2. package/dist/index.cjs +2948 -0
  3. package/dist/index.d.cts +862 -0
  4. package/dist/index.d.ts +862 -11
  5. package/dist/index.js +2760 -10
  6. package/dist/tool-MDKZB6AJ.js +1 -0
  7. package/package.json +3 -3
  8. package/dist/__tests__/utils/testTenant.d.ts +0 -7
  9. package/dist/__tests__/utils/testTenant.d.ts.map +0 -1
  10. package/dist/__tests__/utils/testTenant.js +0 -10
  11. package/dist/__tests__/utils/testTenant.js.map +0 -1
  12. package/dist/agent.d.ts +0 -39
  13. package/dist/agent.d.ts.map +0 -1
  14. package/dist/agent.js +0 -513
  15. package/dist/agent.js.map +0 -1
  16. package/dist/artifact-component.d.ts +0 -27
  17. package/dist/artifact-component.d.ts.map +0 -1
  18. package/dist/artifact-component.js +0 -118
  19. package/dist/artifact-component.js.map +0 -1
  20. package/dist/builders.d.ts +0 -211
  21. package/dist/builders.d.ts.map +0 -1
  22. package/dist/builders.js +0 -244
  23. package/dist/builders.js.map +0 -1
  24. package/dist/data-component.d.ts +0 -25
  25. package/dist/data-component.d.ts.map +0 -1
  26. package/dist/data-component.js +0 -114
  27. package/dist/data-component.js.map +0 -1
  28. package/dist/environment-settings.d.ts +0 -28
  29. package/dist/environment-settings.d.ts.map +0 -1
  30. package/dist/environment-settings.js +0 -79
  31. package/dist/environment-settings.js.map +0 -1
  32. package/dist/externalAgent.d.ts +0 -58
  33. package/dist/externalAgent.d.ts.map +0 -1
  34. package/dist/externalAgent.js +0 -163
  35. package/dist/externalAgent.js.map +0 -1
  36. package/dist/graph.d.ts +0 -200
  37. package/dist/graph.d.ts.map +0 -1
  38. package/dist/graph.js +0 -1322
  39. package/dist/graph.js.map +0 -1
  40. package/dist/graphFullClient.d.ts +0 -22
  41. package/dist/graphFullClient.d.ts.map +0 -1
  42. package/dist/graphFullClient.js +0 -189
  43. package/dist/graphFullClient.js.map +0 -1
  44. package/dist/index.d.ts.map +0 -1
  45. package/dist/index.js.map +0 -1
  46. package/dist/module-hosted-tool-manager.d.ts +0 -37
  47. package/dist/module-hosted-tool-manager.d.ts.map +0 -1
  48. package/dist/module-hosted-tool-manager.js +0 -378
  49. package/dist/module-hosted-tool-manager.js.map +0 -1
  50. package/dist/runner.d.ts +0 -38
  51. package/dist/runner.d.ts.map +0 -1
  52. package/dist/runner.js +0 -164
  53. package/dist/runner.js.map +0 -1
  54. package/dist/tool.d.ts +0 -29
  55. package/dist/tool.d.ts.map +0 -1
  56. package/dist/tool.js +0 -122
  57. package/dist/tool.js.map +0 -1
  58. package/dist/types.d.ts +0 -286
  59. package/dist/types.d.ts.map +0 -1
  60. package/dist/types.js +0 -39
  61. package/dist/types.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,2948 @@
1
+ 'use strict';
2
+
3
+ var agentsCore = require('@inkeep/agents-core');
4
+ var zod = require('zod');
5
+
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
17
+
18
+ // src/tool.ts
19
+ var tool_exports = {};
20
+ __export(tool_exports, {
21
+ Tool: () => exports.Tool
22
+ });
23
+ var logger3; exports.Tool = void 0;
24
+ var init_tool = __esm({
25
+ "src/tool.ts"() {
26
+ logger3 = agentsCore.getLogger("tool");
27
+ exports.Tool = class {
28
+ constructor(config) {
29
+ __publicField(this, "config");
30
+ __publicField(this, "baseURL");
31
+ __publicField(this, "tenantId");
32
+ __publicField(this, "initialized", false);
33
+ this.config = config;
34
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
35
+ this.tenantId = config.tenantId || "default";
36
+ logger3.info(
37
+ {
38
+ toolId: this.getId(),
39
+ toolName: config.name
40
+ },
41
+ "Tool constructor initialized"
42
+ );
43
+ }
44
+ // Compute ID from name using same slug transformation as agents
45
+ getId() {
46
+ return this.config.id;
47
+ }
48
+ getName() {
49
+ return this.config.name;
50
+ }
51
+ getDescription() {
52
+ return this.config.description || "";
53
+ }
54
+ getServerUrl() {
55
+ return this.config.serverUrl;
56
+ }
57
+ getActiveTools() {
58
+ return this.config.activeTools;
59
+ }
60
+ getCredentialReferenceId() {
61
+ return this.config.credential?.id;
62
+ }
63
+ // Public method to ensure tool exists in backend (with upsert behavior)
64
+ async init(options) {
65
+ if (this.initialized) return;
66
+ try {
67
+ if (!options?.skipDatabaseRegistration) {
68
+ await this.upsertTool();
69
+ }
70
+ logger3.info(
71
+ {
72
+ toolId: this.getId()
73
+ },
74
+ "Tool initialized successfully"
75
+ );
76
+ this.initialized = true;
77
+ } catch (error) {
78
+ logger3.error(
79
+ {
80
+ toolId: this.getId(),
81
+ error: error instanceof Error ? error.message : "Unknown error"
82
+ },
83
+ "Failed to initialize tool"
84
+ );
85
+ throw error;
86
+ }
87
+ }
88
+ // Private method to upsert tool (create or update)
89
+ async upsertTool() {
90
+ const toolDataForUpdate = {
91
+ id: this.getId(),
92
+ name: this.config.name,
93
+ // Don't send description as it's not in the database schema
94
+ // Explicitly set to null when undefined to ensure removal
95
+ credentialReferenceId: this.config.credential?.id ?? null,
96
+ // Explicitly set headers to null when undefined to ensure removal
97
+ headers: this.config.headers ?? null,
98
+ imageUrl: this.config.imageUrl,
99
+ // Include image URL
100
+ config: {
101
+ type: "mcp",
102
+ mcp: {
103
+ server: {
104
+ url: this.config.serverUrl
105
+ },
106
+ activeTools: this.config.activeTools
107
+ }
108
+ }
109
+ };
110
+ const toolDataForCreate = {
111
+ ...toolDataForUpdate
112
+ };
113
+ logger3.info({ toolDataForCreate }, "toolDataForCreate");
114
+ const updateResponse = await fetch(
115
+ `${this.baseURL}/tenants/${this.tenantId}/crud/tools/${this.getId()}`,
116
+ {
117
+ method: "PUT",
118
+ headers: {
119
+ "Content-Type": "application/json"
120
+ },
121
+ body: JSON.stringify(toolDataForUpdate)
122
+ }
123
+ );
124
+ logger3.info({ updateResponse }, "tool updateResponse");
125
+ if (updateResponse.ok) {
126
+ logger3.info(
127
+ {
128
+ toolId: this.getId()
129
+ },
130
+ "Tool updated successfully"
131
+ );
132
+ return;
133
+ }
134
+ if (updateResponse.status === 404) {
135
+ logger3.info(
136
+ {
137
+ toolId: this.getId()
138
+ },
139
+ "Tool not found, creating new tool"
140
+ );
141
+ const createResponse = await fetch(
142
+ `${this.baseURL}/tenants/${this.tenantId}/crud/tools`,
143
+ {
144
+ method: "POST",
145
+ headers: {
146
+ "Content-Type": "application/json"
147
+ },
148
+ body: JSON.stringify(toolDataForCreate)
149
+ }
150
+ );
151
+ if (!createResponse.ok) {
152
+ throw new Error(`Failed to create tool: ${createResponse.status}`);
153
+ }
154
+ logger3.info(
155
+ {
156
+ toolId: this.getId()
157
+ },
158
+ "Tool created successfully"
159
+ );
160
+ return;
161
+ }
162
+ throw new Error(`Failed to update tool: ${updateResponse.status}`);
163
+ }
164
+ };
165
+ }
166
+ });
167
+ var logger = agentsCore.getLogger("artifactComponent");
168
+ var ArtifactComponent = class {
169
+ constructor(config) {
170
+ __publicField(this, "config");
171
+ __publicField(this, "baseURL");
172
+ __publicField(this, "tenantId");
173
+ __publicField(this, "projectId");
174
+ __publicField(this, "initialized", false);
175
+ __publicField(this, "id");
176
+ this.id = agentsCore.generateIdFromName(config.name);
177
+ this.config = {
178
+ ...config,
179
+ id: this.id,
180
+ tenantId: config.tenantId || "default",
181
+ projectId: config.projectId || "default"
182
+ };
183
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
184
+ this.tenantId = this.config.tenantId;
185
+ this.projectId = this.config.projectId;
186
+ logger.info(
187
+ {
188
+ artifactComponentId: this.getId(),
189
+ artifactComponentName: config.name
190
+ },
191
+ "ArtifactComponent constructor initialized"
192
+ );
193
+ }
194
+ // Compute ID from name using same slug transformation as agents
195
+ getId() {
196
+ return this.id;
197
+ }
198
+ getName() {
199
+ return this.config.name;
200
+ }
201
+ getDescription() {
202
+ return this.config.description;
203
+ }
204
+ getSummaryProps() {
205
+ return this.config.summaryProps;
206
+ }
207
+ getFullProps() {
208
+ return this.config.fullProps;
209
+ }
210
+ // Public method to ensure artifact component exists in backend (with upsert behavior)
211
+ async init() {
212
+ if (this.initialized) return;
213
+ try {
214
+ await this.upsertArtifactComponent();
215
+ logger.info(
216
+ {
217
+ artifactComponentId: this.getId()
218
+ },
219
+ "ArtifactComponent initialized successfully"
220
+ );
221
+ this.initialized = true;
222
+ } catch (error) {
223
+ logger.error(
224
+ {
225
+ artifactComponentId: this.getId(),
226
+ error: error instanceof Error ? error.message : "Unknown error"
227
+ },
228
+ "Failed to initialize artifact component"
229
+ );
230
+ throw error;
231
+ }
232
+ }
233
+ // Private method to upsert artifact component (create or update)
234
+ async upsertArtifactComponent() {
235
+ const artifactComponentData = {
236
+ id: this.getId(),
237
+ name: this.config.name,
238
+ description: this.config.description,
239
+ summaryProps: this.config.summaryProps,
240
+ fullProps: this.config.fullProps
241
+ };
242
+ logger.info(
243
+ { artifactComponentData },
244
+ "artifactComponentData for create/update"
245
+ );
246
+ const updateResponse = await fetch(
247
+ `${this.baseURL}/tenants/${this.tenantId}/crud/artifact-components/${this.getId()}`,
248
+ {
249
+ method: "PUT",
250
+ headers: {
251
+ "Content-Type": "application/json"
252
+ },
253
+ body: JSON.stringify(artifactComponentData)
254
+ }
255
+ );
256
+ logger.info(
257
+ {
258
+ status: updateResponse.status,
259
+ artifactComponentId: this.getId()
260
+ },
261
+ "artifact component updateResponse"
262
+ );
263
+ if (updateResponse.ok) {
264
+ logger.info(
265
+ {
266
+ artifactComponentId: this.getId()
267
+ },
268
+ "ArtifactComponent updated successfully"
269
+ );
270
+ return;
271
+ }
272
+ if (updateResponse.status === 404) {
273
+ logger.info(
274
+ {
275
+ artifactComponentId: this.getId()
276
+ },
277
+ "ArtifactComponent not found, creating new artifact component"
278
+ );
279
+ const createResponse = await fetch(
280
+ `${this.baseURL}/tenants/${this.tenantId}/crud/artifact-components`,
281
+ {
282
+ method: "POST",
283
+ headers: {
284
+ "Content-Type": "application/json"
285
+ },
286
+ body: JSON.stringify(artifactComponentData)
287
+ }
288
+ );
289
+ if (!createResponse.ok) {
290
+ const errorText2 = await createResponse.text().catch(() => "Unknown error");
291
+ throw new Error(
292
+ `Failed to create artifact component: ${createResponse.status} ${createResponse.statusText} - ${errorText2}`
293
+ );
294
+ }
295
+ logger.info(
296
+ {
297
+ artifactComponentId: this.getId()
298
+ },
299
+ "ArtifactComponent created successfully"
300
+ );
301
+ return;
302
+ }
303
+ const errorText = await updateResponse.text().catch(() => "Unknown error");
304
+ throw new Error(
305
+ `Failed to update artifact component: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`
306
+ );
307
+ }
308
+ };
309
+ var logger2 = agentsCore.getLogger("dataComponent");
310
+ var DataComponent = class {
311
+ constructor(config) {
312
+ __publicField(this, "config");
313
+ __publicField(this, "baseURL");
314
+ __publicField(this, "tenantId");
315
+ __publicField(this, "projectId");
316
+ __publicField(this, "initialized", false);
317
+ __publicField(this, "id");
318
+ this.id = agentsCore.generateIdFromName(config.name);
319
+ this.config = {
320
+ ...config,
321
+ id: this.id,
322
+ tenantId: config.tenantId || "default",
323
+ projectId: config.projectId || "default"
324
+ };
325
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
326
+ this.tenantId = this.config.tenantId;
327
+ this.projectId = this.config.projectId;
328
+ logger2.info(
329
+ {
330
+ dataComponentId: this.getId(),
331
+ dataComponentName: config.name
332
+ },
333
+ "DataComponent constructor initialized"
334
+ );
335
+ }
336
+ // Compute ID from name using same slug transformation as agents
337
+ getId() {
338
+ return this.id;
339
+ }
340
+ getName() {
341
+ return this.config.name;
342
+ }
343
+ getDescription() {
344
+ return this.config.description;
345
+ }
346
+ getProps() {
347
+ return this.config.props;
348
+ }
349
+ // Public method to ensure data component exists in backend (with upsert behavior)
350
+ async init() {
351
+ if (this.initialized) return;
352
+ try {
353
+ await this.upsertDataComponent();
354
+ logger2.info(
355
+ {
356
+ dataComponentId: this.getId()
357
+ },
358
+ "DataComponent initialized successfully"
359
+ );
360
+ this.initialized = true;
361
+ } catch (error) {
362
+ logger2.error(
363
+ {
364
+ dataComponentId: this.getId(),
365
+ error: error instanceof Error ? error.message : "Unknown error"
366
+ },
367
+ "Failed to initialize data component"
368
+ );
369
+ throw error;
370
+ }
371
+ }
372
+ // Private method to upsert data component (create or update)
373
+ async upsertDataComponent() {
374
+ const dataComponentData = {
375
+ id: this.getId(),
376
+ name: this.config.name,
377
+ description: this.config.description,
378
+ props: this.config.props
379
+ };
380
+ logger2.info({ dataComponentData }, "dataComponentData for create/update");
381
+ const updateResponse = await fetch(
382
+ `${this.baseURL}/tenants/${this.tenantId}/crud/data-components/${this.getId()}`,
383
+ {
384
+ method: "PUT",
385
+ headers: {
386
+ "Content-Type": "application/json"
387
+ },
388
+ body: JSON.stringify(dataComponentData)
389
+ }
390
+ );
391
+ logger2.info(
392
+ {
393
+ status: updateResponse.status,
394
+ dataComponentId: this.getId()
395
+ },
396
+ "data component updateResponse"
397
+ );
398
+ if (updateResponse.ok) {
399
+ logger2.info(
400
+ {
401
+ dataComponentId: this.getId()
402
+ },
403
+ "DataComponent updated successfully"
404
+ );
405
+ return;
406
+ }
407
+ if (updateResponse.status === 404) {
408
+ logger2.info(
409
+ {
410
+ dataComponentId: this.getId()
411
+ },
412
+ "DataComponent not found, creating new data component"
413
+ );
414
+ const createResponse = await fetch(
415
+ `${this.baseURL}/tenants/${this.tenantId}/crud/data-components`,
416
+ {
417
+ method: "POST",
418
+ headers: {
419
+ "Content-Type": "application/json"
420
+ },
421
+ body: JSON.stringify(dataComponentData)
422
+ }
423
+ );
424
+ if (!createResponse.ok) {
425
+ const errorText2 = await createResponse.text().catch(() => "Unknown error");
426
+ throw new Error(
427
+ `Failed to create data component: ${createResponse.status} ${createResponse.statusText} - ${errorText2}`
428
+ );
429
+ }
430
+ logger2.info(
431
+ {
432
+ dataComponentId: this.getId()
433
+ },
434
+ "DataComponent created successfully"
435
+ );
436
+ return;
437
+ }
438
+ const errorText = await updateResponse.text().catch(() => "Unknown error");
439
+ throw new Error(
440
+ `Failed to update data component: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`
441
+ );
442
+ }
443
+ };
444
+
445
+ // src/agent.ts
446
+ var logger4 = agentsCore.getLogger("agent");
447
+ function resolveGetter(value) {
448
+ if (typeof value === "function") {
449
+ return value();
450
+ }
451
+ return value;
452
+ }
453
+ var Agent = class {
454
+ constructor(config) {
455
+ __publicField(this, "config");
456
+ __publicField(this, "type", "internal");
457
+ __publicField(this, "baseURL");
458
+ __publicField(this, "tenantId");
459
+ __publicField(this, "projectId");
460
+ __publicField(this, "initialized", false);
461
+ this.config = { ...config, type: "internal" };
462
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
463
+ this.tenantId = config.tenantId || "default";
464
+ this.projectId = config.projectId || "default";
465
+ logger4.info(
466
+ {
467
+ tenantId: this.tenantId,
468
+ agentId: this.config.id,
469
+ agentName: config.name
470
+ },
471
+ "Agent constructor initialized"
472
+ );
473
+ }
474
+ // Return the configured ID
475
+ getId() {
476
+ return this.config.id;
477
+ }
478
+ // Agent introspection methods
479
+ getName() {
480
+ return this.config.name;
481
+ }
482
+ getInstructions() {
483
+ return this.config.prompt;
484
+ }
485
+ getTools() {
486
+ const tools = resolveGetter(this.config.tools);
487
+ if (!tools) {
488
+ return {};
489
+ }
490
+ if (!Array.isArray(tools)) {
491
+ throw new Error("tools getter must return an array");
492
+ }
493
+ const toolRecord = {};
494
+ for (const tool2 of tools) {
495
+ if (tool2 && typeof tool2 === "object") {
496
+ const id = tool2.id || tool2.getId?.() || tool2.name;
497
+ if (id) {
498
+ toolRecord[id] = tool2;
499
+ }
500
+ }
501
+ }
502
+ return toolRecord;
503
+ }
504
+ getModels() {
505
+ return this.config.models;
506
+ }
507
+ setModels(models) {
508
+ this.config.models = models;
509
+ }
510
+ getTransfers() {
511
+ return typeof this.config.canTransferTo === "function" ? this.config.canTransferTo() : [];
512
+ }
513
+ getDelegates() {
514
+ return typeof this.config.canDelegateTo === "function" ? this.config.canDelegateTo() : [];
515
+ }
516
+ getDataComponents() {
517
+ return resolveGetter(this.config.dataComponents) || [];
518
+ }
519
+ getArtifactComponents() {
520
+ return resolveGetter(this.config.artifactComponents) || [];
521
+ }
522
+ addTool(_name, tool2) {
523
+ const existingTools = this.config.tools ? this.config.tools() : [];
524
+ this.config.tools = () => [...existingTools, tool2];
525
+ }
526
+ addTransfer(...agents) {
527
+ if (typeof this.config.canTransferTo === "function") {
528
+ const existingTransfers = this.config.canTransferTo;
529
+ this.config.canTransferTo = () => [...existingTransfers(), ...agents];
530
+ } else {
531
+ this.config.canTransferTo = () => agents;
532
+ }
533
+ }
534
+ addDelegate(...agents) {
535
+ if (typeof this.config.canDelegateTo === "function") {
536
+ const existingDelegates = this.config.canDelegateTo;
537
+ this.config.canDelegateTo = () => [...existingDelegates(), ...agents];
538
+ } else {
539
+ this.config.canDelegateTo = () => agents;
540
+ }
541
+ }
542
+ // Public method to ensure agent exists in backend (with upsert behavior)
543
+ async init() {
544
+ if (this.initialized) return;
545
+ try {
546
+ await this.upsertAgent();
547
+ await this.loadDataComponents();
548
+ await this.loadArtifactComponents();
549
+ await this.saveToolsAndRelations();
550
+ await this.saveDataComponents();
551
+ await this.saveArtifactComponents();
552
+ logger4.info(
553
+ {
554
+ agentId: this.getId()
555
+ },
556
+ "Agent initialized successfully"
557
+ );
558
+ this.initialized = true;
559
+ } catch (error) {
560
+ logger4.error(
561
+ {
562
+ agentId: this.getId(),
563
+ error: error instanceof Error ? error.message : "Unknown error"
564
+ },
565
+ "Failed to initialize agent"
566
+ );
567
+ throw error;
568
+ }
569
+ }
570
+ // Private method to upsert agent (create or update)
571
+ async upsertAgent() {
572
+ const agentData = {
573
+ id: this.getId(),
574
+ name: this.config.name,
575
+ description: this.config.description || "",
576
+ prompt: this.config.prompt,
577
+ conversationHistoryConfig: this.config.conversationHistoryConfig,
578
+ models: this.config.models,
579
+ stopWhen: this.config.stopWhen
580
+ };
581
+ const updateResponse = await fetch(
582
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agents/${this.getId()}`,
583
+ {
584
+ method: "PUT",
585
+ headers: {
586
+ "Content-Type": "application/json"
587
+ },
588
+ body: JSON.stringify(agentData)
589
+ }
590
+ );
591
+ if (updateResponse.ok) {
592
+ logger4.info(
593
+ {
594
+ agentId: this.getId()
595
+ },
596
+ "Agent updated successfully"
597
+ );
598
+ return;
599
+ }
600
+ if (updateResponse.status === 404) {
601
+ logger4.info(
602
+ {
603
+ agentId: this.getId()
604
+ },
605
+ "Agent not found, creating new agent"
606
+ );
607
+ const createResponse = await fetch(
608
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agents`,
609
+ {
610
+ method: "POST",
611
+ headers: {
612
+ "Content-Type": "application/json"
613
+ },
614
+ body: JSON.stringify(agentData)
615
+ }
616
+ );
617
+ if (!createResponse.ok) {
618
+ const errorText2 = await createResponse.text().catch(() => "Unknown error");
619
+ throw new Error(
620
+ `Failed to create agent: ${createResponse.status} ${createResponse.statusText} - ${errorText2}`
621
+ );
622
+ }
623
+ logger4.info(
624
+ {
625
+ agentId: this.getId()
626
+ },
627
+ "Agent created successfully"
628
+ );
629
+ return;
630
+ }
631
+ const errorText = await updateResponse.text().catch(() => "Unknown error");
632
+ throw new Error(
633
+ `Failed to update agent: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`
634
+ );
635
+ }
636
+ async saveToolsAndRelations() {
637
+ logger4.info(
638
+ {
639
+ transfers: this.getTransfers(),
640
+ delegates: this.getDelegates(),
641
+ tools: this.config.tools
642
+ },
643
+ "transfers, delegates, and tools"
644
+ );
645
+ if (this.config.tools) {
646
+ logger4.info({ tools: this.config.tools }, "tools and config");
647
+ for (const [toolId, toolConfig] of Object.entries(this.config.tools)) {
648
+ await this.createTool(toolId, toolConfig);
649
+ }
650
+ }
651
+ }
652
+ async saveDataComponents() {
653
+ logger4.info(
654
+ { dataComponents: this.config.dataComponents },
655
+ "dataComponents and config"
656
+ );
657
+ const components = resolveGetter(this.config.dataComponents);
658
+ if (components) {
659
+ for (const dataComponent2 of components) {
660
+ await this.createDataComponent(dataComponent2);
661
+ }
662
+ }
663
+ }
664
+ async saveArtifactComponents() {
665
+ logger4.info(
666
+ { artifactComponents: this.config.artifactComponents },
667
+ "artifactComponents and config"
668
+ );
669
+ const components = resolveGetter(this.config.artifactComponents);
670
+ if (components) {
671
+ for (const artifactComponent2 of components) {
672
+ await this.createArtifactComponent(artifactComponent2);
673
+ }
674
+ }
675
+ }
676
+ async loadDataComponents() {
677
+ try {
678
+ const existingComponents = [];
679
+ const dbDataComponents = existingComponents.map((component) => ({
680
+ id: component.id,
681
+ tenantId: component.tenantId || this.tenantId,
682
+ projectId: component.projectId || this.projectId,
683
+ name: component.name,
684
+ description: component.description,
685
+ props: component.props,
686
+ createdAt: component.createdAt,
687
+ updatedAt: component.updatedAt
688
+ }));
689
+ const configComponents = resolveGetter(this.config.dataComponents) || [];
690
+ const allComponents = [...dbDataComponents, ...configComponents];
691
+ const uniqueComponents = allComponents.reduce((acc, component) => {
692
+ const existingIndex = acc.findIndex((c) => c.id === component.id);
693
+ if (existingIndex >= 0) {
694
+ acc[existingIndex] = component;
695
+ } else {
696
+ acc.push(component);
697
+ }
698
+ return acc;
699
+ }, []);
700
+ this.config.dataComponents = uniqueComponents;
701
+ logger4.info(
702
+ {
703
+ agentId: this.getId(),
704
+ dbComponentCount: dbDataComponents.length,
705
+ configComponentCount: configComponents.length,
706
+ totalComponentCount: uniqueComponents.length
707
+ },
708
+ "Loaded and merged data components"
709
+ );
710
+ } catch (error) {
711
+ logger4.error(
712
+ {
713
+ agentId: this.getId(),
714
+ error: error instanceof Error ? error.message : "Unknown error"
715
+ },
716
+ "Failed to load data components from database"
717
+ );
718
+ }
719
+ }
720
+ async loadArtifactComponents() {
721
+ try {
722
+ const existingComponents = [];
723
+ const dbArtifactComponents = existingComponents.map((component) => ({
724
+ id: component.id,
725
+ tenantId: component.tenantId || this.tenantId,
726
+ projectId: component.projectId || this.projectId,
727
+ name: component.name,
728
+ description: component.description,
729
+ summaryProps: component.summaryProps,
730
+ fullProps: component.fullProps,
731
+ createdAt: component.createdAt,
732
+ updatedAt: component.updatedAt
733
+ }));
734
+ const configComponents = resolveGetter(this.config.artifactComponents) || [];
735
+ const allComponents = [...dbArtifactComponents, ...configComponents];
736
+ const uniqueComponents = allComponents.reduce((acc, component) => {
737
+ const existingIndex = acc.findIndex((c) => c.id === component.id);
738
+ if (existingIndex >= 0) {
739
+ acc[existingIndex] = component;
740
+ } else {
741
+ acc.push(component);
742
+ }
743
+ return acc;
744
+ }, []);
745
+ this.config.artifactComponents = uniqueComponents;
746
+ logger4.info(
747
+ {
748
+ agentId: this.getId(),
749
+ dbComponentCount: dbArtifactComponents.length,
750
+ configComponentCount: configComponents.length,
751
+ totalComponentCount: uniqueComponents.length
752
+ },
753
+ "Loaded and merged artifact components"
754
+ );
755
+ } catch (error) {
756
+ logger4.error(
757
+ {
758
+ agentId: this.getId(),
759
+ error: error instanceof Error ? error.message : "Unknown error"
760
+ },
761
+ "Failed to load artifact components from database"
762
+ );
763
+ }
764
+ }
765
+ async createTool(toolId, toolConfig) {
766
+ try {
767
+ if (toolConfig.type === "function") {
768
+ logger4.info(
769
+ {
770
+ agentId: this.getId(),
771
+ toolId,
772
+ toolType: "function"
773
+ },
774
+ "Skipping function tool creation - will be handled at runtime"
775
+ );
776
+ return;
777
+ }
778
+ const { Tool: Tool2 } = await Promise.resolve().then(() => (init_tool(), tool_exports));
779
+ let tool2;
780
+ if (toolConfig instanceof Tool2) {
781
+ logger4.info(
782
+ {
783
+ agentId: this.getId(),
784
+ toolId,
785
+ toolType: "Tool"
786
+ },
787
+ "Initializing Tool instance"
788
+ );
789
+ tool2 = toolConfig;
790
+ await tool2.init();
791
+ } else {
792
+ logger4.info(
793
+ {
794
+ agentId: this.getId(),
795
+ toolId,
796
+ toolType: "legacy-config"
797
+ },
798
+ "Creating Tool from config"
799
+ );
800
+ tool2 = new Tool2({
801
+ id: toolId,
802
+ tenantId: this.tenantId,
803
+ name: toolConfig.name || toolId,
804
+ description: toolConfig.description || `MCP tool: ${toolId}`,
805
+ serverUrl: toolConfig.config?.serverUrl || toolConfig.serverUrl || "http://localhost:3000",
806
+ activeTools: toolConfig.config?.mcp?.activeTools,
807
+ credential: toolConfig.credential
808
+ });
809
+ await tool2.init();
810
+ }
811
+ await this.createAgentToolRelation(tool2.getId());
812
+ logger4.info(
813
+ {
814
+ agentId: this.getId(),
815
+ toolId: tool2.getId()
816
+ },
817
+ "Tool created and linked to agent"
818
+ );
819
+ } catch (error) {
820
+ logger4.error(
821
+ {
822
+ agentId: this.getId(),
823
+ toolId,
824
+ error: error instanceof Error ? error.message : "Unknown error"
825
+ },
826
+ "Failed to create tool"
827
+ );
828
+ }
829
+ }
830
+ async createDataComponent(dataComponent2) {
831
+ try {
832
+ const dc = new DataComponent({
833
+ tenantId: this.tenantId,
834
+ projectId: this.projectId,
835
+ name: dataComponent2.name,
836
+ description: dataComponent2.description,
837
+ props: dataComponent2.props
838
+ });
839
+ await dc.init();
840
+ await this.createAgentDataComponentRelation(dc.getId());
841
+ logger4.info(
842
+ {
843
+ agentId: this.getId(),
844
+ dataComponentId: dc.getId()
845
+ },
846
+ "DataComponent created and linked to agent"
847
+ );
848
+ } catch (error) {
849
+ logger4.error(
850
+ {
851
+ agentId: this.getId(),
852
+ dataComponentName: dataComponent2.name,
853
+ error: error instanceof Error ? error.message : "Unknown error"
854
+ },
855
+ "Failed to create data component"
856
+ );
857
+ throw error;
858
+ }
859
+ }
860
+ async createArtifactComponent(artifactComponent2) {
861
+ try {
862
+ const ac = new ArtifactComponent({
863
+ tenantId: this.tenantId,
864
+ projectId: this.projectId,
865
+ name: artifactComponent2.name,
866
+ description: artifactComponent2.description,
867
+ summaryProps: artifactComponent2.summaryProps,
868
+ fullProps: artifactComponent2.fullProps
869
+ });
870
+ await ac.init();
871
+ await this.createAgentArtifactComponentRelation(ac.getId());
872
+ logger4.info(
873
+ {
874
+ agentId: this.getId(),
875
+ artifactComponentId: ac.getId()
876
+ },
877
+ "ArtifactComponent created and linked to agent"
878
+ );
879
+ } catch (error) {
880
+ logger4.error(
881
+ {
882
+ agentId: this.getId(),
883
+ artifactComponentName: artifactComponent2.name,
884
+ error: error instanceof Error ? error.message : "Unknown error"
885
+ },
886
+ "Failed to create artifact component"
887
+ );
888
+ throw error;
889
+ }
890
+ }
891
+ async createAgentDataComponentRelation(dataComponentId) {
892
+ const relationResponse = await fetch(
893
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agent-data-components`,
894
+ {
895
+ method: "POST",
896
+ headers: {
897
+ "Content-Type": "application/json"
898
+ },
899
+ body: JSON.stringify({
900
+ id: `${this.getId()}-dc-${dataComponentId}`,
901
+ tenantId: this.tenantId,
902
+ agentId: this.getId(),
903
+ dataComponentId
904
+ })
905
+ }
906
+ );
907
+ if (!relationResponse.ok) {
908
+ throw new Error(
909
+ `Failed to create agent-dataComponent relation: ${relationResponse.status} ${relationResponse.statusText}`
910
+ );
911
+ }
912
+ logger4.info(
913
+ {
914
+ agentId: this.getId(),
915
+ dataComponentId
916
+ },
917
+ "Created agent-dataComponent relation"
918
+ );
919
+ }
920
+ async createAgentArtifactComponentRelation(artifactComponentId) {
921
+ const relationResponse = await fetch(
922
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agent-artifact-components`,
923
+ {
924
+ method: "POST",
925
+ headers: {
926
+ "Content-Type": "application/json"
927
+ },
928
+ body: JSON.stringify({
929
+ id: crypto.randomUUID(),
930
+ tenantId: this.tenantId,
931
+ agentId: this.getId(),
932
+ artifactComponentId
933
+ })
934
+ }
935
+ );
936
+ if (!relationResponse.ok) {
937
+ throw new Error(
938
+ `Failed to create agent-artifactComponent relation: ${relationResponse.status} ${relationResponse.statusText}`
939
+ );
940
+ }
941
+ logger4.info(
942
+ {
943
+ agentId: this.getId(),
944
+ artifactComponentId
945
+ },
946
+ "Created agent-artifactComponent relation"
947
+ );
948
+ }
949
+ async createAgentToolRelation(toolId) {
950
+ const relationResponse = await fetch(
951
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agent-tool-relations`,
952
+ {
953
+ method: "POST",
954
+ headers: {
955
+ "Content-Type": "application/json"
956
+ },
957
+ body: JSON.stringify({
958
+ id: `${this.getId()}-tool-${toolId}`,
959
+ tenantId: this.tenantId,
960
+ agentId: this.getId(),
961
+ toolId
962
+ })
963
+ }
964
+ );
965
+ if (!relationResponse.ok) {
966
+ const errorBody = await relationResponse.text().catch(() => "Unknown error");
967
+ throw new Error(
968
+ `Failed to create agent-tool relation: ${relationResponse.status} - ${errorBody}`
969
+ );
970
+ }
971
+ }
972
+ };
973
+ init_tool();
974
+ function agent(config) {
975
+ return new Agent(config);
976
+ }
977
+ function credential(config) {
978
+ return agentsCore.CredentialReferenceApiInsertSchema.parse(config);
979
+ }
980
+ var ToolConfigSchema = zod.z.object({
981
+ id: zod.z.string().optional(),
982
+ name: zod.z.string(),
983
+ description: zod.z.string(),
984
+ parameters: zod.z.record(zod.z.string(), zod.z.any()).optional(),
985
+ schema: zod.z.unknown().optional()
986
+ });
987
+ ToolConfigSchema.extend({
988
+ execute: zod.z.any()
989
+ // Function - validated separately at runtime
990
+ });
991
+ function tool(config) {
992
+ if (typeof config.execute !== "function") {
993
+ throw new Error("execute must be a function");
994
+ }
995
+ const { execute, ...configWithoutFunction } = config;
996
+ const validatedConfig = ToolConfigSchema.parse(configWithoutFunction);
997
+ const fullConfig = { ...validatedConfig, execute };
998
+ const computedId = fullConfig.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
999
+ return {
1000
+ id: computedId,
1001
+ name: fullConfig.name,
1002
+ description: fullConfig.description,
1003
+ execute: fullConfig.execute,
1004
+ parameters: fullConfig.parameters,
1005
+ schema: fullConfig.schema,
1006
+ type: "function"
1007
+ };
1008
+ }
1009
+ zod.z.object({
1010
+ id: zod.z.string().optional(),
1011
+ name: zod.z.string(),
1012
+ description: zod.z.string(),
1013
+ tenantId: zod.z.string().optional(),
1014
+ // Deployment configuration
1015
+ deployment: zod.z.enum(["local", "remote"]).optional(),
1016
+ // For local MCP servers
1017
+ port: zod.z.number().optional(),
1018
+ // For remote MCP servers
1019
+ serverUrl: zod.z.string().optional(),
1020
+ credential: agentsCore.CredentialReferenceApiInsertSchema.optional(),
1021
+ // Additional configuration
1022
+ parameters: zod.z.record(zod.z.string(), zod.z.any()).optional(),
1023
+ transport: zod.z.enum(["ipc", "http", "sse"]).optional(),
1024
+ activeTools: zod.z.array(zod.z.string()).optional(),
1025
+ headers: zod.z.record(zod.z.string(), zod.z.string()).optional()
1026
+ });
1027
+ function mcpServer(config) {
1028
+ const deployment = config.deployment || (config.execute ? "local" : "remote");
1029
+ const id = config.id || config.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1030
+ if (deployment === "local") {
1031
+ if (!config.execute) {
1032
+ throw new Error("Local MCP server requires an execute function");
1033
+ }
1034
+ throw new Error(
1035
+ "Local MCP servers are no longer supported. Please use remote MCP servers instead."
1036
+ );
1037
+ } else {
1038
+ if (!config.serverUrl) {
1039
+ throw new Error("Remote MCP server requires a serverUrl");
1040
+ }
1041
+ return new exports.Tool({
1042
+ id,
1043
+ name: config.name,
1044
+ description: config.description,
1045
+ serverUrl: config.serverUrl,
1046
+ tenantId: config.tenantId,
1047
+ credential: config.credential,
1048
+ activeTools: config.activeTools,
1049
+ headers: config.headers
1050
+ });
1051
+ }
1052
+ }
1053
+ function mcpTool(config) {
1054
+ const validatedConfig = agentsCore.MCPToolConfigSchema.parse(config);
1055
+ return new exports.Tool(validatedConfig);
1056
+ }
1057
+ var TransferConfigSchema = zod.z.object({
1058
+ agent: zod.z.instanceof(Agent),
1059
+ description: zod.z.string().optional()
1060
+ });
1061
+ var TransferSchema = TransferConfigSchema.extend({
1062
+ condition: zod.z.any().optional()
1063
+ // Function - validated separately at runtime when present
1064
+ });
1065
+ function transfer(targetAgent, description, condition) {
1066
+ if (condition !== void 0 && typeof condition !== "function") {
1067
+ throw new Error("condition must be a function when provided");
1068
+ }
1069
+ const config = {
1070
+ agent: targetAgent,
1071
+ description: description || `Hand off to ${targetAgent.getName()}`,
1072
+ condition
1073
+ };
1074
+ return TransferSchema.parse(config);
1075
+ }
1076
+ function artifactComponent(config) {
1077
+ return new ArtifactComponent({
1078
+ ...config,
1079
+ tenantId: config.tenantId || "default",
1080
+ projectId: config.projectId || "default"
1081
+ });
1082
+ }
1083
+ function dataComponent(config) {
1084
+ return new DataComponent({
1085
+ ...config,
1086
+ tenantId: config.tenantId || "default",
1087
+ projectId: config.projectId || "default"
1088
+ });
1089
+ }
1090
+
1091
+ // src/environment-settings.ts
1092
+ var globalSettingKeys = /* @__PURE__ */ new Set();
1093
+ function registerSettingKeys(settingIds) {
1094
+ settingIds.forEach((id) => globalSettingKeys.add(id));
1095
+ }
1096
+ function getAllEnvironmentSettingKeys() {
1097
+ return Array.from(globalSettingKeys);
1098
+ }
1099
+ function createEnvironmentSettings(environments) {
1100
+ const environmentMap = environments;
1101
+ const environmentNames = Object.keys(environments);
1102
+ const allEnvironments = Object.values(environments);
1103
+ return {
1104
+ getEnvironmentSetting: async (key) => {
1105
+ if (environmentNames.length === 0) {
1106
+ throw new Error(
1107
+ `No environments provided to createEnvironmentSettings().
1108
+
1109
+ You must pass environments as an object: createEnvironmentSettings({ development, production })`
1110
+ );
1111
+ }
1112
+ const currentEnv = process.env.NODE_ENV || "development";
1113
+ const matchingEnv = environmentMap[currentEnv];
1114
+ if (!matchingEnv) {
1115
+ throw new Error(
1116
+ `Environment '${currentEnv}' not found.
1117
+
1118
+ Available environments: ${environmentNames.join(", ")}
1119
+ Set NODE_ENV to one of the available environments or add a '${currentEnv}' environment.`
1120
+ );
1121
+ }
1122
+ if (!matchingEnv.credentials?.[key]) {
1123
+ throw new Error(
1124
+ `Credential environment setting '${key}' not found in environment '${currentEnv}'.
1125
+
1126
+ `
1127
+ );
1128
+ }
1129
+ return matchingEnv.credentials[key];
1130
+ },
1131
+ getEnvironmentSettingKeys: () => {
1132
+ if (allEnvironments.length === 0) return [];
1133
+ if (allEnvironments.length === 1)
1134
+ return Object.keys(allEnvironments[0].credentials || {});
1135
+ let commonKeys = new Set(
1136
+ Object.keys(allEnvironments[0].credentials || {})
1137
+ );
1138
+ for (let i = 1; i < allEnvironments.length; i++) {
1139
+ const envKeys = new Set(
1140
+ Object.keys(allEnvironments[i].credentials || {})
1141
+ );
1142
+ commonKeys = new Set([...commonKeys].filter((key) => envKeys.has(key)));
1143
+ }
1144
+ return Array.from(commonKeys);
1145
+ },
1146
+ hasEnvironmentSetting: (key) => {
1147
+ if (allEnvironments.length === 0) return false;
1148
+ if (allEnvironments.length === 1)
1149
+ return !!(allEnvironments[0].credentials && key in allEnvironments[0].credentials);
1150
+ return allEnvironments.every(
1151
+ (env) => env.credentials && key in env.credentials
1152
+ );
1153
+ }
1154
+ };
1155
+ }
1156
+ function registerEnvironmentSettings(config) {
1157
+ if (config.credentials) {
1158
+ const settingIds = Object.keys(config.credentials);
1159
+ registerSettingKeys(settingIds);
1160
+ }
1161
+ return config;
1162
+ }
1163
+ var logger5 = agentsCore.getLogger("external-agent-builder");
1164
+ var ExternalAgent = class {
1165
+ constructor(config) {
1166
+ __publicField(this, "config");
1167
+ __publicField(this, "type", "external");
1168
+ __publicField(this, "initialized", false);
1169
+ __publicField(this, "tenantId");
1170
+ __publicField(this, "baseURL");
1171
+ this.config = { ...config, type: "external" };
1172
+ this.tenantId = config.tenantId || "default";
1173
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
1174
+ logger5.debug(
1175
+ {
1176
+ externalAgentName: this.config.name,
1177
+ baseUrl: this.config.baseUrl,
1178
+ tenantId: this.config.tenantId
1179
+ },
1180
+ "External Agent constructor initialized"
1181
+ );
1182
+ }
1183
+ /**
1184
+ * Initialize the external agent by upserting it in the database
1185
+ */
1186
+ async init() {
1187
+ if (this.initialized) return;
1188
+ try {
1189
+ await this.upsertExternalAgent();
1190
+ logger5.info(
1191
+ {
1192
+ externalAgentId: this.getId()
1193
+ },
1194
+ "External agent initialized successfully"
1195
+ );
1196
+ this.initialized = true;
1197
+ } catch (error) {
1198
+ logger5.error(
1199
+ {
1200
+ externalAgentId: this.getId(),
1201
+ error: error instanceof Error ? error.message : "Unknown error"
1202
+ },
1203
+ "Failed to initialize external agent"
1204
+ );
1205
+ throw error;
1206
+ }
1207
+ }
1208
+ // Compute ID from name using a simple slug transformation
1209
+ getId() {
1210
+ return this.config.id;
1211
+ }
1212
+ // Private method to upsert external agent (create or update)
1213
+ async upsertExternalAgent() {
1214
+ const externalAgentData = {
1215
+ id: this.getId(),
1216
+ name: this.config.name,
1217
+ description: this.config.description,
1218
+ baseUrl: this.config.baseUrl,
1219
+ credentialReferenceId: this.config.credentialReference?.id || void 0,
1220
+ headers: this.config.headers || void 0
1221
+ };
1222
+ const updateResponse = await fetch(
1223
+ `${this.baseURL}/tenants/${this.tenantId}/crud/external-agents/${this.getId()}`,
1224
+ {
1225
+ method: "PUT",
1226
+ headers: {
1227
+ "Content-Type": "application/json"
1228
+ },
1229
+ body: JSON.stringify(externalAgentData)
1230
+ }
1231
+ );
1232
+ if (updateResponse.ok) {
1233
+ logger5.info(
1234
+ {
1235
+ externalAgentId: this.getId()
1236
+ },
1237
+ "External agent updated successfully"
1238
+ );
1239
+ return;
1240
+ }
1241
+ if (updateResponse.status === 404) {
1242
+ logger5.info(
1243
+ {
1244
+ externalAgentId: this.getId()
1245
+ },
1246
+ "External agent not found, creating new external agent"
1247
+ );
1248
+ const createResponse = await fetch(
1249
+ `${this.baseURL}/tenants/${this.tenantId}/crud/external-agents`,
1250
+ {
1251
+ method: "POST",
1252
+ headers: {
1253
+ "Content-Type": "application/json"
1254
+ },
1255
+ body: JSON.stringify(externalAgentData)
1256
+ }
1257
+ );
1258
+ if (!createResponse.ok) {
1259
+ const errorText2 = await createResponse.text().catch(() => "Unknown error");
1260
+ throw new Error(
1261
+ `Failed to create external agent: ${createResponse.status} ${createResponse.statusText} - ${errorText2}`
1262
+ );
1263
+ }
1264
+ logger5.info(
1265
+ {
1266
+ externalAgentId: this.getId()
1267
+ },
1268
+ "External agent created successfully"
1269
+ );
1270
+ return;
1271
+ }
1272
+ const errorText = await updateResponse.text().catch(() => "Unknown error");
1273
+ throw new Error(
1274
+ `Failed to update external agent: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`
1275
+ );
1276
+ }
1277
+ /**
1278
+ * Get the external agent configuration
1279
+ */
1280
+ getConfig() {
1281
+ return { ...this.config };
1282
+ }
1283
+ /**
1284
+ * Get the external agent name
1285
+ */
1286
+ getName() {
1287
+ return this.config.name;
1288
+ }
1289
+ /**
1290
+ * Get the external agent base URL
1291
+ */
1292
+ getBaseUrl() {
1293
+ return this.config.baseUrl;
1294
+ }
1295
+ /**
1296
+ * Get the tenant ID
1297
+ */
1298
+ getTenantId() {
1299
+ return this.tenantId;
1300
+ }
1301
+ getDescription() {
1302
+ return this.config.description || "";
1303
+ }
1304
+ getCredentialReferenceId() {
1305
+ return this.config.credentialReference?.id || void 0;
1306
+ }
1307
+ getHeaders() {
1308
+ return this.config.headers;
1309
+ }
1310
+ };
1311
+ function externalAgent(config) {
1312
+ return new ExternalAgent(config);
1313
+ }
1314
+ function externalAgents(configs) {
1315
+ const builders = {};
1316
+ for (const [name, config] of Object.entries(configs)) {
1317
+ builders[name] = externalAgent(config);
1318
+ }
1319
+ return builders;
1320
+ }
1321
+ var logger6 = agentsCore.getLogger("graphFullClient");
1322
+ async function updateFullGraphViaAPI(tenantId, projectId, apiUrl, graphId, graphData) {
1323
+ logger6.info(
1324
+ {
1325
+ tenantId,
1326
+ projectId,
1327
+ graphId,
1328
+ apiUrl
1329
+ },
1330
+ "Updating full graph via API"
1331
+ );
1332
+ const url = `${apiUrl}/tenants/${tenantId}/crud/projects/${projectId}/graph/${graphId}`;
1333
+ const response = await fetch(url, {
1334
+ method: "PUT",
1335
+ headers: {
1336
+ "Content-Type": "application/json"
1337
+ },
1338
+ body: JSON.stringify(graphData)
1339
+ });
1340
+ if (!response.ok) {
1341
+ const errorText = await response.text();
1342
+ let errorMessage = `Failed to update graph: ${response.status} ${response.statusText}`;
1343
+ try {
1344
+ const errorJson = JSON.parse(errorText);
1345
+ if (errorJson.error) {
1346
+ errorMessage = errorJson.error;
1347
+ }
1348
+ } catch {
1349
+ if (errorText) {
1350
+ errorMessage = errorText;
1351
+ }
1352
+ }
1353
+ logger6.error(
1354
+ {
1355
+ status: response.status,
1356
+ error: errorMessage
1357
+ },
1358
+ "Failed to update graph via API"
1359
+ );
1360
+ throw new Error(errorMessage);
1361
+ }
1362
+ const result = await response.json();
1363
+ logger6.info(
1364
+ {
1365
+ graphId
1366
+ },
1367
+ "Successfully updated graph via API"
1368
+ );
1369
+ return result.data;
1370
+ }
1371
+
1372
+ // src/graph.ts
1373
+ var logger7 = agentsCore.getLogger("graph");
1374
+ function resolveGetter2(value) {
1375
+ if (typeof value === "function") {
1376
+ return value();
1377
+ }
1378
+ return value;
1379
+ }
1380
+ var AgentGraph = class {
1381
+ constructor(config) {
1382
+ __publicField(this, "agents", []);
1383
+ __publicField(this, "agentMap", /* @__PURE__ */ new Map());
1384
+ __publicField(this, "defaultAgent");
1385
+ __publicField(this, "baseURL");
1386
+ __publicField(this, "tenantId");
1387
+ __publicField(this, "projectId");
1388
+ __publicField(this, "graphId");
1389
+ __publicField(this, "graphName");
1390
+ __publicField(this, "graphDescription");
1391
+ __publicField(this, "initialized", false);
1392
+ __publicField(this, "contextConfig");
1393
+ // ContextConfigBuilder
1394
+ __publicField(this, "credentials");
1395
+ __publicField(this, "models");
1396
+ __publicField(this, "statusUpdateSettings");
1397
+ __publicField(this, "graphPrompt");
1398
+ __publicField(this, "stopWhen");
1399
+ __publicField(this, "dbClient");
1400
+ this.defaultAgent = config.defaultAgent;
1401
+ this.tenantId = config.tenantId || "default";
1402
+ this.projectId = "default";
1403
+ this.graphId = config.id;
1404
+ this.graphName = config.name || this.graphId;
1405
+ this.graphDescription = config.description;
1406
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
1407
+ this.contextConfig = config.contextConfig;
1408
+ this.credentials = resolveGetter2(config.credentials);
1409
+ this.models = config.models;
1410
+ const dbUrl = process.env.ENVIRONMENT === "test" ? ":memory:" : process.env.DB_FILE_NAME || process.env.DATABASE_URL || ":memory:";
1411
+ this.dbClient = agentsCore.createDatabaseClient({
1412
+ url: dbUrl
1413
+ });
1414
+ this.statusUpdateSettings = config.statusUpdates;
1415
+ this.graphPrompt = config.graphPrompt;
1416
+ this.stopWhen = config.stopWhen ? {
1417
+ transferCountIs: config.stopWhen.transferCountIs
1418
+ } : void 0;
1419
+ this.agents = resolveGetter2(config.agents) || [];
1420
+ this.agentMap = new Map(this.agents.map((agent2) => [agent2.getId(), agent2]));
1421
+ if (this.defaultAgent) {
1422
+ this.agents.push(this.defaultAgent);
1423
+ this.agentMap.set(this.defaultAgent.getId(), this.defaultAgent);
1424
+ }
1425
+ if (this.models) {
1426
+ this.propagateImmediateModelSettings();
1427
+ }
1428
+ logger7.info(
1429
+ {
1430
+ graphId: this.graphId,
1431
+ tenantId: this.tenantId,
1432
+ agentCount: this.agents.length,
1433
+ defaultAgent: this.defaultAgent?.getName()
1434
+ },
1435
+ "AgentGraph created"
1436
+ );
1437
+ }
1438
+ /**
1439
+ * Set or update the configuration (tenantId, projectId and apiUrl)
1440
+ * This is used by the CLI to inject configuration from inkeep.config.ts
1441
+ */
1442
+ setConfig(tenantId, projectId, apiUrl) {
1443
+ if (this.initialized) {
1444
+ throw new Error("Cannot set config after graph has been initialized");
1445
+ }
1446
+ this.tenantId = tenantId;
1447
+ this.projectId = projectId;
1448
+ this.baseURL = apiUrl;
1449
+ for (const agent2 of this.agents) {
1450
+ if (this.isInternalAgent(agent2)) {
1451
+ const internalAgent = agent2;
1452
+ if (!internalAgent.config.tenantId) {
1453
+ internalAgent.config.tenantId = tenantId;
1454
+ }
1455
+ const tools = internalAgent.getTools();
1456
+ for (const [_, toolInstance] of Object.entries(tools)) {
1457
+ if (toolInstance && typeof toolInstance === "object" && toolInstance.config) {
1458
+ if (!toolInstance.config.tenantId) {
1459
+ toolInstance.config.tenantId = tenantId;
1460
+ }
1461
+ if ("baseURL" in toolInstance && !toolInstance.baseURL) {
1462
+ toolInstance.baseURL = apiUrl;
1463
+ }
1464
+ }
1465
+ }
1466
+ }
1467
+ }
1468
+ if (this.contextConfig && !this.contextConfig.tenantId) {
1469
+ this.contextConfig.tenantId = tenantId;
1470
+ }
1471
+ logger7.info(
1472
+ {
1473
+ graphId: this.graphId,
1474
+ tenantId: this.tenantId,
1475
+ projectId: this.projectId,
1476
+ apiUrl: this.baseURL
1477
+ },
1478
+ "Graph configuration updated"
1479
+ );
1480
+ }
1481
+ /**
1482
+ * Convert the AgentGraph to FullGraphDefinition format for the new graph endpoint
1483
+ */
1484
+ async toFullGraphDefinition() {
1485
+ const agentsObject = {};
1486
+ for (const agent2 of this.agents) {
1487
+ if (this.isInternalAgent(agent2)) {
1488
+ const internalAgent = agent2;
1489
+ const transfers = internalAgent.getTransfers();
1490
+ const delegates = internalAgent.getDelegates();
1491
+ const tools = [];
1492
+ const agentTools = internalAgent.getTools();
1493
+ for (const [toolName, toolInstance] of Object.entries(agentTools)) {
1494
+ if (toolInstance && typeof toolInstance === "object") {
1495
+ const toolId = toolInstance.getId?.() || toolInstance.id || toolName;
1496
+ tools.push(toolId);
1497
+ }
1498
+ }
1499
+ const dataComponents = [];
1500
+ const agentDataComponents = internalAgent.getDataComponents();
1501
+ if (agentDataComponents) {
1502
+ for (const dataComponent2 of agentDataComponents) {
1503
+ const dataComponentId = dataComponent2.id || dataComponent2.name.toLowerCase().replace(/\s+/g, "-");
1504
+ dataComponents.push(dataComponentId);
1505
+ }
1506
+ }
1507
+ const artifactComponents = [];
1508
+ const agentArtifactComponents = internalAgent.getArtifactComponents();
1509
+ if (agentArtifactComponents) {
1510
+ for (const artifactComponent2 of agentArtifactComponents) {
1511
+ const artifactComponentId = artifactComponent2.id || artifactComponent2.name.toLowerCase().replace(/\s+/g, "-");
1512
+ artifactComponents.push(artifactComponentId);
1513
+ }
1514
+ }
1515
+ agentsObject[internalAgent.getId()] = {
1516
+ id: internalAgent.getId(),
1517
+ name: internalAgent.getName(),
1518
+ description: internalAgent.config.description || `Agent ${internalAgent.getName()}`,
1519
+ prompt: internalAgent.getInstructions(),
1520
+ models: internalAgent.config.models,
1521
+ canTransferTo: transfers.map((h) => h.getId()),
1522
+ canDelegateTo: delegates.map((d) => d.getId()),
1523
+ tools,
1524
+ dataComponents: dataComponents.length > 0 ? dataComponents : void 0,
1525
+ artifactComponents: artifactComponents.length > 0 ? artifactComponents : void 0,
1526
+ type: "internal"
1527
+ };
1528
+ } else {
1529
+ const externalAgent2 = agent2;
1530
+ agentsObject[externalAgent2.getId()] = {
1531
+ id: externalAgent2.getId(),
1532
+ name: externalAgent2.getName(),
1533
+ description: externalAgent2.getDescription(),
1534
+ baseUrl: externalAgent2.getBaseUrl(),
1535
+ credentialReferenceId: externalAgent2.getCredentialReferenceId(),
1536
+ headers: externalAgent2.getHeaders(),
1537
+ tools: [],
1538
+ // External agents don't have tools in this context
1539
+ type: "external"
1540
+ };
1541
+ }
1542
+ }
1543
+ const toolsObject = {};
1544
+ for (const agent2 of this.agents) {
1545
+ if (!agent2.getTransfers) {
1546
+ continue;
1547
+ }
1548
+ const internalAgent = agent2;
1549
+ const agentTools = internalAgent.getTools();
1550
+ for (const [toolName, toolInstance] of Object.entries(agentTools)) {
1551
+ if (toolInstance && typeof toolInstance === "object") {
1552
+ const toolId = toolInstance.getId?.() || toolInstance.id || toolName;
1553
+ if (!toolsObject[toolId]) {
1554
+ let toolConfig;
1555
+ if (toolInstance.config?.serverUrl) {
1556
+ toolConfig = {
1557
+ type: "mcp",
1558
+ mcp: {
1559
+ server: {
1560
+ url: toolInstance.config.serverUrl
1561
+ }
1562
+ }
1563
+ };
1564
+ } else if (toolInstance.config?.type === "mcp") {
1565
+ toolConfig = toolInstance.config;
1566
+ } else {
1567
+ toolConfig = {
1568
+ type: "function",
1569
+ parameters: toolInstance.parameters || {}
1570
+ };
1571
+ }
1572
+ const toolData = {
1573
+ id: toolId,
1574
+ name: toolInstance.config?.name || toolInstance.name || toolName,
1575
+ config: toolConfig,
1576
+ status: toolInstance.getStatus?.() || toolInstance.status || "unknown"
1577
+ };
1578
+ if (toolInstance.config?.imageUrl) {
1579
+ toolData.imageUrl = toolInstance.config.imageUrl;
1580
+ }
1581
+ if (toolInstance.config?.headers) {
1582
+ toolData.headers = toolInstance.config.headers;
1583
+ }
1584
+ if (toolInstance.capabilities) {
1585
+ toolData.capabilities = toolInstance.capabilities;
1586
+ }
1587
+ if (toolInstance.lastHealthCheck) {
1588
+ toolData.lastHealthCheck = toolInstance.lastHealthCheck;
1589
+ }
1590
+ if (toolInstance.availableTools) {
1591
+ toolData.availableTools = toolInstance.availableTools;
1592
+ }
1593
+ if (toolInstance.lastError) {
1594
+ toolData.lastError = toolInstance.lastError;
1595
+ }
1596
+ if (toolInstance.lastToolsSync) {
1597
+ toolData.lastToolsSync = toolInstance.lastToolsSync;
1598
+ }
1599
+ if (toolInstance.getCredentialReferenceId?.()) {
1600
+ toolData.credentialReferenceId = toolInstance.getCredentialReferenceId();
1601
+ }
1602
+ toolsObject[toolId] = toolData;
1603
+ }
1604
+ }
1605
+ }
1606
+ }
1607
+ const dataComponentsObject = {};
1608
+ for (const agent2 of this.agents) {
1609
+ if (!this.isInternalAgent(agent2)) {
1610
+ continue;
1611
+ }
1612
+ const internalAgent = agent2;
1613
+ const agentDataComponents = internalAgent.getDataComponents();
1614
+ if (agentDataComponents) {
1615
+ for (const dataComponent2 of agentDataComponents) {
1616
+ const dataComponentId = dataComponent2.id || dataComponent2.name.toLowerCase().replace(/\s+/g, "-");
1617
+ if (!dataComponentsObject[dataComponentId]) {
1618
+ dataComponentsObject[dataComponentId] = {
1619
+ id: dataComponentId,
1620
+ name: dataComponent2.name,
1621
+ description: dataComponent2.description || "",
1622
+ props: dataComponent2.props || {}
1623
+ };
1624
+ }
1625
+ }
1626
+ }
1627
+ }
1628
+ const artifactComponentsObject = {};
1629
+ for (const agent2 of this.agents) {
1630
+ if (!this.isInternalAgent(agent2)) {
1631
+ continue;
1632
+ }
1633
+ const internalAgent = agent2;
1634
+ const agentArtifactComponents = internalAgent.getArtifactComponents();
1635
+ if (agentArtifactComponents) {
1636
+ for (const artifactComponent2 of agentArtifactComponents) {
1637
+ const artifactComponentId = artifactComponent2.id || artifactComponent2.name.toLowerCase().replace(/\s+/g, "-");
1638
+ if (!artifactComponentsObject[artifactComponentId]) {
1639
+ artifactComponentsObject[artifactComponentId] = {
1640
+ id: artifactComponentId,
1641
+ name: artifactComponent2.name,
1642
+ description: artifactComponent2.description || "",
1643
+ summaryProps: artifactComponent2.summaryProps || {},
1644
+ fullProps: artifactComponent2.fullProps || {}
1645
+ };
1646
+ }
1647
+ }
1648
+ }
1649
+ }
1650
+ return {
1651
+ id: this.graphId,
1652
+ name: this.graphName,
1653
+ description: this.graphDescription,
1654
+ defaultAgentId: this.defaultAgent?.getId() || "",
1655
+ agents: agentsObject,
1656
+ tools: toolsObject,
1657
+ contextConfig: this.contextConfig?.toObject(),
1658
+ credentialReferences: this.credentials?.map((credentialReference) => ({
1659
+ type: credentialReference.type,
1660
+ id: credentialReference.id,
1661
+ credentialStoreId: credentialReference.credentialStoreId,
1662
+ retrievalParams: credentialReference.retrievalParams || {}
1663
+ })),
1664
+ models: this.models,
1665
+ statusUpdates: this.statusUpdateSettings,
1666
+ graphPrompt: this.graphPrompt,
1667
+ dataComponents: Object.keys(dataComponentsObject).length > 0 ? dataComponentsObject : void 0,
1668
+ artifactComponents: Object.keys(artifactComponentsObject).length > 0 ? artifactComponentsObject : void 0,
1669
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1670
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1671
+ };
1672
+ }
1673
+ /**
1674
+ * Initialize all tools in all agents (especially IPCTools that need MCP server URLs)
1675
+ */
1676
+ async initializeAllTools() {
1677
+ logger7.info({ graphId: this.graphId }, "Initializing all tools in graph");
1678
+ const toolInitPromises = [];
1679
+ for (const agent2 of this.agents) {
1680
+ if (!agent2.getTools) {
1681
+ continue;
1682
+ }
1683
+ const internalAgent = agent2;
1684
+ const agentTools = internalAgent.getTools();
1685
+ for (const [toolName, toolInstance] of Object.entries(agentTools)) {
1686
+ if (toolInstance && typeof toolInstance === "object") {
1687
+ if (typeof toolInstance.init === "function") {
1688
+ toolInitPromises.push(
1689
+ (async () => {
1690
+ try {
1691
+ const skipDbRegistration = toolInstance.constructor.name === "IPCTool" || toolInstance.constructor.name === "HostedTool" || toolInstance.constructor.name === "Tool";
1692
+ if (typeof toolInstance.init === "function") {
1693
+ if (skipDbRegistration) {
1694
+ await toolInstance.init({
1695
+ skipDatabaseRegistration: true
1696
+ });
1697
+ } else {
1698
+ await toolInstance.init();
1699
+ }
1700
+ }
1701
+ logger7.debug(
1702
+ {
1703
+ agentId: agent2.getId(),
1704
+ toolName,
1705
+ toolType: toolInstance.constructor.name,
1706
+ skipDbRegistration
1707
+ },
1708
+ "Tool initialized successfully"
1709
+ );
1710
+ } catch (error) {
1711
+ logger7.error(
1712
+ {
1713
+ agentId: agent2.getId(),
1714
+ toolName,
1715
+ error: error instanceof Error ? error.message : "Unknown error"
1716
+ },
1717
+ "Failed to initialize tool"
1718
+ );
1719
+ throw error;
1720
+ }
1721
+ })()
1722
+ );
1723
+ }
1724
+ }
1725
+ }
1726
+ }
1727
+ await Promise.all(toolInitPromises);
1728
+ logger7.info(
1729
+ { graphId: this.graphId, toolCount: toolInitPromises.length },
1730
+ "All tools initialized successfully"
1731
+ );
1732
+ }
1733
+ /**
1734
+ * Initialize the graph and all agents in the backend using the new graph endpoint
1735
+ */
1736
+ async init() {
1737
+ if (this.initialized) {
1738
+ logger7.info({ graphId: this.graphId }, "Graph already initialized");
1739
+ return;
1740
+ }
1741
+ logger7.info(
1742
+ {
1743
+ graphId: this.graphId,
1744
+ agentCount: this.agents.length
1745
+ },
1746
+ "Initializing agent graph using new graph endpoint"
1747
+ );
1748
+ try {
1749
+ await this.initializeAllTools();
1750
+ await this.applyModelInheritance();
1751
+ const graphDefinition = await this.toFullGraphDefinition();
1752
+ logger7.info(
1753
+ {
1754
+ graphId: this.graphId,
1755
+ mode: "api-client",
1756
+ apiUrl: this.baseURL
1757
+ },
1758
+ "Using API client to create/update graph"
1759
+ );
1760
+ const createdGraph = await updateFullGraphViaAPI(
1761
+ this.tenantId,
1762
+ this.projectId,
1763
+ this.baseURL,
1764
+ this.graphId,
1765
+ graphDefinition
1766
+ );
1767
+ logger7.info(
1768
+ {
1769
+ graphId: this.graphId,
1770
+ agentCount: Object.keys(createdGraph.agents || {}).length
1771
+ },
1772
+ "Agent graph initialized successfully using graph endpoint"
1773
+ );
1774
+ this.initialized = true;
1775
+ } catch (error) {
1776
+ logger7.error(
1777
+ {
1778
+ graphId: this.graphId,
1779
+ error: error instanceof Error ? error.message : "Unknown error"
1780
+ },
1781
+ "Failed to initialize agent graph using graph endpoint"
1782
+ );
1783
+ throw error;
1784
+ }
1785
+ }
1786
+ /**
1787
+ * Legacy initialization method - kept for backward compatibility
1788
+ * Initialize the graph and all agents in the backend using individual endpoints
1789
+ */
1790
+ async initLegacy() {
1791
+ if (this.initialized) {
1792
+ logger7.info({ graphId: this.graphId }, "Graph already initialized");
1793
+ return;
1794
+ }
1795
+ logger7.info(
1796
+ {
1797
+ graphId: this.graphId,
1798
+ agentCount: this.agents.length
1799
+ },
1800
+ "Initializing agent graph"
1801
+ );
1802
+ try {
1803
+ if (this.contextConfig) {
1804
+ await this.contextConfig.init();
1805
+ logger7.info(
1806
+ {
1807
+ graphId: this.graphId,
1808
+ contextConfigId: this.contextConfig.getId()
1809
+ },
1810
+ "Context configuration initialized for graph"
1811
+ );
1812
+ }
1813
+ const initPromises = this.agents.map(async (agent2) => {
1814
+ try {
1815
+ agent2.config.graphId = this.graphId;
1816
+ await agent2.init();
1817
+ logger7.debug(
1818
+ {
1819
+ agentId: agent2.getId(),
1820
+ graphId: this.graphId
1821
+ },
1822
+ "Agent initialized in graph"
1823
+ );
1824
+ } catch (error) {
1825
+ logger7.error(
1826
+ {
1827
+ agentId: agent2.getId(),
1828
+ graphId: this.graphId,
1829
+ error: error instanceof Error ? error.message : "Unknown error"
1830
+ },
1831
+ "Failed to initialize agent in graph"
1832
+ );
1833
+ throw error;
1834
+ }
1835
+ });
1836
+ await Promise.all(initPromises);
1837
+ await this.saveToDatabase();
1838
+ await this.createExternalAgents();
1839
+ await this.createAgentRelations();
1840
+ await this.saveRelations();
1841
+ this.initialized = true;
1842
+ logger7.info(
1843
+ {
1844
+ graphId: this.graphId,
1845
+ agentCount: this.agents.length
1846
+ },
1847
+ "Agent graph initialized successfully"
1848
+ );
1849
+ } catch (error) {
1850
+ logger7.error(
1851
+ {
1852
+ graphId: this.graphId,
1853
+ error: error instanceof Error ? error.message : "Unknown error"
1854
+ },
1855
+ "Failed to initialize agent graph"
1856
+ );
1857
+ throw error;
1858
+ }
1859
+ }
1860
+ /**
1861
+ * Generate a response using the default agent
1862
+ */
1863
+ async generate(input, options) {
1864
+ await this._init();
1865
+ if (!this.defaultAgent) {
1866
+ throw new Error("No default agent configured for this graph");
1867
+ }
1868
+ logger7.info(
1869
+ {
1870
+ graphId: this.graphId,
1871
+ defaultAgent: this.defaultAgent.getName(),
1872
+ conversationId: options?.conversationId
1873
+ },
1874
+ "Generating response with default agent"
1875
+ );
1876
+ const response = await this.executeWithBackend(input, options);
1877
+ return response;
1878
+ }
1879
+ /**
1880
+ * Stream a response using the default agent
1881
+ */
1882
+ async stream(input, options) {
1883
+ await this._init();
1884
+ if (!this.defaultAgent) {
1885
+ throw new Error("No default agent configured for this graph");
1886
+ }
1887
+ logger7.info(
1888
+ {
1889
+ graphId: this.graphId,
1890
+ defaultAgent: this.defaultAgent.getName(),
1891
+ conversationId: options?.conversationId
1892
+ },
1893
+ "Streaming response with default agent"
1894
+ );
1895
+ const textStream = async function* (graph) {
1896
+ const response = await graph.executeWithBackend(input, options);
1897
+ const words = response.split(" ");
1898
+ for (const word of words) {
1899
+ yield `${word} `;
1900
+ }
1901
+ };
1902
+ return {
1903
+ textStream: textStream(this)
1904
+ };
1905
+ }
1906
+ /**
1907
+ * Alias for stream() method for consistency with naming patterns
1908
+ */
1909
+ async generateStream(input, options) {
1910
+ return await this.stream(input, options);
1911
+ }
1912
+ /**
1913
+ * Run with a specific agent from the graph
1914
+ */
1915
+ async runWith(agentId, input, options) {
1916
+ await this._init();
1917
+ const agent2 = this.getAgent(agentId);
1918
+ if (!agent2) {
1919
+ throw new Error(`Agent '${agentId}' not found in graph`);
1920
+ }
1921
+ if (!this.isInternalAgent(agent2)) {
1922
+ throw new Error(
1923
+ `Agent '${agentId}' is an external agent and cannot be run directly. External agents are only accessible via delegation.`
1924
+ );
1925
+ }
1926
+ logger7.info(
1927
+ {
1928
+ graphId: this.graphId,
1929
+ agentId,
1930
+ conversationId: options?.conversationId
1931
+ },
1932
+ "Running with specific agent"
1933
+ );
1934
+ const response = await this.executeWithBackend(input, options);
1935
+ return {
1936
+ finalOutput: response,
1937
+ agent: agent2,
1938
+ turnCount: 1,
1939
+ usage: { inputTokens: 0, outputTokens: 0 },
1940
+ metadata: {
1941
+ toolCalls: [],
1942
+ transfers: []
1943
+ }
1944
+ };
1945
+ }
1946
+ /**
1947
+ * Get an agent by name (unified method for all agent types)
1948
+ */
1949
+ getAgent(name) {
1950
+ return this.agentMap.get(name);
1951
+ }
1952
+ /**
1953
+ * Add an agent to the graph
1954
+ */
1955
+ addAgent(agent2) {
1956
+ this.agents.push(agent2);
1957
+ this.agentMap.set(agent2.getId(), agent2);
1958
+ if (this.models && this.isInternalAgent(agent2)) {
1959
+ this.propagateModelSettingsToAgent(agent2);
1960
+ }
1961
+ logger7.info(
1962
+ {
1963
+ graphId: this.graphId,
1964
+ agentId: agent2.getId(),
1965
+ agentType: this.isInternalAgent(agent2) ? "internal" : "external"
1966
+ },
1967
+ "Agent added to graph"
1968
+ );
1969
+ }
1970
+ /**
1971
+ * Remove an agent from the graph
1972
+ */
1973
+ removeAgent(id) {
1974
+ const agentToRemove = this.agentMap.get(id);
1975
+ if (agentToRemove) {
1976
+ this.agentMap.delete(agentToRemove.getId());
1977
+ this.agents = this.agents.filter(
1978
+ (agent2) => agent2.getId() !== agentToRemove.getId()
1979
+ );
1980
+ logger7.info(
1981
+ {
1982
+ graphId: this.graphId,
1983
+ agentId: agentToRemove.getId()
1984
+ },
1985
+ "Agent removed from graph"
1986
+ );
1987
+ return true;
1988
+ }
1989
+ return false;
1990
+ }
1991
+ /**
1992
+ * Get all agents in the graph
1993
+ */
1994
+ getAgents() {
1995
+ return this.agents;
1996
+ }
1997
+ /**
1998
+ * Get all agent ids (unified method for all agent types)
1999
+ */
2000
+ getAgentIds() {
2001
+ return Array.from(this.agentMap.keys());
2002
+ }
2003
+ /**
2004
+ * Set the default agent
2005
+ */
2006
+ setDefaultAgent(agent2) {
2007
+ this.defaultAgent = agent2;
2008
+ this.addAgent(agent2);
2009
+ logger7.info(
2010
+ {
2011
+ graphId: this.graphId,
2012
+ defaultAgent: agent2.getId()
2013
+ },
2014
+ "Default agent updated"
2015
+ );
2016
+ }
2017
+ /**
2018
+ * Get the default agent
2019
+ */
2020
+ getDefaultAgent() {
2021
+ return this.defaultAgent;
2022
+ }
2023
+ /**
2024
+ * Get the graph ID
2025
+ */
2026
+ getId() {
2027
+ return this.graphId;
2028
+ }
2029
+ getName() {
2030
+ return this.graphName;
2031
+ }
2032
+ getDescription() {
2033
+ return this.graphDescription;
2034
+ }
2035
+ getTenantId() {
2036
+ return this.tenantId;
2037
+ }
2038
+ /**
2039
+ * Get the graph's model settingsuration
2040
+ */
2041
+ getModels() {
2042
+ return this.models;
2043
+ }
2044
+ /**
2045
+ * Set the graph's model settingsuration
2046
+ */
2047
+ setModels(models) {
2048
+ this.models = models;
2049
+ }
2050
+ /**
2051
+ * Get the graph's prompt configuration
2052
+ */
2053
+ getGraphPrompt() {
2054
+ return this.graphPrompt;
2055
+ }
2056
+ /**
2057
+ * Get the graph's stopWhen configuration
2058
+ */
2059
+ getStopWhen() {
2060
+ return this.stopWhen || { transferCountIs: 10 };
2061
+ }
2062
+ /**
2063
+ * Get the graph's status updates configuration
2064
+ */
2065
+ getStatusUpdateSettings() {
2066
+ return this.statusUpdateSettings;
2067
+ }
2068
+ /**
2069
+ * Get the summarizer model from the graph's model settings
2070
+ */
2071
+ getSummarizerModel() {
2072
+ return this.models?.summarizer;
2073
+ }
2074
+ /**
2075
+ * Get graph statistics
2076
+ */
2077
+ getStats() {
2078
+ return {
2079
+ agentCount: this.agents.length,
2080
+ defaultAgent: this.defaultAgent?.getName() || null,
2081
+ initialized: this.initialized,
2082
+ graphId: this.graphId,
2083
+ tenantId: this.tenantId
2084
+ };
2085
+ }
2086
+ /**
2087
+ * Validate the graph configuration
2088
+ */
2089
+ validate() {
2090
+ const errors = [];
2091
+ if (this.agents.length === 0) {
2092
+ errors.push("Graph must contain at least one agent");
2093
+ }
2094
+ if (!this.defaultAgent) {
2095
+ errors.push("Graph must have a default agent");
2096
+ }
2097
+ const names = /* @__PURE__ */ new Set();
2098
+ for (const agent2 of this.agents) {
2099
+ const name = agent2.getName();
2100
+ if (names.has(name)) {
2101
+ errors.push(`Duplicate agent name: ${name}`);
2102
+ }
2103
+ names.add(name);
2104
+ }
2105
+ for (const agent2 of this.agents) {
2106
+ if (!this.isInternalAgent(agent2)) continue;
2107
+ const transfers = agent2.getTransfers();
2108
+ for (const transferAgent of transfers) {
2109
+ if (!this.agentMap.has(transferAgent.getName())) {
2110
+ errors.push(
2111
+ `Agent '${agent2.getName()}' has transfer to '${transferAgent.getName()}' which is not in the graph`
2112
+ );
2113
+ }
2114
+ }
2115
+ const delegates = agent2.getDelegates();
2116
+ for (const delegateAgent of delegates) {
2117
+ if (!this.agentMap.has(delegateAgent.getName())) {
2118
+ errors.push(
2119
+ `Agent '${agent2.getName()}' has delegation to '${delegateAgent.getName()}' which is not in the graph`
2120
+ );
2121
+ }
2122
+ }
2123
+ }
2124
+ return {
2125
+ valid: errors.length === 0,
2126
+ errors
2127
+ };
2128
+ }
2129
+ // Private helper methods
2130
+ async _init() {
2131
+ if (!this.initialized) {
2132
+ await this.init();
2133
+ }
2134
+ }
2135
+ /**
2136
+ * Type guard to check if an agent is an internal AgentInterface
2137
+ */
2138
+ isInternalAgent(agent2) {
2139
+ return "getTransfers" in agent2 && typeof agent2.getTransfers === "function";
2140
+ }
2141
+ /**
2142
+ * Get project-level model settingsuration defaults
2143
+ */
2144
+ async getProjectModelDefaults() {
2145
+ try {
2146
+ const project = await agentsCore.getProject(this.dbClient)({
2147
+ scopes: { tenantId: this.tenantId, projectId: this.projectId }
2148
+ });
2149
+ return project?.models;
2150
+ } catch (error) {
2151
+ logger7.warn(
2152
+ {
2153
+ tenantId: this.tenantId,
2154
+ projectId: this.projectId,
2155
+ error: error instanceof Error ? error.message : "Unknown error"
2156
+ },
2157
+ "Failed to get project model defaults"
2158
+ );
2159
+ return void 0;
2160
+ }
2161
+ }
2162
+ /**
2163
+ * Get project-level stopWhen configuration defaults
2164
+ */
2165
+ async getProjectStopWhenDefaults() {
2166
+ try {
2167
+ const project = await agentsCore.getProject(this.dbClient)({
2168
+ scopes: { tenantId: this.tenantId, projectId: this.projectId }
2169
+ });
2170
+ return project?.stopWhen;
2171
+ } catch (error) {
2172
+ logger7.warn(
2173
+ {
2174
+ tenantId: this.tenantId,
2175
+ projectId: this.projectId,
2176
+ error: error instanceof Error ? error.message : "Unknown error"
2177
+ },
2178
+ "Failed to get project stopWhen defaults"
2179
+ );
2180
+ return void 0;
2181
+ }
2182
+ }
2183
+ /**
2184
+ * Apply model inheritance hierarchy: Project -> Graph -> Agent
2185
+ */
2186
+ async applyModelInheritance() {
2187
+ const projectModels = await this.getProjectModelDefaults();
2188
+ if (projectModels) {
2189
+ if (!this.models) {
2190
+ this.models = {};
2191
+ }
2192
+ if (!this.models.base && projectModels.base) {
2193
+ this.models.base = projectModels.base;
2194
+ }
2195
+ if (!this.models.structuredOutput && projectModels.structuredOutput) {
2196
+ this.models.structuredOutput = projectModels.structuredOutput;
2197
+ }
2198
+ if (!this.models.summarizer && projectModels.summarizer) {
2199
+ this.models.summarizer = projectModels.summarizer;
2200
+ }
2201
+ }
2202
+ await this.applyStopWhenInheritance();
2203
+ for (const agent2 of this.agents) {
2204
+ if (this.isInternalAgent(agent2)) {
2205
+ this.propagateModelSettingsToAgent(agent2);
2206
+ }
2207
+ }
2208
+ }
2209
+ /**
2210
+ * Apply stopWhen inheritance hierarchy: Project -> Graph -> Agent
2211
+ */
2212
+ async applyStopWhenInheritance() {
2213
+ const projectStopWhen = await this.getProjectStopWhenDefaults();
2214
+ if (!this.stopWhen) {
2215
+ this.stopWhen = {};
2216
+ }
2217
+ if (this.stopWhen.transferCountIs === void 0 && projectStopWhen?.transferCountIs !== void 0) {
2218
+ this.stopWhen.transferCountIs = projectStopWhen.transferCountIs;
2219
+ }
2220
+ if (this.stopWhen.transferCountIs === void 0) {
2221
+ this.stopWhen.transferCountIs = 10;
2222
+ }
2223
+ if (projectStopWhen?.stepCountIs !== void 0) {
2224
+ for (const agent2 of this.agents) {
2225
+ if (this.isInternalAgent(agent2)) {
2226
+ const internalAgent = agent2;
2227
+ if (!internalAgent.config.stopWhen) {
2228
+ internalAgent.config.stopWhen = {};
2229
+ }
2230
+ if (internalAgent.config.stopWhen.stepCountIs === void 0) {
2231
+ internalAgent.config.stopWhen.stepCountIs = projectStopWhen.stepCountIs;
2232
+ }
2233
+ }
2234
+ }
2235
+ }
2236
+ logger7.debug(
2237
+ {
2238
+ graphId: this.graphId,
2239
+ graphStopWhen: this.stopWhen,
2240
+ projectStopWhen
2241
+ },
2242
+ "Applied stopWhen inheritance from project to graph"
2243
+ );
2244
+ }
2245
+ /**
2246
+ * Propagate graph-level model settings to agents (supporting partial inheritance)
2247
+ */
2248
+ propagateModelSettingsToAgent(agent2) {
2249
+ if (this.models) {
2250
+ if (!agent2.config.models) {
2251
+ agent2.config.models = {};
2252
+ }
2253
+ if (!agent2.config.models.base && this.models.base) {
2254
+ agent2.config.models.base = this.models.base;
2255
+ }
2256
+ if (!agent2.config.models.structuredOutput && this.models.structuredOutput) {
2257
+ agent2.config.models.structuredOutput = this.models.structuredOutput;
2258
+ }
2259
+ if (!agent2.config.models.summarizer && this.models.summarizer) {
2260
+ agent2.config.models.summarizer = this.models.summarizer;
2261
+ }
2262
+ }
2263
+ }
2264
+ /**
2265
+ * Immediately propagate graph-level models to all agents during construction
2266
+ */
2267
+ propagateImmediateModelSettings() {
2268
+ for (const agent2 of this.agents) {
2269
+ if (this.isInternalAgent(agent2)) {
2270
+ this.propagateModelSettingsToAgent(agent2);
2271
+ }
2272
+ }
2273
+ }
2274
+ /**
2275
+ * Type guard to check if an agent is an external AgentInterface
2276
+ */
2277
+ isExternalAgent(agent2) {
2278
+ return !this.isInternalAgent(agent2);
2279
+ }
2280
+ /**
2281
+ * Execute agent using the backend system instead of local runner
2282
+ */
2283
+ async executeWithBackend(input, options) {
2284
+ const normalizedMessages = this.normalizeMessages(input);
2285
+ const url = `${this.baseURL}/tenants/${this.tenantId}/graphs/${this.graphId}/v1/chat/completions`;
2286
+ logger7.info({ url }, "Executing with backend");
2287
+ const requestBody = {
2288
+ model: "gpt-4o-mini",
2289
+ messages: normalizedMessages.map((msg) => ({
2290
+ role: msg.role,
2291
+ content: msg.content
2292
+ })),
2293
+ ...options,
2294
+ // Include conversationId for multi-turn support
2295
+ ...options?.conversationId && {
2296
+ conversationId: options.conversationId
2297
+ },
2298
+ // Include context data if available
2299
+ ...options?.customBodyParams && { ...options.customBodyParams },
2300
+ stream: false
2301
+ // Explicitly disable streaming - must come after options to override
2302
+ };
2303
+ try {
2304
+ const response = await fetch(url, {
2305
+ method: "POST",
2306
+ headers: {
2307
+ "Content-Type": "application/json",
2308
+ Accept: "application/json"
2309
+ },
2310
+ body: JSON.stringify(requestBody)
2311
+ });
2312
+ if (!response.ok) {
2313
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2314
+ }
2315
+ const responseText = await response.text();
2316
+ if (responseText.startsWith("data:")) {
2317
+ return this.parseStreamingResponse(responseText);
2318
+ }
2319
+ const data = JSON.parse(responseText);
2320
+ return data.result || data.choices?.[0]?.message?.content || "";
2321
+ } catch (error) {
2322
+ throw new Error(
2323
+ `Graph execution failed: ${error.message || "Unknown error"}`
2324
+ );
2325
+ }
2326
+ }
2327
+ /**
2328
+ * Parse streaming response in SSE format
2329
+ */
2330
+ parseStreamingResponse(text) {
2331
+ const lines = text.split("\n");
2332
+ let content = "";
2333
+ for (const line of lines) {
2334
+ if (line.startsWith("data: ")) {
2335
+ const dataStr = line.slice(6);
2336
+ if (dataStr === "[DONE]") break;
2337
+ try {
2338
+ const data = JSON.parse(dataStr);
2339
+ const delta = data.choices?.[0]?.delta?.content;
2340
+ if (delta) {
2341
+ content += delta;
2342
+ }
2343
+ } catch (_e) {
2344
+ }
2345
+ }
2346
+ }
2347
+ return content;
2348
+ }
2349
+ /**
2350
+ * Normalize input messages to the expected format
2351
+ */
2352
+ normalizeMessages(input) {
2353
+ if (typeof input === "string") {
2354
+ return [{ role: "user", content: input }];
2355
+ }
2356
+ if (Array.isArray(input)) {
2357
+ return input.map(
2358
+ (msg) => typeof msg === "string" ? { role: "user", content: msg } : msg
2359
+ );
2360
+ }
2361
+ return [input];
2362
+ }
2363
+ async saveToDatabase() {
2364
+ try {
2365
+ const getUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/agent-graphs/${this.graphId}`;
2366
+ try {
2367
+ const getResponse = await fetch(getUrl, {
2368
+ method: "GET",
2369
+ headers: {
2370
+ "Content-Type": "application/json"
2371
+ }
2372
+ });
2373
+ if (getResponse.ok) {
2374
+ logger7.info(
2375
+ { graphId: this.graphId },
2376
+ "Graph already exists in backend"
2377
+ );
2378
+ return;
2379
+ }
2380
+ if (getResponse.status !== 404) {
2381
+ throw new Error(
2382
+ `HTTP ${getResponse.status}: ${getResponse.statusText}`
2383
+ );
2384
+ }
2385
+ } catch (error) {
2386
+ if (!error.message.includes("404")) {
2387
+ throw error;
2388
+ }
2389
+ }
2390
+ logger7.info({ graphId: this.graphId }, "Creating graph in backend");
2391
+ const createUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/agent-graphs`;
2392
+ const createResponse = await fetch(createUrl, {
2393
+ method: "POST",
2394
+ headers: {
2395
+ "Content-Type": "application/json"
2396
+ },
2397
+ body: JSON.stringify({
2398
+ id: this.graphId,
2399
+ name: this.graphName,
2400
+ defaultAgentId: this.defaultAgent?.getId() || "",
2401
+ contextConfigId: this.contextConfig?.getId(),
2402
+ models: this.models
2403
+ })
2404
+ });
2405
+ if (!createResponse.ok) {
2406
+ throw new Error(
2407
+ `HTTP ${createResponse.status}: ${createResponse.statusText}`
2408
+ );
2409
+ }
2410
+ const createData = await createResponse.json();
2411
+ this.graphId = createData.data.id;
2412
+ logger7.info({ graph: createData.data }, "Graph created in backend");
2413
+ } catch (error) {
2414
+ throw new Error(
2415
+ `Failed to save graph to database: ${error instanceof Error ? error.message : "Unknown error"}`
2416
+ );
2417
+ }
2418
+ }
2419
+ async saveRelations() {
2420
+ if (this.defaultAgent) {
2421
+ try {
2422
+ const updateUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/agent-graphs/${this.graphId}`;
2423
+ const updateResponse = await fetch(updateUrl, {
2424
+ method: "PUT",
2425
+ headers: {
2426
+ "Content-Type": "application/json"
2427
+ },
2428
+ body: JSON.stringify({
2429
+ id: this.graphId,
2430
+ defaultAgentId: this.defaultAgent.getId(),
2431
+ contextConfigId: this.contextConfig?.getId()
2432
+ })
2433
+ });
2434
+ if (!updateResponse.ok) {
2435
+ throw new Error(
2436
+ `HTTP ${updateResponse.status}: ${updateResponse.statusText}`
2437
+ );
2438
+ }
2439
+ logger7.debug(
2440
+ {
2441
+ graphId: this.graphId,
2442
+ defaultAgent: this.defaultAgent.getName()
2443
+ },
2444
+ "Graph relationships configured"
2445
+ );
2446
+ } catch (error) {
2447
+ logger7.error(
2448
+ {
2449
+ graphId: this.graphId,
2450
+ error: error instanceof Error ? error.message : "Unknown error"
2451
+ },
2452
+ "Failed to update graph relationships"
2453
+ );
2454
+ throw error;
2455
+ }
2456
+ }
2457
+ }
2458
+ async createAgentRelations() {
2459
+ const allRelationPromises = [];
2460
+ for (const agent2 of this.agents) {
2461
+ if (this.isInternalAgent(agent2)) {
2462
+ const transfers = agent2.getTransfers();
2463
+ for (const transferAgent of transfers) {
2464
+ allRelationPromises.push(
2465
+ this.createInternalAgentRelation(agent2, transferAgent, "transfer")
2466
+ );
2467
+ }
2468
+ const delegates = agent2.getDelegates();
2469
+ for (const delegate of delegates) {
2470
+ if (delegate instanceof ExternalAgent) {
2471
+ allRelationPromises.push(
2472
+ this.createExternalAgentRelation(agent2, delegate, "delegate")
2473
+ );
2474
+ } else {
2475
+ allRelationPromises.push(
2476
+ this.createInternalAgentRelation(
2477
+ agent2,
2478
+ delegate,
2479
+ "delegate"
2480
+ )
2481
+ );
2482
+ }
2483
+ }
2484
+ }
2485
+ }
2486
+ const results = await Promise.allSettled(allRelationPromises);
2487
+ const errors = [];
2488
+ let successCount = 0;
2489
+ for (const result of results) {
2490
+ if (result.status === "fulfilled") {
2491
+ successCount++;
2492
+ } else {
2493
+ errors.push(result.reason);
2494
+ logger7.error(
2495
+ {
2496
+ error: result.reason instanceof Error ? result.reason.message : "Unknown error",
2497
+ graphId: this.graphId
2498
+ },
2499
+ "Failed to create agent relation"
2500
+ );
2501
+ }
2502
+ }
2503
+ logger7.info(
2504
+ {
2505
+ graphId: this.graphId,
2506
+ totalRelations: allRelationPromises.length,
2507
+ successCount,
2508
+ errorCount: errors.length
2509
+ },
2510
+ "Completed agent relation creation batch"
2511
+ );
2512
+ if (errors.length > 0 && successCount === 0) {
2513
+ throw new Error(`All ${errors.length} agent relation creations failed`);
2514
+ }
2515
+ }
2516
+ async createInternalAgentRelation(sourceAgent, targetAgent, relationType) {
2517
+ try {
2518
+ const response = await fetch(
2519
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agent-relations`,
2520
+ {
2521
+ method: "POST",
2522
+ headers: {
2523
+ "Content-Type": "application/json"
2524
+ },
2525
+ body: JSON.stringify({
2526
+ graphId: this.graphId,
2527
+ sourceAgentId: sourceAgent.getId(),
2528
+ targetAgentId: targetAgent.getId(),
2529
+ relationType
2530
+ })
2531
+ }
2532
+ );
2533
+ if (!response.ok) {
2534
+ const errorText = await response.text().catch(() => "Unknown error");
2535
+ if (response.status === 422 && errorText.includes("already exists")) {
2536
+ logger7.info(
2537
+ {
2538
+ sourceAgentId: sourceAgent.getId(),
2539
+ targetAgentId: targetAgent.getId(),
2540
+ graphId: this.graphId,
2541
+ relationType
2542
+ },
2543
+ `${relationType} relation already exists, skipping creation`
2544
+ );
2545
+ return;
2546
+ }
2547
+ throw new Error(
2548
+ `Failed to create agent relation: ${response.status} - ${errorText}`
2549
+ );
2550
+ }
2551
+ logger7.info(
2552
+ {
2553
+ sourceAgentId: sourceAgent.getId(),
2554
+ targetAgentId: targetAgent.getId(),
2555
+ graphId: this.graphId,
2556
+ relationType
2557
+ },
2558
+ `${relationType} relation created successfully`
2559
+ );
2560
+ } catch (error) {
2561
+ logger7.error(
2562
+ {
2563
+ sourceAgentId: sourceAgent.getId(),
2564
+ targetAgentId: targetAgent.getId(),
2565
+ graphId: this.graphId,
2566
+ relationType,
2567
+ error: error instanceof Error ? error.message : "Unknown error"
2568
+ },
2569
+ `Failed to create ${relationType} relation`
2570
+ );
2571
+ throw error;
2572
+ }
2573
+ }
2574
+ // enableComponentMode removed – feature deprecated
2575
+ async createExternalAgentRelation(sourceAgent, externalAgent2, relationType) {
2576
+ try {
2577
+ const response = await fetch(
2578
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agent-relations`,
2579
+ {
2580
+ method: "POST",
2581
+ headers: {
2582
+ "Content-Type": "application/json"
2583
+ },
2584
+ body: JSON.stringify({
2585
+ graphId: this.graphId,
2586
+ sourceAgentId: sourceAgent.getId(),
2587
+ externalAgentId: externalAgent2.getId(),
2588
+ relationType
2589
+ })
2590
+ }
2591
+ );
2592
+ if (!response.ok) {
2593
+ const errorText = await response.text().catch(() => "Unknown error");
2594
+ if (response.status === 422 && errorText.includes("already exists")) {
2595
+ logger7.info(
2596
+ {
2597
+ sourceAgentId: sourceAgent.getId(),
2598
+ externalAgentId: externalAgent2.getId(),
2599
+ graphId: this.graphId,
2600
+ relationType
2601
+ },
2602
+ `${relationType} relation already exists, skipping creation`
2603
+ );
2604
+ return;
2605
+ }
2606
+ throw new Error(
2607
+ `Failed to create external agent relation: ${response.status} - ${errorText}`
2608
+ );
2609
+ }
2610
+ logger7.info(
2611
+ {
2612
+ sourceAgentId: sourceAgent.getId(),
2613
+ externalAgentId: externalAgent2.getId(),
2614
+ graphId: this.graphId,
2615
+ relationType
2616
+ },
2617
+ `${relationType} relation created successfully`
2618
+ );
2619
+ } catch (error) {
2620
+ logger7.error(
2621
+ {
2622
+ sourceAgentId: sourceAgent.getId(),
2623
+ externalAgentId: externalAgent2.getId(),
2624
+ graphId: this.graphId,
2625
+ relationType,
2626
+ error: error instanceof Error ? error.message : "Unknown error"
2627
+ },
2628
+ `Failed to create ${relationType} relation`
2629
+ );
2630
+ throw error;
2631
+ }
2632
+ }
2633
+ /**
2634
+ * Create external agents in the database
2635
+ */
2636
+ async createExternalAgents() {
2637
+ const externalAgents2 = this.agents.filter(
2638
+ (agent2) => this.isExternalAgent(agent2)
2639
+ );
2640
+ logger7.info(
2641
+ {
2642
+ graphId: this.graphId,
2643
+ externalAgentCount: externalAgents2.length
2644
+ },
2645
+ "Creating external agents in database"
2646
+ );
2647
+ const initPromises = externalAgents2.map(async (externalAgent2) => {
2648
+ try {
2649
+ await externalAgent2.init();
2650
+ logger7.debug(
2651
+ {
2652
+ externalAgentId: externalAgent2.getId(),
2653
+ graphId: this.graphId
2654
+ },
2655
+ "External agent created in database"
2656
+ );
2657
+ } catch (error) {
2658
+ logger7.error(
2659
+ {
2660
+ externalAgentId: externalAgent2.getId(),
2661
+ graphId: this.graphId,
2662
+ error: error instanceof Error ? error.message : "Unknown error"
2663
+ },
2664
+ "Failed to create external agent in database"
2665
+ );
2666
+ throw error;
2667
+ }
2668
+ });
2669
+ try {
2670
+ await Promise.all(initPromises);
2671
+ logger7.info(
2672
+ {
2673
+ graphId: this.graphId,
2674
+ externalAgentCount: externalAgents2.length
2675
+ },
2676
+ "All external agents created successfully"
2677
+ );
2678
+ } catch (error) {
2679
+ logger7.error(
2680
+ {
2681
+ graphId: this.graphId,
2682
+ error: error instanceof Error ? error.message : "Unknown error"
2683
+ },
2684
+ "Failed to create some external agents"
2685
+ );
2686
+ throw error;
2687
+ }
2688
+ }
2689
+ };
2690
+ function agentGraph(config) {
2691
+ return new AgentGraph(config);
2692
+ }
2693
+ async function generateGraph(configPath) {
2694
+ logger7.info({ configPath }, "Loading graph configuration");
2695
+ try {
2696
+ const config = await import(configPath);
2697
+ const graphConfig = config.default || config;
2698
+ const graph = agentGraph(graphConfig);
2699
+ await graph.init();
2700
+ logger7.info(
2701
+ {
2702
+ configPath,
2703
+ graphId: graph.getStats().graphId,
2704
+ agentCount: graph.getStats().agentCount
2705
+ },
2706
+ "Graph generated successfully"
2707
+ );
2708
+ return graph;
2709
+ } catch (error) {
2710
+ logger7.error(
2711
+ {
2712
+ configPath,
2713
+ error: error instanceof Error ? error.message : "Unknown error"
2714
+ },
2715
+ "Failed to generate graph from configuration"
2716
+ );
2717
+ throw error;
2718
+ }
2719
+ }
2720
+ zod.z.object({
2721
+ model: zod.z.string().optional(),
2722
+ providerOptions: zod.z.record(zod.z.string(), zod.z.record(zod.z.string(), zod.z.unknown())).optional()
2723
+ });
2724
+ var AgentError = class extends Error {
2725
+ constructor(message, code, details) {
2726
+ super(message);
2727
+ this.code = code;
2728
+ this.details = details;
2729
+ this.name = "AgentError";
2730
+ }
2731
+ };
2732
+ var MaxTurnsExceededError = class extends AgentError {
2733
+ constructor(maxTurns) {
2734
+ super(`Maximum turns (${maxTurns}) exceeded`);
2735
+ this.code = "MAX_TURNS_EXCEEDED";
2736
+ }
2737
+ };
2738
+
2739
+ // src/runner.ts
2740
+ var logger8 = agentsCore.getLogger("runner");
2741
+ var Runner = class _Runner {
2742
+ /**
2743
+ * Run a graph until completion, handling transfers and tool calls
2744
+ * Similar to OpenAI's Runner.run() pattern
2745
+ * NOTE: This now requires a graph instead of an agent
2746
+ */
2747
+ static async run(graph, messages, options) {
2748
+ const maxTurns = options?.maxTurns || 10;
2749
+ let turnCount = 0;
2750
+ const messageHistory = _Runner.normalizeToMessageHistory(messages);
2751
+ const allToolCalls = [];
2752
+ logger8.info(
2753
+ {
2754
+ graphId: graph.getId(),
2755
+ defaultAgent: graph.getDefaultAgent()?.getName(),
2756
+ maxTurns,
2757
+ initialMessageCount: messageHistory.length
2758
+ },
2759
+ "Starting graph run"
2760
+ );
2761
+ while (turnCount < maxTurns) {
2762
+ logger8.debug(
2763
+ {
2764
+ graphId: graph.getId(),
2765
+ turnCount,
2766
+ messageHistoryLength: messageHistory.length
2767
+ },
2768
+ "Starting turn"
2769
+ );
2770
+ const response = await graph.generate(messageHistory, options);
2771
+ turnCount++;
2772
+ logger8.info(
2773
+ {
2774
+ graphId: graph.getId(),
2775
+ turnCount,
2776
+ responseLength: response.length
2777
+ },
2778
+ "Graph generation completed"
2779
+ );
2780
+ return {
2781
+ finalOutput: response,
2782
+ agent: graph.getDefaultAgent() || {},
2783
+ turnCount,
2784
+ usage: { inputTokens: 0, outputTokens: 0 },
2785
+ metadata: {
2786
+ toolCalls: allToolCalls,
2787
+ transfers: []
2788
+ // Graph handles transfers internally
2789
+ }
2790
+ };
2791
+ }
2792
+ logger8.error(
2793
+ {
2794
+ graphId: graph.getId(),
2795
+ maxTurns,
2796
+ finalTurnCount: turnCount
2797
+ },
2798
+ "Maximum turns exceeded"
2799
+ );
2800
+ throw new MaxTurnsExceededError(maxTurns);
2801
+ }
2802
+ /**
2803
+ * Stream a graph's response
2804
+ */
2805
+ static async stream(graph, messages, options) {
2806
+ logger8.info(
2807
+ {
2808
+ graphId: graph.getId(),
2809
+ defaultAgent: graph.getDefaultAgent()?.getName()
2810
+ },
2811
+ "Starting graph stream"
2812
+ );
2813
+ return graph.stream(messages, options);
2814
+ }
2815
+ /**
2816
+ * Execute multiple graphs in parallel and return the first successful result
2817
+ */
2818
+ static async raceGraphs(graphs, messages, options) {
2819
+ if (graphs.length === 0) {
2820
+ throw new Error("No graphs provided for race");
2821
+ }
2822
+ logger8.info(
2823
+ {
2824
+ graphCount: graphs.length,
2825
+ graphIds: graphs.map((g) => g.getId())
2826
+ },
2827
+ "Starting graph race"
2828
+ );
2829
+ const promises = graphs.map(async (graph, index) => {
2830
+ try {
2831
+ const result2 = await _Runner.run(graph, messages, options);
2832
+ return { ...result2, raceIndex: index };
2833
+ } catch (error) {
2834
+ logger8.error(
2835
+ {
2836
+ graphId: graph.getId(),
2837
+ error: error instanceof Error ? error.message : "Unknown error"
2838
+ },
2839
+ "Graph failed in race"
2840
+ );
2841
+ throw error;
2842
+ }
2843
+ });
2844
+ const result = await Promise.race(promises);
2845
+ logger8.info(
2846
+ {
2847
+ winningGraphId: result.graphId || "unknown",
2848
+ raceIndex: result.raceIndex
2849
+ },
2850
+ "Graph race completed"
2851
+ );
2852
+ return result;
2853
+ }
2854
+ // Private helper methods
2855
+ static normalizeToMessageHistory(messages) {
2856
+ if (typeof messages === "string") {
2857
+ return [{ role: "user", content: messages }];
2858
+ }
2859
+ if (Array.isArray(messages)) {
2860
+ return messages.map(
2861
+ (msg) => typeof msg === "string" ? { role: "user", content: msg } : msg
2862
+ );
2863
+ }
2864
+ return [messages];
2865
+ }
2866
+ /**
2867
+ * Validate graph configuration before running
2868
+ */
2869
+ static validateGraph(graph) {
2870
+ const errors = [];
2871
+ if (!graph.getId()) {
2872
+ errors.push("Graph ID is required");
2873
+ }
2874
+ const defaultAgent = graph.getDefaultAgent();
2875
+ if (!defaultAgent) {
2876
+ errors.push("Default agent is required");
2877
+ } else {
2878
+ if (!defaultAgent.getName()) {
2879
+ errors.push("Default agent name is required");
2880
+ }
2881
+ if (!defaultAgent.getInstructions()) {
2882
+ errors.push("Default agent instructions are required");
2883
+ }
2884
+ }
2885
+ const agents = graph.getAgents();
2886
+ if (agents.length === 0) {
2887
+ errors.push("Graph must contain at least one agent");
2888
+ }
2889
+ for (const agent2 of agents) {
2890
+ if (!agent2.getName()) {
2891
+ errors.push(`Agent missing name`);
2892
+ }
2893
+ }
2894
+ return {
2895
+ valid: errors.length === 0,
2896
+ errors
2897
+ };
2898
+ }
2899
+ /**
2900
+ * Get execution statistics for a graph
2901
+ */
2902
+ static async getExecutionStats(graph, messages, options) {
2903
+ const agents = graph.getAgents();
2904
+ const defaultAgent = graph.getDefaultAgent();
2905
+ const messageCount = Array.isArray(messages) ? messages.length : 1;
2906
+ return {
2907
+ estimatedTurns: Math.min(
2908
+ Math.max(messageCount, 1),
2909
+ options?.maxTurns || 10
2910
+ ),
2911
+ estimatedTokens: messageCount * 100,
2912
+ // Rough estimate
2913
+ agentCount: agents.length,
2914
+ defaultAgent: defaultAgent?.getName()
2915
+ };
2916
+ }
2917
+ };
2918
+ var run = Runner.run.bind(Runner);
2919
+ var stream = Runner.stream.bind(Runner);
2920
+ var raceGraphs = Runner.raceGraphs.bind(Runner);
2921
+
2922
+ // src/index.ts
2923
+ init_tool();
2924
+
2925
+ exports.Agent = Agent;
2926
+ exports.AgentGraph = AgentGraph;
2927
+ exports.ArtifactComponent = ArtifactComponent;
2928
+ exports.DataComponent = DataComponent;
2929
+ exports.ExternalAgent = ExternalAgent;
2930
+ exports.Runner = Runner;
2931
+ exports.agent = agent;
2932
+ exports.agentGraph = agentGraph;
2933
+ exports.artifactComponent = artifactComponent;
2934
+ exports.createEnvironmentSettings = createEnvironmentSettings;
2935
+ exports.credential = credential;
2936
+ exports.dataComponent = dataComponent;
2937
+ exports.externalAgent = externalAgent;
2938
+ exports.externalAgents = externalAgents;
2939
+ exports.generateGraph = generateGraph;
2940
+ exports.getAllEnvironmentSettingKeys = getAllEnvironmentSettingKeys;
2941
+ exports.mcpServer = mcpServer;
2942
+ exports.mcpTool = mcpTool;
2943
+ exports.raceGraphs = raceGraphs;
2944
+ exports.registerEnvironmentSettings = registerEnvironmentSettings;
2945
+ exports.run = run;
2946
+ exports.stream = stream;
2947
+ exports.tool = tool;
2948
+ exports.transfer = transfer;