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