@inkeep/agents-sdk 0.1.1 → 0.1.7

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