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

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 +2899 -0
  3. package/dist/index.d.cts +855 -0
  4. package/dist/index.d.ts +855 -11
  5. package/dist/index.js +2712 -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,2899 @@
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
+ function createEnvironmentSettings(environments) {
1093
+ return {
1094
+ getEnvironmentSetting: async (key) => {
1095
+ const currentEnv = process.env.INKEEP_ENV || "development";
1096
+ const env = environments[currentEnv];
1097
+ if (!env) {
1098
+ throw new Error(
1099
+ `Environment '${currentEnv}' not found. Available: ${Object.keys(environments).join(", ")}`
1100
+ );
1101
+ }
1102
+ const credential2 = env.credentials?.[key];
1103
+ if (!credential2) {
1104
+ throw new Error(
1105
+ `Credential '${String(key)}' not found in environment '${currentEnv}'`
1106
+ );
1107
+ }
1108
+ return credential2;
1109
+ }
1110
+ };
1111
+ }
1112
+ function registerEnvironmentSettings(config) {
1113
+ return config;
1114
+ }
1115
+ var logger5 = agentsCore.getLogger("external-agent-builder");
1116
+ var ExternalAgent = class {
1117
+ constructor(config) {
1118
+ __publicField(this, "config");
1119
+ __publicField(this, "type", "external");
1120
+ __publicField(this, "initialized", false);
1121
+ __publicField(this, "tenantId");
1122
+ __publicField(this, "baseURL");
1123
+ this.config = { ...config, type: "external" };
1124
+ this.tenantId = config.tenantId || "default";
1125
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
1126
+ logger5.debug(
1127
+ {
1128
+ externalAgentName: this.config.name,
1129
+ baseUrl: this.config.baseUrl,
1130
+ tenantId: this.config.tenantId
1131
+ },
1132
+ "External Agent constructor initialized"
1133
+ );
1134
+ }
1135
+ /**
1136
+ * Initialize the external agent by upserting it in the database
1137
+ */
1138
+ async init() {
1139
+ if (this.initialized) return;
1140
+ try {
1141
+ await this.upsertExternalAgent();
1142
+ logger5.info(
1143
+ {
1144
+ externalAgentId: this.getId()
1145
+ },
1146
+ "External agent initialized successfully"
1147
+ );
1148
+ this.initialized = true;
1149
+ } catch (error) {
1150
+ logger5.error(
1151
+ {
1152
+ externalAgentId: this.getId(),
1153
+ error: error instanceof Error ? error.message : "Unknown error"
1154
+ },
1155
+ "Failed to initialize external agent"
1156
+ );
1157
+ throw error;
1158
+ }
1159
+ }
1160
+ // Compute ID from name using a simple slug transformation
1161
+ getId() {
1162
+ return this.config.id;
1163
+ }
1164
+ // Private method to upsert external agent (create or update)
1165
+ async upsertExternalAgent() {
1166
+ const externalAgentData = {
1167
+ id: this.getId(),
1168
+ name: this.config.name,
1169
+ description: this.config.description,
1170
+ baseUrl: this.config.baseUrl,
1171
+ credentialReferenceId: this.config.credentialReference?.id || void 0,
1172
+ headers: this.config.headers || void 0
1173
+ };
1174
+ const updateResponse = await fetch(
1175
+ `${this.baseURL}/tenants/${this.tenantId}/crud/external-agents/${this.getId()}`,
1176
+ {
1177
+ method: "PUT",
1178
+ headers: {
1179
+ "Content-Type": "application/json"
1180
+ },
1181
+ body: JSON.stringify(externalAgentData)
1182
+ }
1183
+ );
1184
+ if (updateResponse.ok) {
1185
+ logger5.info(
1186
+ {
1187
+ externalAgentId: this.getId()
1188
+ },
1189
+ "External agent updated successfully"
1190
+ );
1191
+ return;
1192
+ }
1193
+ if (updateResponse.status === 404) {
1194
+ logger5.info(
1195
+ {
1196
+ externalAgentId: this.getId()
1197
+ },
1198
+ "External agent not found, creating new external agent"
1199
+ );
1200
+ const createResponse = await fetch(
1201
+ `${this.baseURL}/tenants/${this.tenantId}/crud/external-agents`,
1202
+ {
1203
+ method: "POST",
1204
+ headers: {
1205
+ "Content-Type": "application/json"
1206
+ },
1207
+ body: JSON.stringify(externalAgentData)
1208
+ }
1209
+ );
1210
+ if (!createResponse.ok) {
1211
+ const errorText2 = await createResponse.text().catch(() => "Unknown error");
1212
+ throw new Error(
1213
+ `Failed to create external agent: ${createResponse.status} ${createResponse.statusText} - ${errorText2}`
1214
+ );
1215
+ }
1216
+ logger5.info(
1217
+ {
1218
+ externalAgentId: this.getId()
1219
+ },
1220
+ "External agent created successfully"
1221
+ );
1222
+ return;
1223
+ }
1224
+ const errorText = await updateResponse.text().catch(() => "Unknown error");
1225
+ throw new Error(
1226
+ `Failed to update external agent: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`
1227
+ );
1228
+ }
1229
+ /**
1230
+ * Get the external agent configuration
1231
+ */
1232
+ getConfig() {
1233
+ return { ...this.config };
1234
+ }
1235
+ /**
1236
+ * Get the external agent name
1237
+ */
1238
+ getName() {
1239
+ return this.config.name;
1240
+ }
1241
+ /**
1242
+ * Get the external agent base URL
1243
+ */
1244
+ getBaseUrl() {
1245
+ return this.config.baseUrl;
1246
+ }
1247
+ /**
1248
+ * Get the tenant ID
1249
+ */
1250
+ getTenantId() {
1251
+ return this.tenantId;
1252
+ }
1253
+ getDescription() {
1254
+ return this.config.description || "";
1255
+ }
1256
+ getCredentialReferenceId() {
1257
+ return this.config.credentialReference?.id || void 0;
1258
+ }
1259
+ getHeaders() {
1260
+ return this.config.headers;
1261
+ }
1262
+ };
1263
+ function externalAgent(config) {
1264
+ return new ExternalAgent(config);
1265
+ }
1266
+ function externalAgents(configs) {
1267
+ const builders = {};
1268
+ for (const [name, config] of Object.entries(configs)) {
1269
+ builders[name] = externalAgent(config);
1270
+ }
1271
+ return builders;
1272
+ }
1273
+ var logger6 = agentsCore.getLogger("graphFullClient");
1274
+ async function updateFullGraphViaAPI(tenantId, projectId, apiUrl, graphId, graphData) {
1275
+ logger6.info(
1276
+ {
1277
+ tenantId,
1278
+ projectId,
1279
+ graphId,
1280
+ apiUrl
1281
+ },
1282
+ "Updating full graph via API"
1283
+ );
1284
+ const url = `${apiUrl}/tenants/${tenantId}/crud/projects/${projectId}/graph/${graphId}`;
1285
+ const response = await fetch(url, {
1286
+ method: "PUT",
1287
+ headers: {
1288
+ "Content-Type": "application/json"
1289
+ },
1290
+ body: JSON.stringify(graphData)
1291
+ });
1292
+ if (!response.ok) {
1293
+ const errorText = await response.text();
1294
+ let errorMessage = `Failed to update graph: ${response.status} ${response.statusText}`;
1295
+ try {
1296
+ const errorJson = JSON.parse(errorText);
1297
+ if (errorJson.error) {
1298
+ errorMessage = errorJson.error;
1299
+ }
1300
+ } catch {
1301
+ if (errorText) {
1302
+ errorMessage = errorText;
1303
+ }
1304
+ }
1305
+ logger6.error(
1306
+ {
1307
+ status: response.status,
1308
+ error: errorMessage
1309
+ },
1310
+ "Failed to update graph via API"
1311
+ );
1312
+ throw new Error(errorMessage);
1313
+ }
1314
+ const result = await response.json();
1315
+ logger6.info(
1316
+ {
1317
+ graphId
1318
+ },
1319
+ "Successfully updated graph via API"
1320
+ );
1321
+ return result.data;
1322
+ }
1323
+
1324
+ // src/graph.ts
1325
+ var logger7 = agentsCore.getLogger("graph");
1326
+ function resolveGetter2(value) {
1327
+ if (typeof value === "function") {
1328
+ return value();
1329
+ }
1330
+ return value;
1331
+ }
1332
+ var AgentGraph = class {
1333
+ constructor(config) {
1334
+ __publicField(this, "agents", []);
1335
+ __publicField(this, "agentMap", /* @__PURE__ */ new Map());
1336
+ __publicField(this, "defaultAgent");
1337
+ __publicField(this, "baseURL");
1338
+ __publicField(this, "tenantId");
1339
+ __publicField(this, "projectId");
1340
+ __publicField(this, "graphId");
1341
+ __publicField(this, "graphName");
1342
+ __publicField(this, "graphDescription");
1343
+ __publicField(this, "initialized", false);
1344
+ __publicField(this, "contextConfig");
1345
+ // ContextConfigBuilder
1346
+ __publicField(this, "credentials");
1347
+ __publicField(this, "models");
1348
+ __publicField(this, "statusUpdateSettings");
1349
+ __publicField(this, "graphPrompt");
1350
+ __publicField(this, "stopWhen");
1351
+ __publicField(this, "dbClient");
1352
+ this.defaultAgent = config.defaultAgent;
1353
+ this.tenantId = config.tenantId || "default";
1354
+ this.projectId = "default";
1355
+ this.graphId = config.id;
1356
+ this.graphName = config.name || this.graphId;
1357
+ this.graphDescription = config.description;
1358
+ this.baseURL = process.env.INKEEP_API_URL || "http://localhost:3002";
1359
+ this.contextConfig = config.contextConfig;
1360
+ this.credentials = resolveGetter2(config.credentials);
1361
+ this.models = config.models;
1362
+ const dbUrl = process.env.ENVIRONMENT === "test" ? ":memory:" : process.env.DB_FILE_NAME || process.env.DATABASE_URL || ":memory:";
1363
+ this.dbClient = agentsCore.createDatabaseClient({
1364
+ url: dbUrl
1365
+ });
1366
+ this.statusUpdateSettings = config.statusUpdates;
1367
+ this.graphPrompt = config.graphPrompt;
1368
+ this.stopWhen = config.stopWhen ? {
1369
+ transferCountIs: config.stopWhen.transferCountIs
1370
+ } : void 0;
1371
+ this.agents = resolveGetter2(config.agents) || [];
1372
+ this.agentMap = new Map(this.agents.map((agent2) => [agent2.getId(), agent2]));
1373
+ if (this.defaultAgent) {
1374
+ this.agents.push(this.defaultAgent);
1375
+ this.agentMap.set(this.defaultAgent.getId(), this.defaultAgent);
1376
+ }
1377
+ if (this.models) {
1378
+ this.propagateImmediateModelSettings();
1379
+ }
1380
+ logger7.info(
1381
+ {
1382
+ graphId: this.graphId,
1383
+ tenantId: this.tenantId,
1384
+ agentCount: this.agents.length,
1385
+ defaultAgent: this.defaultAgent?.getName()
1386
+ },
1387
+ "AgentGraph created"
1388
+ );
1389
+ }
1390
+ /**
1391
+ * Set or update the configuration (tenantId, projectId and apiUrl)
1392
+ * This is used by the CLI to inject configuration from inkeep.config.ts
1393
+ */
1394
+ setConfig(tenantId, projectId, apiUrl) {
1395
+ if (this.initialized) {
1396
+ throw new Error("Cannot set config after graph has been initialized");
1397
+ }
1398
+ this.tenantId = tenantId;
1399
+ this.projectId = projectId;
1400
+ this.baseURL = apiUrl;
1401
+ for (const agent2 of this.agents) {
1402
+ if (this.isInternalAgent(agent2)) {
1403
+ const internalAgent = agent2;
1404
+ if (!internalAgent.config.tenantId) {
1405
+ internalAgent.config.tenantId = tenantId;
1406
+ }
1407
+ const tools = internalAgent.getTools();
1408
+ for (const [_, toolInstance] of Object.entries(tools)) {
1409
+ if (toolInstance && typeof toolInstance === "object" && toolInstance.config) {
1410
+ if (!toolInstance.config.tenantId) {
1411
+ toolInstance.config.tenantId = tenantId;
1412
+ }
1413
+ if ("baseURL" in toolInstance && !toolInstance.baseURL) {
1414
+ toolInstance.baseURL = apiUrl;
1415
+ }
1416
+ }
1417
+ }
1418
+ }
1419
+ }
1420
+ if (this.contextConfig && !this.contextConfig.tenantId) {
1421
+ this.contextConfig.tenantId = tenantId;
1422
+ }
1423
+ logger7.info(
1424
+ {
1425
+ graphId: this.graphId,
1426
+ tenantId: this.tenantId,
1427
+ projectId: this.projectId,
1428
+ apiUrl: this.baseURL
1429
+ },
1430
+ "Graph configuration updated"
1431
+ );
1432
+ }
1433
+ /**
1434
+ * Convert the AgentGraph to FullGraphDefinition format for the new graph endpoint
1435
+ */
1436
+ async toFullGraphDefinition() {
1437
+ const agentsObject = {};
1438
+ for (const agent2 of this.agents) {
1439
+ if (this.isInternalAgent(agent2)) {
1440
+ const internalAgent = agent2;
1441
+ const transfers = internalAgent.getTransfers();
1442
+ const delegates = internalAgent.getDelegates();
1443
+ const tools = [];
1444
+ const agentTools = internalAgent.getTools();
1445
+ for (const [toolName, toolInstance] of Object.entries(agentTools)) {
1446
+ if (toolInstance && typeof toolInstance === "object") {
1447
+ const toolId = toolInstance.getId?.() || toolInstance.id || toolName;
1448
+ tools.push(toolId);
1449
+ }
1450
+ }
1451
+ const dataComponents = [];
1452
+ const agentDataComponents = internalAgent.getDataComponents();
1453
+ if (agentDataComponents) {
1454
+ for (const dataComponent2 of agentDataComponents) {
1455
+ const dataComponentId = dataComponent2.id || dataComponent2.name.toLowerCase().replace(/\s+/g, "-");
1456
+ dataComponents.push(dataComponentId);
1457
+ }
1458
+ }
1459
+ const artifactComponents = [];
1460
+ const agentArtifactComponents = internalAgent.getArtifactComponents();
1461
+ if (agentArtifactComponents) {
1462
+ for (const artifactComponent2 of agentArtifactComponents) {
1463
+ const artifactComponentId = artifactComponent2.id || artifactComponent2.name.toLowerCase().replace(/\s+/g, "-");
1464
+ artifactComponents.push(artifactComponentId);
1465
+ }
1466
+ }
1467
+ agentsObject[internalAgent.getId()] = {
1468
+ id: internalAgent.getId(),
1469
+ name: internalAgent.getName(),
1470
+ description: internalAgent.config.description || `Agent ${internalAgent.getName()}`,
1471
+ prompt: internalAgent.getInstructions(),
1472
+ models: internalAgent.config.models,
1473
+ canTransferTo: transfers.map((h) => h.getId()),
1474
+ canDelegateTo: delegates.map((d) => d.getId()),
1475
+ tools,
1476
+ dataComponents: dataComponents.length > 0 ? dataComponents : void 0,
1477
+ artifactComponents: artifactComponents.length > 0 ? artifactComponents : void 0,
1478
+ type: "internal"
1479
+ };
1480
+ } else {
1481
+ const externalAgent2 = agent2;
1482
+ agentsObject[externalAgent2.getId()] = {
1483
+ id: externalAgent2.getId(),
1484
+ name: externalAgent2.getName(),
1485
+ description: externalAgent2.getDescription(),
1486
+ baseUrl: externalAgent2.getBaseUrl(),
1487
+ credentialReferenceId: externalAgent2.getCredentialReferenceId(),
1488
+ headers: externalAgent2.getHeaders(),
1489
+ tools: [],
1490
+ // External agents don't have tools in this context
1491
+ type: "external"
1492
+ };
1493
+ }
1494
+ }
1495
+ const toolsObject = {};
1496
+ for (const agent2 of this.agents) {
1497
+ if (!agent2.getTransfers) {
1498
+ continue;
1499
+ }
1500
+ const internalAgent = agent2;
1501
+ const agentTools = internalAgent.getTools();
1502
+ for (const [toolName, toolInstance] of Object.entries(agentTools)) {
1503
+ if (toolInstance && typeof toolInstance === "object") {
1504
+ const toolId = toolInstance.getId?.() || toolInstance.id || toolName;
1505
+ if (!toolsObject[toolId]) {
1506
+ let toolConfig;
1507
+ if (toolInstance.config?.serverUrl) {
1508
+ toolConfig = {
1509
+ type: "mcp",
1510
+ mcp: {
1511
+ server: {
1512
+ url: toolInstance.config.serverUrl
1513
+ }
1514
+ }
1515
+ };
1516
+ } else if (toolInstance.config?.type === "mcp") {
1517
+ toolConfig = toolInstance.config;
1518
+ } else {
1519
+ toolConfig = {
1520
+ type: "function",
1521
+ parameters: toolInstance.parameters || {}
1522
+ };
1523
+ }
1524
+ const toolData = {
1525
+ id: toolId,
1526
+ name: toolInstance.config?.name || toolInstance.name || toolName,
1527
+ config: toolConfig,
1528
+ status: toolInstance.getStatus?.() || toolInstance.status || "unknown"
1529
+ };
1530
+ if (toolInstance.config?.imageUrl) {
1531
+ toolData.imageUrl = toolInstance.config.imageUrl;
1532
+ }
1533
+ if (toolInstance.config?.headers) {
1534
+ toolData.headers = toolInstance.config.headers;
1535
+ }
1536
+ if (toolInstance.capabilities) {
1537
+ toolData.capabilities = toolInstance.capabilities;
1538
+ }
1539
+ if (toolInstance.lastHealthCheck) {
1540
+ toolData.lastHealthCheck = toolInstance.lastHealthCheck;
1541
+ }
1542
+ if (toolInstance.availableTools) {
1543
+ toolData.availableTools = toolInstance.availableTools;
1544
+ }
1545
+ if (toolInstance.lastError) {
1546
+ toolData.lastError = toolInstance.lastError;
1547
+ }
1548
+ if (toolInstance.lastToolsSync) {
1549
+ toolData.lastToolsSync = toolInstance.lastToolsSync;
1550
+ }
1551
+ if (toolInstance.getCredentialReferenceId?.()) {
1552
+ toolData.credentialReferenceId = toolInstance.getCredentialReferenceId();
1553
+ }
1554
+ toolsObject[toolId] = toolData;
1555
+ }
1556
+ }
1557
+ }
1558
+ }
1559
+ const dataComponentsObject = {};
1560
+ for (const agent2 of this.agents) {
1561
+ if (!this.isInternalAgent(agent2)) {
1562
+ continue;
1563
+ }
1564
+ const internalAgent = agent2;
1565
+ const agentDataComponents = internalAgent.getDataComponents();
1566
+ if (agentDataComponents) {
1567
+ for (const dataComponent2 of agentDataComponents) {
1568
+ const dataComponentId = dataComponent2.id || dataComponent2.name.toLowerCase().replace(/\s+/g, "-");
1569
+ if (!dataComponentsObject[dataComponentId]) {
1570
+ dataComponentsObject[dataComponentId] = {
1571
+ id: dataComponentId,
1572
+ name: dataComponent2.name,
1573
+ description: dataComponent2.description || "",
1574
+ props: dataComponent2.props || {}
1575
+ };
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ const artifactComponentsObject = {};
1581
+ for (const agent2 of this.agents) {
1582
+ if (!this.isInternalAgent(agent2)) {
1583
+ continue;
1584
+ }
1585
+ const internalAgent = agent2;
1586
+ const agentArtifactComponents = internalAgent.getArtifactComponents();
1587
+ if (agentArtifactComponents) {
1588
+ for (const artifactComponent2 of agentArtifactComponents) {
1589
+ const artifactComponentId = artifactComponent2.id || artifactComponent2.name.toLowerCase().replace(/\s+/g, "-");
1590
+ if (!artifactComponentsObject[artifactComponentId]) {
1591
+ artifactComponentsObject[artifactComponentId] = {
1592
+ id: artifactComponentId,
1593
+ name: artifactComponent2.name,
1594
+ description: artifactComponent2.description || "",
1595
+ summaryProps: artifactComponent2.summaryProps || {},
1596
+ fullProps: artifactComponent2.fullProps || {}
1597
+ };
1598
+ }
1599
+ }
1600
+ }
1601
+ }
1602
+ return {
1603
+ id: this.graphId,
1604
+ name: this.graphName,
1605
+ description: this.graphDescription,
1606
+ defaultAgentId: this.defaultAgent?.getId() || "",
1607
+ agents: agentsObject,
1608
+ tools: toolsObject,
1609
+ contextConfig: this.contextConfig?.toObject(),
1610
+ credentialReferences: this.credentials?.map((credentialReference) => ({
1611
+ type: credentialReference.type,
1612
+ id: credentialReference.id,
1613
+ credentialStoreId: credentialReference.credentialStoreId,
1614
+ retrievalParams: credentialReference.retrievalParams || {}
1615
+ })),
1616
+ models: this.models,
1617
+ statusUpdates: this.statusUpdateSettings,
1618
+ graphPrompt: this.graphPrompt,
1619
+ dataComponents: Object.keys(dataComponentsObject).length > 0 ? dataComponentsObject : void 0,
1620
+ artifactComponents: Object.keys(artifactComponentsObject).length > 0 ? artifactComponentsObject : void 0,
1621
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1622
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1623
+ };
1624
+ }
1625
+ /**
1626
+ * Initialize all tools in all agents (especially IPCTools that need MCP server URLs)
1627
+ */
1628
+ async initializeAllTools() {
1629
+ logger7.info({ graphId: this.graphId }, "Initializing all tools in graph");
1630
+ const toolInitPromises = [];
1631
+ for (const agent2 of this.agents) {
1632
+ if (!agent2.getTools) {
1633
+ continue;
1634
+ }
1635
+ const internalAgent = agent2;
1636
+ const agentTools = internalAgent.getTools();
1637
+ for (const [toolName, toolInstance] of Object.entries(agentTools)) {
1638
+ if (toolInstance && typeof toolInstance === "object") {
1639
+ if (typeof toolInstance.init === "function") {
1640
+ toolInitPromises.push(
1641
+ (async () => {
1642
+ try {
1643
+ const skipDbRegistration = toolInstance.constructor.name === "IPCTool" || toolInstance.constructor.name === "HostedTool" || toolInstance.constructor.name === "Tool";
1644
+ if (typeof toolInstance.init === "function") {
1645
+ if (skipDbRegistration) {
1646
+ await toolInstance.init({
1647
+ skipDatabaseRegistration: true
1648
+ });
1649
+ } else {
1650
+ await toolInstance.init();
1651
+ }
1652
+ }
1653
+ logger7.debug(
1654
+ {
1655
+ agentId: agent2.getId(),
1656
+ toolName,
1657
+ toolType: toolInstance.constructor.name,
1658
+ skipDbRegistration
1659
+ },
1660
+ "Tool initialized successfully"
1661
+ );
1662
+ } catch (error) {
1663
+ logger7.error(
1664
+ {
1665
+ agentId: agent2.getId(),
1666
+ toolName,
1667
+ error: error instanceof Error ? error.message : "Unknown error"
1668
+ },
1669
+ "Failed to initialize tool"
1670
+ );
1671
+ throw error;
1672
+ }
1673
+ })()
1674
+ );
1675
+ }
1676
+ }
1677
+ }
1678
+ }
1679
+ await Promise.all(toolInitPromises);
1680
+ logger7.info(
1681
+ { graphId: this.graphId, toolCount: toolInitPromises.length },
1682
+ "All tools initialized successfully"
1683
+ );
1684
+ }
1685
+ /**
1686
+ * Initialize the graph and all agents in the backend using the new graph endpoint
1687
+ */
1688
+ async init() {
1689
+ if (this.initialized) {
1690
+ logger7.info({ graphId: this.graphId }, "Graph already initialized");
1691
+ return;
1692
+ }
1693
+ logger7.info(
1694
+ {
1695
+ graphId: this.graphId,
1696
+ agentCount: this.agents.length
1697
+ },
1698
+ "Initializing agent graph using new graph endpoint"
1699
+ );
1700
+ try {
1701
+ await this.initializeAllTools();
1702
+ await this.applyModelInheritance();
1703
+ const graphDefinition = await this.toFullGraphDefinition();
1704
+ logger7.info(
1705
+ {
1706
+ graphId: this.graphId,
1707
+ mode: "api-client",
1708
+ apiUrl: this.baseURL
1709
+ },
1710
+ "Using API client to create/update graph"
1711
+ );
1712
+ const createdGraph = await updateFullGraphViaAPI(
1713
+ this.tenantId,
1714
+ this.projectId,
1715
+ this.baseURL,
1716
+ this.graphId,
1717
+ graphDefinition
1718
+ );
1719
+ logger7.info(
1720
+ {
1721
+ graphId: this.graphId,
1722
+ agentCount: Object.keys(createdGraph.agents || {}).length
1723
+ },
1724
+ "Agent graph initialized successfully using graph endpoint"
1725
+ );
1726
+ this.initialized = true;
1727
+ } catch (error) {
1728
+ logger7.error(
1729
+ {
1730
+ graphId: this.graphId,
1731
+ error: error instanceof Error ? error.message : "Unknown error"
1732
+ },
1733
+ "Failed to initialize agent graph using graph endpoint"
1734
+ );
1735
+ throw error;
1736
+ }
1737
+ }
1738
+ /**
1739
+ * Legacy initialization method - kept for backward compatibility
1740
+ * Initialize the graph and all agents in the backend using individual endpoints
1741
+ */
1742
+ async initLegacy() {
1743
+ if (this.initialized) {
1744
+ logger7.info({ graphId: this.graphId }, "Graph already initialized");
1745
+ return;
1746
+ }
1747
+ logger7.info(
1748
+ {
1749
+ graphId: this.graphId,
1750
+ agentCount: this.agents.length
1751
+ },
1752
+ "Initializing agent graph"
1753
+ );
1754
+ try {
1755
+ if (this.contextConfig) {
1756
+ await this.contextConfig.init();
1757
+ logger7.info(
1758
+ {
1759
+ graphId: this.graphId,
1760
+ contextConfigId: this.contextConfig.getId()
1761
+ },
1762
+ "Context configuration initialized for graph"
1763
+ );
1764
+ }
1765
+ const initPromises = this.agents.map(async (agent2) => {
1766
+ try {
1767
+ agent2.config.graphId = this.graphId;
1768
+ await agent2.init();
1769
+ logger7.debug(
1770
+ {
1771
+ agentId: agent2.getId(),
1772
+ graphId: this.graphId
1773
+ },
1774
+ "Agent initialized in graph"
1775
+ );
1776
+ } catch (error) {
1777
+ logger7.error(
1778
+ {
1779
+ agentId: agent2.getId(),
1780
+ graphId: this.graphId,
1781
+ error: error instanceof Error ? error.message : "Unknown error"
1782
+ },
1783
+ "Failed to initialize agent in graph"
1784
+ );
1785
+ throw error;
1786
+ }
1787
+ });
1788
+ await Promise.all(initPromises);
1789
+ await this.saveToDatabase();
1790
+ await this.createExternalAgents();
1791
+ await this.createAgentRelations();
1792
+ await this.saveRelations();
1793
+ this.initialized = true;
1794
+ logger7.info(
1795
+ {
1796
+ graphId: this.graphId,
1797
+ agentCount: this.agents.length
1798
+ },
1799
+ "Agent graph initialized successfully"
1800
+ );
1801
+ } catch (error) {
1802
+ logger7.error(
1803
+ {
1804
+ graphId: this.graphId,
1805
+ error: error instanceof Error ? error.message : "Unknown error"
1806
+ },
1807
+ "Failed to initialize agent graph"
1808
+ );
1809
+ throw error;
1810
+ }
1811
+ }
1812
+ /**
1813
+ * Generate a response using the default agent
1814
+ */
1815
+ async generate(input, options) {
1816
+ await this._init();
1817
+ if (!this.defaultAgent) {
1818
+ throw new Error("No default agent configured for this graph");
1819
+ }
1820
+ logger7.info(
1821
+ {
1822
+ graphId: this.graphId,
1823
+ defaultAgent: this.defaultAgent.getName(),
1824
+ conversationId: options?.conversationId
1825
+ },
1826
+ "Generating response with default agent"
1827
+ );
1828
+ const response = await this.executeWithBackend(input, options);
1829
+ return response;
1830
+ }
1831
+ /**
1832
+ * Stream a response using the default agent
1833
+ */
1834
+ async stream(input, options) {
1835
+ await this._init();
1836
+ if (!this.defaultAgent) {
1837
+ throw new Error("No default agent configured for this graph");
1838
+ }
1839
+ logger7.info(
1840
+ {
1841
+ graphId: this.graphId,
1842
+ defaultAgent: this.defaultAgent.getName(),
1843
+ conversationId: options?.conversationId
1844
+ },
1845
+ "Streaming response with default agent"
1846
+ );
1847
+ const textStream = async function* (graph) {
1848
+ const response = await graph.executeWithBackend(input, options);
1849
+ const words = response.split(" ");
1850
+ for (const word of words) {
1851
+ yield `${word} `;
1852
+ }
1853
+ };
1854
+ return {
1855
+ textStream: textStream(this)
1856
+ };
1857
+ }
1858
+ /**
1859
+ * Alias for stream() method for consistency with naming patterns
1860
+ */
1861
+ async generateStream(input, options) {
1862
+ return await this.stream(input, options);
1863
+ }
1864
+ /**
1865
+ * Run with a specific agent from the graph
1866
+ */
1867
+ async runWith(agentId, input, options) {
1868
+ await this._init();
1869
+ const agent2 = this.getAgent(agentId);
1870
+ if (!agent2) {
1871
+ throw new Error(`Agent '${agentId}' not found in graph`);
1872
+ }
1873
+ if (!this.isInternalAgent(agent2)) {
1874
+ throw new Error(
1875
+ `Agent '${agentId}' is an external agent and cannot be run directly. External agents are only accessible via delegation.`
1876
+ );
1877
+ }
1878
+ logger7.info(
1879
+ {
1880
+ graphId: this.graphId,
1881
+ agentId,
1882
+ conversationId: options?.conversationId
1883
+ },
1884
+ "Running with specific agent"
1885
+ );
1886
+ const response = await this.executeWithBackend(input, options);
1887
+ return {
1888
+ finalOutput: response,
1889
+ agent: agent2,
1890
+ turnCount: 1,
1891
+ usage: { inputTokens: 0, outputTokens: 0 },
1892
+ metadata: {
1893
+ toolCalls: [],
1894
+ transfers: []
1895
+ }
1896
+ };
1897
+ }
1898
+ /**
1899
+ * Get an agent by name (unified method for all agent types)
1900
+ */
1901
+ getAgent(name) {
1902
+ return this.agentMap.get(name);
1903
+ }
1904
+ /**
1905
+ * Add an agent to the graph
1906
+ */
1907
+ addAgent(agent2) {
1908
+ this.agents.push(agent2);
1909
+ this.agentMap.set(agent2.getId(), agent2);
1910
+ if (this.models && this.isInternalAgent(agent2)) {
1911
+ this.propagateModelSettingsToAgent(agent2);
1912
+ }
1913
+ logger7.info(
1914
+ {
1915
+ graphId: this.graphId,
1916
+ agentId: agent2.getId(),
1917
+ agentType: this.isInternalAgent(agent2) ? "internal" : "external"
1918
+ },
1919
+ "Agent added to graph"
1920
+ );
1921
+ }
1922
+ /**
1923
+ * Remove an agent from the graph
1924
+ */
1925
+ removeAgent(id) {
1926
+ const agentToRemove = this.agentMap.get(id);
1927
+ if (agentToRemove) {
1928
+ this.agentMap.delete(agentToRemove.getId());
1929
+ this.agents = this.agents.filter(
1930
+ (agent2) => agent2.getId() !== agentToRemove.getId()
1931
+ );
1932
+ logger7.info(
1933
+ {
1934
+ graphId: this.graphId,
1935
+ agentId: agentToRemove.getId()
1936
+ },
1937
+ "Agent removed from graph"
1938
+ );
1939
+ return true;
1940
+ }
1941
+ return false;
1942
+ }
1943
+ /**
1944
+ * Get all agents in the graph
1945
+ */
1946
+ getAgents() {
1947
+ return this.agents;
1948
+ }
1949
+ /**
1950
+ * Get all agent ids (unified method for all agent types)
1951
+ */
1952
+ getAgentIds() {
1953
+ return Array.from(this.agentMap.keys());
1954
+ }
1955
+ /**
1956
+ * Set the default agent
1957
+ */
1958
+ setDefaultAgent(agent2) {
1959
+ this.defaultAgent = agent2;
1960
+ this.addAgent(agent2);
1961
+ logger7.info(
1962
+ {
1963
+ graphId: this.graphId,
1964
+ defaultAgent: agent2.getId()
1965
+ },
1966
+ "Default agent updated"
1967
+ );
1968
+ }
1969
+ /**
1970
+ * Get the default agent
1971
+ */
1972
+ getDefaultAgent() {
1973
+ return this.defaultAgent;
1974
+ }
1975
+ /**
1976
+ * Get the graph ID
1977
+ */
1978
+ getId() {
1979
+ return this.graphId;
1980
+ }
1981
+ getName() {
1982
+ return this.graphName;
1983
+ }
1984
+ getDescription() {
1985
+ return this.graphDescription;
1986
+ }
1987
+ getTenantId() {
1988
+ return this.tenantId;
1989
+ }
1990
+ /**
1991
+ * Get the graph's model settingsuration
1992
+ */
1993
+ getModels() {
1994
+ return this.models;
1995
+ }
1996
+ /**
1997
+ * Set the graph's model settingsuration
1998
+ */
1999
+ setModels(models) {
2000
+ this.models = models;
2001
+ }
2002
+ /**
2003
+ * Get the graph's prompt configuration
2004
+ */
2005
+ getGraphPrompt() {
2006
+ return this.graphPrompt;
2007
+ }
2008
+ /**
2009
+ * Get the graph's stopWhen configuration
2010
+ */
2011
+ getStopWhen() {
2012
+ return this.stopWhen || { transferCountIs: 10 };
2013
+ }
2014
+ /**
2015
+ * Get the graph's status updates configuration
2016
+ */
2017
+ getStatusUpdateSettings() {
2018
+ return this.statusUpdateSettings;
2019
+ }
2020
+ /**
2021
+ * Get the summarizer model from the graph's model settings
2022
+ */
2023
+ getSummarizerModel() {
2024
+ return this.models?.summarizer;
2025
+ }
2026
+ /**
2027
+ * Get graph statistics
2028
+ */
2029
+ getStats() {
2030
+ return {
2031
+ agentCount: this.agents.length,
2032
+ defaultAgent: this.defaultAgent?.getName() || null,
2033
+ initialized: this.initialized,
2034
+ graphId: this.graphId,
2035
+ tenantId: this.tenantId
2036
+ };
2037
+ }
2038
+ /**
2039
+ * Validate the graph configuration
2040
+ */
2041
+ validate() {
2042
+ const errors = [];
2043
+ if (this.agents.length === 0) {
2044
+ errors.push("Graph must contain at least one agent");
2045
+ }
2046
+ if (!this.defaultAgent) {
2047
+ errors.push("Graph must have a default agent");
2048
+ }
2049
+ const names = /* @__PURE__ */ new Set();
2050
+ for (const agent2 of this.agents) {
2051
+ const name = agent2.getName();
2052
+ if (names.has(name)) {
2053
+ errors.push(`Duplicate agent name: ${name}`);
2054
+ }
2055
+ names.add(name);
2056
+ }
2057
+ for (const agent2 of this.agents) {
2058
+ if (!this.isInternalAgent(agent2)) continue;
2059
+ const transfers = agent2.getTransfers();
2060
+ for (const transferAgent of transfers) {
2061
+ if (!this.agentMap.has(transferAgent.getName())) {
2062
+ errors.push(
2063
+ `Agent '${agent2.getName()}' has transfer to '${transferAgent.getName()}' which is not in the graph`
2064
+ );
2065
+ }
2066
+ }
2067
+ const delegates = agent2.getDelegates();
2068
+ for (const delegateAgent of delegates) {
2069
+ if (!this.agentMap.has(delegateAgent.getName())) {
2070
+ errors.push(
2071
+ `Agent '${agent2.getName()}' has delegation to '${delegateAgent.getName()}' which is not in the graph`
2072
+ );
2073
+ }
2074
+ }
2075
+ }
2076
+ return {
2077
+ valid: errors.length === 0,
2078
+ errors
2079
+ };
2080
+ }
2081
+ // Private helper methods
2082
+ async _init() {
2083
+ if (!this.initialized) {
2084
+ await this.init();
2085
+ }
2086
+ }
2087
+ /**
2088
+ * Type guard to check if an agent is an internal AgentInterface
2089
+ */
2090
+ isInternalAgent(agent2) {
2091
+ return "getTransfers" in agent2 && typeof agent2.getTransfers === "function";
2092
+ }
2093
+ /**
2094
+ * Get project-level model settingsuration defaults
2095
+ */
2096
+ async getProjectModelDefaults() {
2097
+ try {
2098
+ const project = await agentsCore.getProject(this.dbClient)({
2099
+ scopes: { tenantId: this.tenantId, projectId: this.projectId }
2100
+ });
2101
+ return project?.models;
2102
+ } catch (error) {
2103
+ logger7.warn(
2104
+ {
2105
+ tenantId: this.tenantId,
2106
+ projectId: this.projectId,
2107
+ error: error instanceof Error ? error.message : "Unknown error"
2108
+ },
2109
+ "Failed to get project model defaults"
2110
+ );
2111
+ return void 0;
2112
+ }
2113
+ }
2114
+ /**
2115
+ * Get project-level stopWhen configuration defaults
2116
+ */
2117
+ async getProjectStopWhenDefaults() {
2118
+ try {
2119
+ const project = await agentsCore.getProject(this.dbClient)({
2120
+ scopes: { tenantId: this.tenantId, projectId: this.projectId }
2121
+ });
2122
+ return project?.stopWhen;
2123
+ } catch (error) {
2124
+ logger7.warn(
2125
+ {
2126
+ tenantId: this.tenantId,
2127
+ projectId: this.projectId,
2128
+ error: error instanceof Error ? error.message : "Unknown error"
2129
+ },
2130
+ "Failed to get project stopWhen defaults"
2131
+ );
2132
+ return void 0;
2133
+ }
2134
+ }
2135
+ /**
2136
+ * Apply model inheritance hierarchy: Project -> Graph -> Agent
2137
+ */
2138
+ async applyModelInheritance() {
2139
+ const projectModels = await this.getProjectModelDefaults();
2140
+ if (projectModels) {
2141
+ if (!this.models) {
2142
+ this.models = {};
2143
+ }
2144
+ if (!this.models.base && projectModels.base) {
2145
+ this.models.base = projectModels.base;
2146
+ }
2147
+ if (!this.models.structuredOutput && projectModels.structuredOutput) {
2148
+ this.models.structuredOutput = projectModels.structuredOutput;
2149
+ }
2150
+ if (!this.models.summarizer && projectModels.summarizer) {
2151
+ this.models.summarizer = projectModels.summarizer;
2152
+ }
2153
+ }
2154
+ await this.applyStopWhenInheritance();
2155
+ for (const agent2 of this.agents) {
2156
+ if (this.isInternalAgent(agent2)) {
2157
+ this.propagateModelSettingsToAgent(agent2);
2158
+ }
2159
+ }
2160
+ }
2161
+ /**
2162
+ * Apply stopWhen inheritance hierarchy: Project -> Graph -> Agent
2163
+ */
2164
+ async applyStopWhenInheritance() {
2165
+ const projectStopWhen = await this.getProjectStopWhenDefaults();
2166
+ if (!this.stopWhen) {
2167
+ this.stopWhen = {};
2168
+ }
2169
+ if (this.stopWhen.transferCountIs === void 0 && projectStopWhen?.transferCountIs !== void 0) {
2170
+ this.stopWhen.transferCountIs = projectStopWhen.transferCountIs;
2171
+ }
2172
+ if (this.stopWhen.transferCountIs === void 0) {
2173
+ this.stopWhen.transferCountIs = 10;
2174
+ }
2175
+ if (projectStopWhen?.stepCountIs !== void 0) {
2176
+ for (const agent2 of this.agents) {
2177
+ if (this.isInternalAgent(agent2)) {
2178
+ const internalAgent = agent2;
2179
+ if (!internalAgent.config.stopWhen) {
2180
+ internalAgent.config.stopWhen = {};
2181
+ }
2182
+ if (internalAgent.config.stopWhen.stepCountIs === void 0) {
2183
+ internalAgent.config.stopWhen.stepCountIs = projectStopWhen.stepCountIs;
2184
+ }
2185
+ }
2186
+ }
2187
+ }
2188
+ logger7.debug(
2189
+ {
2190
+ graphId: this.graphId,
2191
+ graphStopWhen: this.stopWhen,
2192
+ projectStopWhen
2193
+ },
2194
+ "Applied stopWhen inheritance from project to graph"
2195
+ );
2196
+ }
2197
+ /**
2198
+ * Propagate graph-level model settings to agents (supporting partial inheritance)
2199
+ */
2200
+ propagateModelSettingsToAgent(agent2) {
2201
+ if (this.models) {
2202
+ if (!agent2.config.models) {
2203
+ agent2.config.models = {};
2204
+ }
2205
+ if (!agent2.config.models.base && this.models.base) {
2206
+ agent2.config.models.base = this.models.base;
2207
+ }
2208
+ if (!agent2.config.models.structuredOutput && this.models.structuredOutput) {
2209
+ agent2.config.models.structuredOutput = this.models.structuredOutput;
2210
+ }
2211
+ if (!agent2.config.models.summarizer && this.models.summarizer) {
2212
+ agent2.config.models.summarizer = this.models.summarizer;
2213
+ }
2214
+ }
2215
+ }
2216
+ /**
2217
+ * Immediately propagate graph-level models to all agents during construction
2218
+ */
2219
+ propagateImmediateModelSettings() {
2220
+ for (const agent2 of this.agents) {
2221
+ if (this.isInternalAgent(agent2)) {
2222
+ this.propagateModelSettingsToAgent(agent2);
2223
+ }
2224
+ }
2225
+ }
2226
+ /**
2227
+ * Type guard to check if an agent is an external AgentInterface
2228
+ */
2229
+ isExternalAgent(agent2) {
2230
+ return !this.isInternalAgent(agent2);
2231
+ }
2232
+ /**
2233
+ * Execute agent using the backend system instead of local runner
2234
+ */
2235
+ async executeWithBackend(input, options) {
2236
+ const normalizedMessages = this.normalizeMessages(input);
2237
+ const url = `${this.baseURL}/tenants/${this.tenantId}/graphs/${this.graphId}/v1/chat/completions`;
2238
+ logger7.info({ url }, "Executing with backend");
2239
+ const requestBody = {
2240
+ model: "gpt-4o-mini",
2241
+ messages: normalizedMessages.map((msg) => ({
2242
+ role: msg.role,
2243
+ content: msg.content
2244
+ })),
2245
+ ...options,
2246
+ // Include conversationId for multi-turn support
2247
+ ...options?.conversationId && {
2248
+ conversationId: options.conversationId
2249
+ },
2250
+ // Include context data if available
2251
+ ...options?.customBodyParams && { ...options.customBodyParams },
2252
+ stream: false
2253
+ // Explicitly disable streaming - must come after options to override
2254
+ };
2255
+ try {
2256
+ const response = await fetch(url, {
2257
+ method: "POST",
2258
+ headers: {
2259
+ "Content-Type": "application/json",
2260
+ Accept: "application/json"
2261
+ },
2262
+ body: JSON.stringify(requestBody)
2263
+ });
2264
+ if (!response.ok) {
2265
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2266
+ }
2267
+ const responseText = await response.text();
2268
+ if (responseText.startsWith("data:")) {
2269
+ return this.parseStreamingResponse(responseText);
2270
+ }
2271
+ const data = JSON.parse(responseText);
2272
+ return data.result || data.choices?.[0]?.message?.content || "";
2273
+ } catch (error) {
2274
+ throw new Error(
2275
+ `Graph execution failed: ${error.message || "Unknown error"}`
2276
+ );
2277
+ }
2278
+ }
2279
+ /**
2280
+ * Parse streaming response in SSE format
2281
+ */
2282
+ parseStreamingResponse(text) {
2283
+ const lines = text.split("\n");
2284
+ let content = "";
2285
+ for (const line of lines) {
2286
+ if (line.startsWith("data: ")) {
2287
+ const dataStr = line.slice(6);
2288
+ if (dataStr === "[DONE]") break;
2289
+ try {
2290
+ const data = JSON.parse(dataStr);
2291
+ const delta = data.choices?.[0]?.delta?.content;
2292
+ if (delta) {
2293
+ content += delta;
2294
+ }
2295
+ } catch (_e) {
2296
+ }
2297
+ }
2298
+ }
2299
+ return content;
2300
+ }
2301
+ /**
2302
+ * Normalize input messages to the expected format
2303
+ */
2304
+ normalizeMessages(input) {
2305
+ if (typeof input === "string") {
2306
+ return [{ role: "user", content: input }];
2307
+ }
2308
+ if (Array.isArray(input)) {
2309
+ return input.map(
2310
+ (msg) => typeof msg === "string" ? { role: "user", content: msg } : msg
2311
+ );
2312
+ }
2313
+ return [input];
2314
+ }
2315
+ async saveToDatabase() {
2316
+ try {
2317
+ const getUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/agent-graphs/${this.graphId}`;
2318
+ try {
2319
+ const getResponse = await fetch(getUrl, {
2320
+ method: "GET",
2321
+ headers: {
2322
+ "Content-Type": "application/json"
2323
+ }
2324
+ });
2325
+ if (getResponse.ok) {
2326
+ logger7.info(
2327
+ { graphId: this.graphId },
2328
+ "Graph already exists in backend"
2329
+ );
2330
+ return;
2331
+ }
2332
+ if (getResponse.status !== 404) {
2333
+ throw new Error(
2334
+ `HTTP ${getResponse.status}: ${getResponse.statusText}`
2335
+ );
2336
+ }
2337
+ } catch (error) {
2338
+ if (!error.message.includes("404")) {
2339
+ throw error;
2340
+ }
2341
+ }
2342
+ logger7.info({ graphId: this.graphId }, "Creating graph in backend");
2343
+ const createUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/agent-graphs`;
2344
+ const createResponse = await fetch(createUrl, {
2345
+ method: "POST",
2346
+ headers: {
2347
+ "Content-Type": "application/json"
2348
+ },
2349
+ body: JSON.stringify({
2350
+ id: this.graphId,
2351
+ name: this.graphName,
2352
+ defaultAgentId: this.defaultAgent?.getId() || "",
2353
+ contextConfigId: this.contextConfig?.getId(),
2354
+ models: this.models
2355
+ })
2356
+ });
2357
+ if (!createResponse.ok) {
2358
+ throw new Error(
2359
+ `HTTP ${createResponse.status}: ${createResponse.statusText}`
2360
+ );
2361
+ }
2362
+ const createData = await createResponse.json();
2363
+ this.graphId = createData.data.id;
2364
+ logger7.info({ graph: createData.data }, "Graph created in backend");
2365
+ } catch (error) {
2366
+ throw new Error(
2367
+ `Failed to save graph to database: ${error instanceof Error ? error.message : "Unknown error"}`
2368
+ );
2369
+ }
2370
+ }
2371
+ async saveRelations() {
2372
+ if (this.defaultAgent) {
2373
+ try {
2374
+ const updateUrl = `${this.baseURL}/tenants/${this.tenantId}/crud/agent-graphs/${this.graphId}`;
2375
+ const updateResponse = await fetch(updateUrl, {
2376
+ method: "PUT",
2377
+ headers: {
2378
+ "Content-Type": "application/json"
2379
+ },
2380
+ body: JSON.stringify({
2381
+ id: this.graphId,
2382
+ defaultAgentId: this.defaultAgent.getId(),
2383
+ contextConfigId: this.contextConfig?.getId()
2384
+ })
2385
+ });
2386
+ if (!updateResponse.ok) {
2387
+ throw new Error(
2388
+ `HTTP ${updateResponse.status}: ${updateResponse.statusText}`
2389
+ );
2390
+ }
2391
+ logger7.debug(
2392
+ {
2393
+ graphId: this.graphId,
2394
+ defaultAgent: this.defaultAgent.getName()
2395
+ },
2396
+ "Graph relationships configured"
2397
+ );
2398
+ } catch (error) {
2399
+ logger7.error(
2400
+ {
2401
+ graphId: this.graphId,
2402
+ error: error instanceof Error ? error.message : "Unknown error"
2403
+ },
2404
+ "Failed to update graph relationships"
2405
+ );
2406
+ throw error;
2407
+ }
2408
+ }
2409
+ }
2410
+ async createAgentRelations() {
2411
+ const allRelationPromises = [];
2412
+ for (const agent2 of this.agents) {
2413
+ if (this.isInternalAgent(agent2)) {
2414
+ const transfers = agent2.getTransfers();
2415
+ for (const transferAgent of transfers) {
2416
+ allRelationPromises.push(
2417
+ this.createInternalAgentRelation(agent2, transferAgent, "transfer")
2418
+ );
2419
+ }
2420
+ const delegates = agent2.getDelegates();
2421
+ for (const delegate of delegates) {
2422
+ if (delegate instanceof ExternalAgent) {
2423
+ allRelationPromises.push(
2424
+ this.createExternalAgentRelation(agent2, delegate, "delegate")
2425
+ );
2426
+ } else {
2427
+ allRelationPromises.push(
2428
+ this.createInternalAgentRelation(
2429
+ agent2,
2430
+ delegate,
2431
+ "delegate"
2432
+ )
2433
+ );
2434
+ }
2435
+ }
2436
+ }
2437
+ }
2438
+ const results = await Promise.allSettled(allRelationPromises);
2439
+ const errors = [];
2440
+ let successCount = 0;
2441
+ for (const result of results) {
2442
+ if (result.status === "fulfilled") {
2443
+ successCount++;
2444
+ } else {
2445
+ errors.push(result.reason);
2446
+ logger7.error(
2447
+ {
2448
+ error: result.reason instanceof Error ? result.reason.message : "Unknown error",
2449
+ graphId: this.graphId
2450
+ },
2451
+ "Failed to create agent relation"
2452
+ );
2453
+ }
2454
+ }
2455
+ logger7.info(
2456
+ {
2457
+ graphId: this.graphId,
2458
+ totalRelations: allRelationPromises.length,
2459
+ successCount,
2460
+ errorCount: errors.length
2461
+ },
2462
+ "Completed agent relation creation batch"
2463
+ );
2464
+ if (errors.length > 0 && successCount === 0) {
2465
+ throw new Error(`All ${errors.length} agent relation creations failed`);
2466
+ }
2467
+ }
2468
+ async createInternalAgentRelation(sourceAgent, targetAgent, relationType) {
2469
+ try {
2470
+ const response = await fetch(
2471
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agent-relations`,
2472
+ {
2473
+ method: "POST",
2474
+ headers: {
2475
+ "Content-Type": "application/json"
2476
+ },
2477
+ body: JSON.stringify({
2478
+ graphId: this.graphId,
2479
+ sourceAgentId: sourceAgent.getId(),
2480
+ targetAgentId: targetAgent.getId(),
2481
+ relationType
2482
+ })
2483
+ }
2484
+ );
2485
+ if (!response.ok) {
2486
+ const errorText = await response.text().catch(() => "Unknown error");
2487
+ if (response.status === 422 && errorText.includes("already exists")) {
2488
+ logger7.info(
2489
+ {
2490
+ sourceAgentId: sourceAgent.getId(),
2491
+ targetAgentId: targetAgent.getId(),
2492
+ graphId: this.graphId,
2493
+ relationType
2494
+ },
2495
+ `${relationType} relation already exists, skipping creation`
2496
+ );
2497
+ return;
2498
+ }
2499
+ throw new Error(
2500
+ `Failed to create agent relation: ${response.status} - ${errorText}`
2501
+ );
2502
+ }
2503
+ logger7.info(
2504
+ {
2505
+ sourceAgentId: sourceAgent.getId(),
2506
+ targetAgentId: targetAgent.getId(),
2507
+ graphId: this.graphId,
2508
+ relationType
2509
+ },
2510
+ `${relationType} relation created successfully`
2511
+ );
2512
+ } catch (error) {
2513
+ logger7.error(
2514
+ {
2515
+ sourceAgentId: sourceAgent.getId(),
2516
+ targetAgentId: targetAgent.getId(),
2517
+ graphId: this.graphId,
2518
+ relationType,
2519
+ error: error instanceof Error ? error.message : "Unknown error"
2520
+ },
2521
+ `Failed to create ${relationType} relation`
2522
+ );
2523
+ throw error;
2524
+ }
2525
+ }
2526
+ // enableComponentMode removed – feature deprecated
2527
+ async createExternalAgentRelation(sourceAgent, externalAgent2, relationType) {
2528
+ try {
2529
+ const response = await fetch(
2530
+ `${this.baseURL}/tenants/${this.tenantId}/crud/agent-relations`,
2531
+ {
2532
+ method: "POST",
2533
+ headers: {
2534
+ "Content-Type": "application/json"
2535
+ },
2536
+ body: JSON.stringify({
2537
+ graphId: this.graphId,
2538
+ sourceAgentId: sourceAgent.getId(),
2539
+ externalAgentId: externalAgent2.getId(),
2540
+ relationType
2541
+ })
2542
+ }
2543
+ );
2544
+ if (!response.ok) {
2545
+ const errorText = await response.text().catch(() => "Unknown error");
2546
+ if (response.status === 422 && errorText.includes("already exists")) {
2547
+ logger7.info(
2548
+ {
2549
+ sourceAgentId: sourceAgent.getId(),
2550
+ externalAgentId: externalAgent2.getId(),
2551
+ graphId: this.graphId,
2552
+ relationType
2553
+ },
2554
+ `${relationType} relation already exists, skipping creation`
2555
+ );
2556
+ return;
2557
+ }
2558
+ throw new Error(
2559
+ `Failed to create external agent relation: ${response.status} - ${errorText}`
2560
+ );
2561
+ }
2562
+ logger7.info(
2563
+ {
2564
+ sourceAgentId: sourceAgent.getId(),
2565
+ externalAgentId: externalAgent2.getId(),
2566
+ graphId: this.graphId,
2567
+ relationType
2568
+ },
2569
+ `${relationType} relation created successfully`
2570
+ );
2571
+ } catch (error) {
2572
+ logger7.error(
2573
+ {
2574
+ sourceAgentId: sourceAgent.getId(),
2575
+ externalAgentId: externalAgent2.getId(),
2576
+ graphId: this.graphId,
2577
+ relationType,
2578
+ error: error instanceof Error ? error.message : "Unknown error"
2579
+ },
2580
+ `Failed to create ${relationType} relation`
2581
+ );
2582
+ throw error;
2583
+ }
2584
+ }
2585
+ /**
2586
+ * Create external agents in the database
2587
+ */
2588
+ async createExternalAgents() {
2589
+ const externalAgents2 = this.agents.filter(
2590
+ (agent2) => this.isExternalAgent(agent2)
2591
+ );
2592
+ logger7.info(
2593
+ {
2594
+ graphId: this.graphId,
2595
+ externalAgentCount: externalAgents2.length
2596
+ },
2597
+ "Creating external agents in database"
2598
+ );
2599
+ const initPromises = externalAgents2.map(async (externalAgent2) => {
2600
+ try {
2601
+ await externalAgent2.init();
2602
+ logger7.debug(
2603
+ {
2604
+ externalAgentId: externalAgent2.getId(),
2605
+ graphId: this.graphId
2606
+ },
2607
+ "External agent created in database"
2608
+ );
2609
+ } catch (error) {
2610
+ logger7.error(
2611
+ {
2612
+ externalAgentId: externalAgent2.getId(),
2613
+ graphId: this.graphId,
2614
+ error: error instanceof Error ? error.message : "Unknown error"
2615
+ },
2616
+ "Failed to create external agent in database"
2617
+ );
2618
+ throw error;
2619
+ }
2620
+ });
2621
+ try {
2622
+ await Promise.all(initPromises);
2623
+ logger7.info(
2624
+ {
2625
+ graphId: this.graphId,
2626
+ externalAgentCount: externalAgents2.length
2627
+ },
2628
+ "All external agents created successfully"
2629
+ );
2630
+ } catch (error) {
2631
+ logger7.error(
2632
+ {
2633
+ graphId: this.graphId,
2634
+ error: error instanceof Error ? error.message : "Unknown error"
2635
+ },
2636
+ "Failed to create some external agents"
2637
+ );
2638
+ throw error;
2639
+ }
2640
+ }
2641
+ };
2642
+ function agentGraph(config) {
2643
+ return new AgentGraph(config);
2644
+ }
2645
+ async function generateGraph(configPath) {
2646
+ logger7.info({ configPath }, "Loading graph configuration");
2647
+ try {
2648
+ const config = await import(configPath);
2649
+ const graphConfig = config.default || config;
2650
+ const graph = agentGraph(graphConfig);
2651
+ await graph.init();
2652
+ logger7.info(
2653
+ {
2654
+ configPath,
2655
+ graphId: graph.getStats().graphId,
2656
+ agentCount: graph.getStats().agentCount
2657
+ },
2658
+ "Graph generated successfully"
2659
+ );
2660
+ return graph;
2661
+ } catch (error) {
2662
+ logger7.error(
2663
+ {
2664
+ configPath,
2665
+ error: error instanceof Error ? error.message : "Unknown error"
2666
+ },
2667
+ "Failed to generate graph from configuration"
2668
+ );
2669
+ throw error;
2670
+ }
2671
+ }
2672
+ zod.z.object({
2673
+ model: zod.z.string().optional(),
2674
+ providerOptions: zod.z.record(zod.z.string(), zod.z.record(zod.z.string(), zod.z.unknown())).optional()
2675
+ });
2676
+ var AgentError = class extends Error {
2677
+ constructor(message, code, details) {
2678
+ super(message);
2679
+ this.code = code;
2680
+ this.details = details;
2681
+ this.name = "AgentError";
2682
+ }
2683
+ };
2684
+ var MaxTurnsExceededError = class extends AgentError {
2685
+ constructor(maxTurns) {
2686
+ super(`Maximum turns (${maxTurns}) exceeded`);
2687
+ this.code = "MAX_TURNS_EXCEEDED";
2688
+ }
2689
+ };
2690
+
2691
+ // src/runner.ts
2692
+ var logger8 = agentsCore.getLogger("runner");
2693
+ var Runner = class _Runner {
2694
+ /**
2695
+ * Run a graph until completion, handling transfers and tool calls
2696
+ * Similar to OpenAI's Runner.run() pattern
2697
+ * NOTE: This now requires a graph instead of an agent
2698
+ */
2699
+ static async run(graph, messages, options) {
2700
+ const maxTurns = options?.maxTurns || 10;
2701
+ let turnCount = 0;
2702
+ const messageHistory = _Runner.normalizeToMessageHistory(messages);
2703
+ const allToolCalls = [];
2704
+ logger8.info(
2705
+ {
2706
+ graphId: graph.getId(),
2707
+ defaultAgent: graph.getDefaultAgent()?.getName(),
2708
+ maxTurns,
2709
+ initialMessageCount: messageHistory.length
2710
+ },
2711
+ "Starting graph run"
2712
+ );
2713
+ while (turnCount < maxTurns) {
2714
+ logger8.debug(
2715
+ {
2716
+ graphId: graph.getId(),
2717
+ turnCount,
2718
+ messageHistoryLength: messageHistory.length
2719
+ },
2720
+ "Starting turn"
2721
+ );
2722
+ const response = await graph.generate(messageHistory, options);
2723
+ turnCount++;
2724
+ logger8.info(
2725
+ {
2726
+ graphId: graph.getId(),
2727
+ turnCount,
2728
+ responseLength: response.length
2729
+ },
2730
+ "Graph generation completed"
2731
+ );
2732
+ return {
2733
+ finalOutput: response,
2734
+ agent: graph.getDefaultAgent() || {},
2735
+ turnCount,
2736
+ usage: { inputTokens: 0, outputTokens: 0 },
2737
+ metadata: {
2738
+ toolCalls: allToolCalls,
2739
+ transfers: []
2740
+ // Graph handles transfers internally
2741
+ }
2742
+ };
2743
+ }
2744
+ logger8.error(
2745
+ {
2746
+ graphId: graph.getId(),
2747
+ maxTurns,
2748
+ finalTurnCount: turnCount
2749
+ },
2750
+ "Maximum turns exceeded"
2751
+ );
2752
+ throw new MaxTurnsExceededError(maxTurns);
2753
+ }
2754
+ /**
2755
+ * Stream a graph's response
2756
+ */
2757
+ static async stream(graph, messages, options) {
2758
+ logger8.info(
2759
+ {
2760
+ graphId: graph.getId(),
2761
+ defaultAgent: graph.getDefaultAgent()?.getName()
2762
+ },
2763
+ "Starting graph stream"
2764
+ );
2765
+ return graph.stream(messages, options);
2766
+ }
2767
+ /**
2768
+ * Execute multiple graphs in parallel and return the first successful result
2769
+ */
2770
+ static async raceGraphs(graphs, messages, options) {
2771
+ if (graphs.length === 0) {
2772
+ throw new Error("No graphs provided for race");
2773
+ }
2774
+ logger8.info(
2775
+ {
2776
+ graphCount: graphs.length,
2777
+ graphIds: graphs.map((g) => g.getId())
2778
+ },
2779
+ "Starting graph race"
2780
+ );
2781
+ const promises = graphs.map(async (graph, index) => {
2782
+ try {
2783
+ const result2 = await _Runner.run(graph, messages, options);
2784
+ return { ...result2, raceIndex: index };
2785
+ } catch (error) {
2786
+ logger8.error(
2787
+ {
2788
+ graphId: graph.getId(),
2789
+ error: error instanceof Error ? error.message : "Unknown error"
2790
+ },
2791
+ "Graph failed in race"
2792
+ );
2793
+ throw error;
2794
+ }
2795
+ });
2796
+ const result = await Promise.race(promises);
2797
+ logger8.info(
2798
+ {
2799
+ winningGraphId: result.graphId || "unknown",
2800
+ raceIndex: result.raceIndex
2801
+ },
2802
+ "Graph race completed"
2803
+ );
2804
+ return result;
2805
+ }
2806
+ // Private helper methods
2807
+ static normalizeToMessageHistory(messages) {
2808
+ if (typeof messages === "string") {
2809
+ return [{ role: "user", content: messages }];
2810
+ }
2811
+ if (Array.isArray(messages)) {
2812
+ return messages.map(
2813
+ (msg) => typeof msg === "string" ? { role: "user", content: msg } : msg
2814
+ );
2815
+ }
2816
+ return [messages];
2817
+ }
2818
+ /**
2819
+ * Validate graph configuration before running
2820
+ */
2821
+ static validateGraph(graph) {
2822
+ const errors = [];
2823
+ if (!graph.getId()) {
2824
+ errors.push("Graph ID is required");
2825
+ }
2826
+ const defaultAgent = graph.getDefaultAgent();
2827
+ if (!defaultAgent) {
2828
+ errors.push("Default agent is required");
2829
+ } else {
2830
+ if (!defaultAgent.getName()) {
2831
+ errors.push("Default agent name is required");
2832
+ }
2833
+ if (!defaultAgent.getInstructions()) {
2834
+ errors.push("Default agent instructions are required");
2835
+ }
2836
+ }
2837
+ const agents = graph.getAgents();
2838
+ if (agents.length === 0) {
2839
+ errors.push("Graph must contain at least one agent");
2840
+ }
2841
+ for (const agent2 of agents) {
2842
+ if (!agent2.getName()) {
2843
+ errors.push(`Agent missing name`);
2844
+ }
2845
+ }
2846
+ return {
2847
+ valid: errors.length === 0,
2848
+ errors
2849
+ };
2850
+ }
2851
+ /**
2852
+ * Get execution statistics for a graph
2853
+ */
2854
+ static async getExecutionStats(graph, messages, options) {
2855
+ const agents = graph.getAgents();
2856
+ const defaultAgent = graph.getDefaultAgent();
2857
+ const messageCount = Array.isArray(messages) ? messages.length : 1;
2858
+ return {
2859
+ estimatedTurns: Math.min(
2860
+ Math.max(messageCount, 1),
2861
+ options?.maxTurns || 10
2862
+ ),
2863
+ estimatedTokens: messageCount * 100,
2864
+ // Rough estimate
2865
+ agentCount: agents.length,
2866
+ defaultAgent: defaultAgent?.getName()
2867
+ };
2868
+ }
2869
+ };
2870
+ var run = Runner.run.bind(Runner);
2871
+ var stream = Runner.stream.bind(Runner);
2872
+ var raceGraphs = Runner.raceGraphs.bind(Runner);
2873
+
2874
+ // src/index.ts
2875
+ init_tool();
2876
+
2877
+ exports.Agent = Agent;
2878
+ exports.AgentGraph = AgentGraph;
2879
+ exports.ArtifactComponent = ArtifactComponent;
2880
+ exports.DataComponent = DataComponent;
2881
+ exports.ExternalAgent = ExternalAgent;
2882
+ exports.Runner = Runner;
2883
+ exports.agent = agent;
2884
+ exports.agentGraph = agentGraph;
2885
+ exports.artifactComponent = artifactComponent;
2886
+ exports.createEnvironmentSettings = createEnvironmentSettings;
2887
+ exports.credential = credential;
2888
+ exports.dataComponent = dataComponent;
2889
+ exports.externalAgent = externalAgent;
2890
+ exports.externalAgents = externalAgents;
2891
+ exports.generateGraph = generateGraph;
2892
+ exports.mcpServer = mcpServer;
2893
+ exports.mcpTool = mcpTool;
2894
+ exports.raceGraphs = raceGraphs;
2895
+ exports.registerEnvironmentSettings = registerEnvironmentSettings;
2896
+ exports.run = run;
2897
+ exports.stream = stream;
2898
+ exports.tool = tool;
2899
+ exports.transfer = transfer;