@inkeep/agents-sdk 0.1.1 → 0.1.6

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