@inkeep/agents-sdk 0.1.1 → 0.1.6

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