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

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