@inkeep/agents-run-api 0.15.0 → 0.16.1

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.
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig
4
4
  import { dbClient_default } from './chunk-7IMXW4RD.js';
5
5
  import { env } from './chunk-NZHNG4A3.js';
6
6
  import { __publicField } from './chunk-PKBMQBKP.js';
7
- import { getLogger as getLogger$1, getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentGraphWithDefaultAgent, contextValidationMiddleware, getConversationId, getFullGraph, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, getAgentGraphById, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getRelatedAgentsForGraph, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getContextConfigById, getFullGraphDefinition, TemplateEngine, graphHasArtifactComponents, MCPTransportType, getExternalAgent } from '@inkeep/agents-core';
7
+ import { getLogger as getLogger$1, getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentGraphWithDefaultAgent, contextValidationMiddleware, getConversationId, getFullGraph, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, getAgentGraphById, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getRelatedAgentsForGraph, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunction, getContextConfigById, getFullGraphDefinition, TemplateEngine, graphHasArtifactComponents, MCPTransportType, getExternalAgent } from '@inkeep/agents-core';
8
8
  import { otel } from '@hono/otel';
9
9
  import { OpenAPIHono, createRoute, z as z$1 } from '@hono/zod-openapi';
10
10
  import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
@@ -14,7 +14,7 @@ import { HTTPException } from 'hono/http-exception';
14
14
  import { requestId } from 'hono/request-id';
15
15
  import { createMiddleware } from 'hono/factory';
16
16
  import { swaggerUI } from '@hono/swagger-ui';
17
- import z4, { z } from 'zod';
17
+ import z5, { z } from 'zod';
18
18
  import { streamSSE, stream } from 'hono/streaming';
19
19
  import { nanoid } from 'nanoid';
20
20
  import { createUIMessageStream, JsonToSseTransformStream, parsePartialJson, generateObject, tool, streamText, generateText, streamObject } from 'ai';
@@ -24,6 +24,7 @@ import { createGoogleGenerativeAI, google } from '@ai-sdk/google';
24
24
  import { createOpenAI, openai } from '@ai-sdk/openai';
25
25
  import { createOpenRouter, openrouter } from '@openrouter/ai-sdk-provider';
26
26
  import jmespath from 'jmespath';
27
+ import Ajv from 'ajv';
27
28
  import destr from 'destr';
28
29
  import traverse from 'traverse';
29
30
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
@@ -56,7 +57,9 @@ var apiKeyAuth = () => createMiddleware(async (c, next) => {
56
57
  const projectId = c.req.header("x-inkeep-project-id");
57
58
  const graphId = c.req.header("x-inkeep-graph-id");
58
59
  const agentId = c.req.header("x-inkeep-agent-id");
59
- const baseUrl = new URL(c.req.url).origin;
60
+ const proto = c.req.header("x-forwarded-proto") ?? "http";
61
+ const host = c.req.header("x-forwarded-host") ?? c.req.header("host");
62
+ const baseUrl = `${proto}://${host}`;
60
63
  if (process.env.ENVIRONMENT === "development" || process.env.ENVIRONMENT === "test") {
61
64
  let executionContext;
62
65
  if (authHeader?.startsWith("Bearer ")) {
@@ -941,38 +944,6 @@ async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
941
944
  apiKey
942
945
  });
943
946
  }
944
- async function resolveModelConfig(graphId, agent) {
945
- if (agent.models?.base?.model) {
946
- return {
947
- base: agent.models.base,
948
- structuredOutput: agent.models.structuredOutput || agent.models.base,
949
- summarizer: agent.models.summarizer || agent.models.base
950
- };
951
- }
952
- const graph = await getAgentGraphById(dbClient_default)({
953
- scopes: { tenantId: agent.tenantId, projectId: agent.projectId, graphId }
954
- });
955
- if (graph?.models?.base?.model) {
956
- return {
957
- base: graph.models.base,
958
- structuredOutput: agent.models?.structuredOutput || graph.models.structuredOutput || graph.models.base,
959
- summarizer: agent.models?.summarizer || graph.models.summarizer || graph.models.base
960
- };
961
- }
962
- const project = await getProject(dbClient_default)({
963
- scopes: { tenantId: agent.tenantId, projectId: agent.projectId }
964
- });
965
- if (project?.models?.base?.model) {
966
- return {
967
- base: project.models.base,
968
- structuredOutput: agent.models?.structuredOutput || project.models.structuredOutput || project.models.base,
969
- summarizer: agent.models?.summarizer || project.models.summarizer || project.models.base
970
- };
971
- }
972
- throw new Error(
973
- "Base model configuration is required. Please configure models at the project level."
974
- );
975
- }
976
947
  var logger4 = getLogger("ModelFactory");
977
948
  var _ModelFactory = class _ModelFactory {
978
949
  /**
@@ -1356,7 +1327,43 @@ function unregisterStreamHelper(requestId2) {
1356
1327
  streamHelperRegistry.delete(requestId2);
1357
1328
  }
1358
1329
  var tracer = getTracer("agents-run-api");
1359
- var logger6 = getLogger("ArtifactService");
1330
+ getLogger("SchemaValidation");
1331
+ new Ajv({ allErrors: true, strict: false });
1332
+ function extractPreviewFields(schema) {
1333
+ const previewProperties = {};
1334
+ if (schema.properties) {
1335
+ for (const [key, prop] of Object.entries(schema.properties)) {
1336
+ if (prop.inPreview === true) {
1337
+ const cleanProp = { ...prop };
1338
+ delete cleanProp.inPreview;
1339
+ previewProperties[key] = cleanProp;
1340
+ }
1341
+ }
1342
+ }
1343
+ return {
1344
+ type: "object",
1345
+ properties: previewProperties,
1346
+ required: schema.required?.filter((field) => previewProperties[field])
1347
+ };
1348
+ }
1349
+ function extractFullFields(schema) {
1350
+ const fullProperties = {};
1351
+ if (schema.properties) {
1352
+ for (const [key, prop] of Object.entries(schema.properties)) {
1353
+ const cleanProp = { ...prop };
1354
+ delete cleanProp.inPreview;
1355
+ fullProperties[key] = cleanProp;
1356
+ }
1357
+ }
1358
+ return {
1359
+ type: "object",
1360
+ properties: fullProperties,
1361
+ required: schema.required
1362
+ };
1363
+ }
1364
+
1365
+ // src/services/ArtifactService.ts
1366
+ var logger7 = getLogger("ArtifactService");
1360
1367
  var _ArtifactService = class _ArtifactService {
1361
1368
  constructor(context) {
1362
1369
  this.context = context;
@@ -1368,6 +1375,12 @@ var _ArtifactService = class _ArtifactService {
1368
1375
  static clearCaches() {
1369
1376
  _ArtifactService.selectorCache.clear();
1370
1377
  }
1378
+ /**
1379
+ * Update artifact components in the context
1380
+ */
1381
+ updateArtifactComponents(artifactComponents) {
1382
+ this.context.artifactComponents = artifactComponents;
1383
+ }
1371
1384
  /**
1372
1385
  * Get all artifacts for a context from database
1373
1386
  */
@@ -1382,7 +1395,7 @@ var _ArtifactService = class _ArtifactService {
1382
1395
  id: taskId
1383
1396
  });
1384
1397
  if (!task) {
1385
- logger6.warn({ taskId }, "Task not found when fetching artifacts");
1398
+ logger7.warn({ taskId }, "Task not found when fetching artifacts");
1386
1399
  continue;
1387
1400
  }
1388
1401
  const taskArtifacts = await getLedgerArtifacts(dbClient_default)({
@@ -1400,7 +1413,7 @@ var _ArtifactService = class _ArtifactService {
1400
1413
  }
1401
1414
  }
1402
1415
  } catch (error) {
1403
- logger6.error({ error, contextId }, "Error loading context artifacts");
1416
+ logger7.error({ error, contextId }, "Error loading context artifacts");
1404
1417
  }
1405
1418
  return artifacts;
1406
1419
  }
@@ -1409,12 +1422,12 @@ var _ArtifactService = class _ArtifactService {
1409
1422
  */
1410
1423
  async createArtifact(request, agentId) {
1411
1424
  if (!this.context.sessionId) {
1412
- logger6.warn({ request }, "No session ID available for artifact creation");
1425
+ logger7.warn({ request }, "No session ID available for artifact creation");
1413
1426
  return null;
1414
1427
  }
1415
1428
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
1416
1429
  if (!toolResult) {
1417
- logger6.warn(
1430
+ logger7.warn(
1418
1431
  { request, sessionId: this.context.sessionId },
1419
1432
  "Tool result not found for artifact"
1420
1433
  );
@@ -1430,7 +1443,7 @@ var _ArtifactService = class _ArtifactService {
1430
1443
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
1431
1444
  }
1432
1445
  if (!selectedData) {
1433
- logger6.warn(
1446
+ logger7.warn(
1434
1447
  {
1435
1448
  request,
1436
1449
  baseSelector: request.baseSelector
@@ -1439,8 +1452,26 @@ var _ArtifactService = class _ArtifactService {
1439
1452
  );
1440
1453
  selectedData = {};
1441
1454
  }
1442
- const summaryData = this.extractProps(selectedData, request.summaryProps || {});
1443
- let fullData = this.extractProps(selectedData, request.fullProps || {});
1455
+ const component = this.context.artifactComponents?.find((ac) => ac.name === request.type);
1456
+ let summaryData = {};
1457
+ let fullData = {};
1458
+ if (component?.props) {
1459
+ const previewSchema = extractPreviewFields(component.props);
1460
+ const fullSchema = extractFullFields(component.props);
1461
+ summaryData = this.extractPropsFromSchema(
1462
+ selectedData,
1463
+ previewSchema,
1464
+ request.detailsSelector || {}
1465
+ );
1466
+ fullData = this.extractPropsFromSchema(
1467
+ selectedData,
1468
+ fullSchema,
1469
+ request.detailsSelector || {}
1470
+ );
1471
+ } else {
1472
+ summaryData = selectedData;
1473
+ fullData = selectedData;
1474
+ }
1444
1475
  const isFullDataEmpty = !fullData || Object.keys(fullData).length === 0 || Object.values(fullData).every(
1445
1476
  (val) => val === null || val === void 0 || val === "" || Array.isArray(val) && val.length === 0 || typeof val === "object" && Object.keys(val).length === 0
1446
1477
  );
@@ -1449,14 +1480,13 @@ var _ArtifactService = class _ArtifactService {
1449
1480
  }
1450
1481
  const cleanedSummaryData = this.cleanEscapedContent(summaryData);
1451
1482
  const cleanedFullData = this.cleanEscapedContent(fullData);
1452
- const component = this.context.artifactComponents?.find((ac) => ac.name === request.type);
1453
1483
  const artifactData = {
1454
1484
  artifactId: request.artifactId,
1455
1485
  toolCallId: request.toolCallId,
1456
1486
  name: "Processing...",
1457
1487
  description: "Name and description being generated...",
1458
1488
  type: request.type,
1459
- artifactSummary: component?.summaryProps ? this.filterBySchema(cleanedSummaryData, component.summaryProps) : cleanedSummaryData
1489
+ data: cleanedSummaryData
1460
1490
  };
1461
1491
  await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, agentId);
1462
1492
  await this.cacheArtifact(
@@ -1467,15 +1497,61 @@ var _ArtifactService = class _ArtifactService {
1467
1497
  );
1468
1498
  return artifactData;
1469
1499
  } catch (error) {
1470
- logger6.error({ error, request }, "Failed to create artifact");
1500
+ logger7.error({ error, request }, "Failed to create artifact");
1471
1501
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
1472
1502
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
1473
1503
  }
1474
1504
  }
1475
1505
  /**
1476
- * Get artifact data by ID and tool call ID
1506
+ * Get artifact summary data by ID and tool call ID
1477
1507
  */
1478
- async getArtifactData(artifactId, toolCallId, artifactMap) {
1508
+ async getArtifactSummary(artifactId, toolCallId, artifactMap) {
1509
+ const key = `${artifactId}:${toolCallId}`;
1510
+ if (this.context.streamRequestId) {
1511
+ const cachedArtifact = await graphSessionManager.getArtifactCache(
1512
+ this.context.streamRequestId,
1513
+ key
1514
+ );
1515
+ if (cachedArtifact) {
1516
+ return this.formatArtifactSummaryData(cachedArtifact, artifactId, toolCallId);
1517
+ }
1518
+ }
1519
+ if (this.createdArtifacts.has(key)) {
1520
+ const cached = this.createdArtifacts.get(key);
1521
+ return this.formatArtifactSummaryData(cached, artifactId, toolCallId);
1522
+ }
1523
+ if (artifactMap?.has(key)) {
1524
+ const artifact = artifactMap.get(key);
1525
+ return this.formatArtifactSummaryData(artifact, artifactId, toolCallId);
1526
+ }
1527
+ try {
1528
+ if (!this.context.projectId || !this.context.taskId) {
1529
+ logger7.warn(
1530
+ { artifactId, toolCallId },
1531
+ "No projectId or taskId available for artifact lookup"
1532
+ );
1533
+ return null;
1534
+ }
1535
+ const artifacts = await getLedgerArtifacts(dbClient_default)({
1536
+ scopes: { tenantId: this.context.tenantId, projectId: this.context.projectId },
1537
+ artifactId,
1538
+ taskId: this.context.taskId
1539
+ });
1540
+ if (artifacts.length > 0) {
1541
+ return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
1542
+ }
1543
+ } catch (error) {
1544
+ logger7.warn(
1545
+ { artifactId, toolCallId, taskId: this.context.taskId, error },
1546
+ "Failed to fetch artifact"
1547
+ );
1548
+ }
1549
+ return null;
1550
+ }
1551
+ /**
1552
+ * Get artifact full data by ID and tool call ID
1553
+ */
1554
+ async getArtifactFull(artifactId, toolCallId, artifactMap) {
1479
1555
  const key = `${artifactId}:${toolCallId}`;
1480
1556
  if (this.context.streamRequestId) {
1481
1557
  const cachedArtifact = await graphSessionManager.getArtifactCache(
@@ -1483,20 +1559,20 @@ var _ArtifactService = class _ArtifactService {
1483
1559
  key
1484
1560
  );
1485
1561
  if (cachedArtifact) {
1486
- return this.formatArtifactData(cachedArtifact, artifactId, toolCallId);
1562
+ return this.formatArtifactFullData(cachedArtifact, artifactId, toolCallId);
1487
1563
  }
1488
1564
  }
1489
1565
  if (this.createdArtifacts.has(key)) {
1490
1566
  const cached = this.createdArtifacts.get(key);
1491
- return this.formatArtifactData(cached, artifactId, toolCallId);
1567
+ return this.formatArtifactFullData(cached, artifactId, toolCallId);
1492
1568
  }
1493
1569
  if (artifactMap?.has(key)) {
1494
1570
  const artifact = artifactMap.get(key);
1495
- return this.formatArtifactData(artifact, artifactId, toolCallId);
1571
+ return this.formatArtifactFullData(artifact, artifactId, toolCallId);
1496
1572
  }
1497
1573
  try {
1498
1574
  if (!this.context.projectId || !this.context.taskId) {
1499
- logger6.warn(
1575
+ logger7.warn(
1500
1576
  { artifactId, toolCallId },
1501
1577
  "No projectId or taskId available for artifact lookup"
1502
1578
  );
@@ -1508,10 +1584,10 @@ var _ArtifactService = class _ArtifactService {
1508
1584
  taskId: this.context.taskId
1509
1585
  });
1510
1586
  if (artifacts.length > 0) {
1511
- return this.formatArtifactData(artifacts[0], artifactId, toolCallId);
1587
+ return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
1512
1588
  }
1513
1589
  } catch (error) {
1514
- logger6.warn(
1590
+ logger7.warn(
1515
1591
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1516
1592
  "Failed to fetch artifact"
1517
1593
  );
@@ -1519,16 +1595,29 @@ var _ArtifactService = class _ArtifactService {
1519
1595
  return null;
1520
1596
  }
1521
1597
  /**
1522
- * Format raw artifact to standardized data format
1598
+ * Format raw artifact to standardized summary data format
1523
1599
  */
1524
- formatArtifactData(artifact, artifactId, toolCallId) {
1600
+ formatArtifactSummaryData(artifact, artifactId, toolCallId) {
1525
1601
  return {
1526
1602
  artifactId,
1527
1603
  toolCallId,
1528
1604
  name: artifact.name || "Processing...",
1529
1605
  description: artifact.description || "Name and description being generated...",
1530
1606
  type: artifact.metadata?.artifactType || artifact.artifactType,
1531
- artifactSummary: artifact.parts?.[0]?.data?.summary || {}
1607
+ data: artifact.parts?.[0]?.data?.summary || {}
1608
+ };
1609
+ }
1610
+ /**
1611
+ * Format raw artifact to standardized full data format
1612
+ */
1613
+ formatArtifactFullData(artifact, artifactId, toolCallId) {
1614
+ return {
1615
+ artifactId,
1616
+ toolCallId,
1617
+ name: artifact.name || "Processing...",
1618
+ description: artifact.description || "Name and description being generated...",
1619
+ type: artifact.metadata?.artifactType || artifact.artifactType,
1620
+ data: artifact.parts?.[0]?.data?.full || {}
1532
1621
  };
1533
1622
  }
1534
1623
  /**
@@ -1546,14 +1635,13 @@ var _ArtifactService = class _ArtifactService {
1546
1635
  taskId: this.context.taskId,
1547
1636
  toolCallId: request.toolCallId,
1548
1637
  artifactType: request.type,
1549
- summaryProps: summaryData,
1550
- fullProps: fullData,
1638
+ summaryData,
1639
+ data: fullData,
1551
1640
  agentId: effectiveAgentId,
1552
1641
  metadata: {
1553
1642
  toolCallId: request.toolCallId,
1554
1643
  baseSelector: request.baseSelector,
1555
- summaryProps: request.summaryProps,
1556
- fullProps: request.fullProps,
1644
+ detailsSelector: request.detailsSelector,
1557
1645
  sessionId: this.context.sessionId,
1558
1646
  artifactType: request.type
1559
1647
  },
@@ -1564,14 +1652,17 @@ var _ArtifactService = class _ArtifactService {
1564
1652
  }
1565
1653
  );
1566
1654
  } else {
1567
- logger6.warn({
1568
- artifactId: request.artifactId,
1569
- hasStreamRequestId: !!this.context.streamRequestId,
1570
- hasAgentId: !!effectiveAgentId,
1571
- hasTaskId: !!this.context.taskId,
1572
- passedAgentId: agentId,
1573
- contextAgentId: this.context.agentId
1574
- }, "Skipping artifact_saved event - missing required context");
1655
+ logger7.warn(
1656
+ {
1657
+ artifactId: request.artifactId,
1658
+ hasStreamRequestId: !!this.context.streamRequestId,
1659
+ hasAgentId: !!effectiveAgentId,
1660
+ hasTaskId: !!this.context.taskId,
1661
+ passedAgentId: agentId,
1662
+ contextAgentId: this.context.agentId
1663
+ },
1664
+ "Skipping artifact_saved event - missing required context"
1665
+ );
1575
1666
  }
1576
1667
  }
1577
1668
  /**
@@ -1581,7 +1672,7 @@ var _ArtifactService = class _ArtifactService {
1581
1672
  const cacheKey = `${artifactId}:${toolCallId}`;
1582
1673
  const artifactForCache = {
1583
1674
  ...artifactData,
1584
- parts: [{ data: { summary: artifactData.artifactSummary, full: fullData } }],
1675
+ parts: [{ data: { summary: artifactData.data, data: fullData } }],
1585
1676
  metadata: { artifactType: artifactData.type, toolCallId },
1586
1677
  taskId: this.context.taskId
1587
1678
  };
@@ -1622,6 +1713,30 @@ var _ArtifactService = class _ArtifactService {
1622
1713
  * Used by GraphSession to save artifacts after name/description generation
1623
1714
  */
1624
1715
  async saveArtifact(artifact) {
1716
+ let summaryData = artifact.data;
1717
+ let fullData = artifact.data;
1718
+ if (this.context.artifactComponents) {
1719
+ const artifactComponent = this.context.artifactComponents.find(
1720
+ (ac) => ac.name === artifact.type
1721
+ );
1722
+ if (artifactComponent?.props) {
1723
+ try {
1724
+ const schema = artifactComponent.props;
1725
+ const previewSchema = extractPreviewFields(schema);
1726
+ const fullSchema = extractFullFields(schema);
1727
+ summaryData = this.filterBySchema(artifact.data, previewSchema);
1728
+ fullData = this.filterBySchema(artifact.data, fullSchema);
1729
+ } catch (error) {
1730
+ logger7.warn(
1731
+ {
1732
+ artifactType: artifact.type,
1733
+ error: error instanceof Error ? error.message : "Unknown error"
1734
+ },
1735
+ "Failed to extract preview/full fields from schema, using full data for both"
1736
+ );
1737
+ }
1738
+ }
1739
+ }
1625
1740
  const artifactToSave = {
1626
1741
  artifactId: artifact.artifactId,
1627
1742
  name: artifact.name,
@@ -1632,8 +1747,8 @@ var _ArtifactService = class _ArtifactService {
1632
1747
  {
1633
1748
  kind: "data",
1634
1749
  data: {
1635
- summary: artifact.summaryProps,
1636
- full: artifact.fullProps
1750
+ summary: summaryData,
1751
+ full: fullData
1637
1752
  }
1638
1753
  }
1639
1754
  ],
@@ -1646,10 +1761,11 @@ var _ArtifactService = class _ArtifactService {
1646
1761
  },
1647
1762
  contextId: this.context.contextId,
1648
1763
  taskId: this.context.taskId,
1764
+ toolCallId: artifact.toolCallId,
1649
1765
  artifact: artifactToSave
1650
1766
  });
1651
1767
  if (!result.created && result.existing) {
1652
- logger6.debug(
1768
+ logger7.debug(
1653
1769
  {
1654
1770
  artifactId: artifact.artifactId,
1655
1771
  taskId: this.context.taskId
@@ -1702,7 +1818,7 @@ var _ArtifactService = class _ArtifactService {
1702
1818
  extracted[propName] = this.cleanEscapedContent(rawValue);
1703
1819
  }
1704
1820
  } catch (error) {
1705
- logger6.warn(
1821
+ logger7.warn(
1706
1822
  { propName, selector, error: error instanceof Error ? error.message : "Unknown error" },
1707
1823
  "Failed to extract property"
1708
1824
  );
@@ -1714,6 +1830,39 @@ var _ArtifactService = class _ArtifactService {
1714
1830
  }
1715
1831
  return extracted;
1716
1832
  }
1833
+ /**
1834
+ * Extract properties from data using schema-defined fields and custom selectors
1835
+ */
1836
+ extractPropsFromSchema(item, schema, customSelectors) {
1837
+ const extracted = {};
1838
+ if (schema.properties) {
1839
+ for (const fieldName of Object.keys(schema.properties)) {
1840
+ try {
1841
+ const customSelector = customSelectors[fieldName];
1842
+ let rawValue;
1843
+ if (customSelector) {
1844
+ const sanitizedSelector = this.sanitizeJMESPathSelector(customSelector);
1845
+ rawValue = jmespath.search(item, sanitizedSelector);
1846
+ } else {
1847
+ rawValue = item[fieldName];
1848
+ }
1849
+ if (rawValue !== null && rawValue !== void 0) {
1850
+ extracted[fieldName] = this.cleanEscapedContent(rawValue);
1851
+ }
1852
+ } catch (error) {
1853
+ logger7.warn(
1854
+ { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
1855
+ "Failed to extract schema field"
1856
+ );
1857
+ const fallbackValue = item[fieldName];
1858
+ if (fallbackValue !== null && fallbackValue !== void 0) {
1859
+ extracted[fieldName] = this.cleanEscapedContent(fallbackValue);
1860
+ }
1861
+ }
1862
+ }
1863
+ }
1864
+ return extracted;
1865
+ }
1717
1866
  /**
1718
1867
  * Filter extracted props based on schema
1719
1868
  */
@@ -1732,15 +1881,19 @@ __publicField(_ArtifactService, "selectorCache", /* @__PURE__ */ new Map());
1732
1881
  var ArtifactService = _ArtifactService;
1733
1882
 
1734
1883
  // src/services/ArtifactParser.ts
1735
- var logger7 = getLogger("ArtifactParser");
1884
+ var logger8 = getLogger("ArtifactParser");
1736
1885
  var _ArtifactParser = class _ArtifactParser {
1737
1886
  constructor(tenantId, options) {
1738
1887
  __publicField(this, "artifactService");
1739
- const context = {
1740
- tenantId,
1741
- ...options
1742
- };
1743
- this.artifactService = new ArtifactService(context);
1888
+ if (options?.artifactService) {
1889
+ this.artifactService = options.artifactService;
1890
+ } else {
1891
+ const context = {
1892
+ tenantId,
1893
+ ...options
1894
+ };
1895
+ this.artifactService = new ArtifactService(context);
1896
+ }
1744
1897
  }
1745
1898
  /**
1746
1899
  * Check if text contains complete artifact markers (ref or create)
@@ -1816,7 +1969,7 @@ var _ArtifactParser = class _ArtifactParser {
1816
1969
  attrs[key] = value;
1817
1970
  }
1818
1971
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
1819
- logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
1972
+ logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
1820
1973
  return null;
1821
1974
  }
1822
1975
  return {
@@ -1824,8 +1977,7 @@ var _ArtifactParser = class _ArtifactParser {
1824
1977
  toolCallId: attrs.tool,
1825
1978
  type: attrs.type,
1826
1979
  baseSelector: attrs.base,
1827
- summaryProps: attrs.summary || {},
1828
- fullProps: attrs.full || {}
1980
+ detailsSelector: attrs.details || {}
1829
1981
  };
1830
1982
  }
1831
1983
  /**
@@ -1854,8 +2006,7 @@ var _ArtifactParser = class _ArtifactParser {
1854
2006
  toolCallId: annotation.toolCallId,
1855
2007
  type: annotation.type,
1856
2008
  baseSelector: annotation.baseSelector,
1857
- summaryProps: annotation.summaryProps,
1858
- fullProps: annotation.fullProps
2009
+ detailsSelector: annotation.detailsSelector
1859
2010
  };
1860
2011
  return this.artifactService.createArtifact(request, agentId);
1861
2012
  }
@@ -1875,9 +2026,14 @@ var _ArtifactParser = class _ArtifactParser {
1875
2026
  if (artifactData && annotation.raw) {
1876
2027
  createdArtifactData.set(annotation.raw, artifactData);
1877
2028
  } else if (annotation.raw) {
1878
- failedAnnotations.push(`Failed to create artifact "${annotation.artifactId}": Missing or invalid data`);
2029
+ failedAnnotations.push(
2030
+ `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
2031
+ );
1879
2032
  processedText = processedText.replace(annotation.raw, "");
1880
- logger7.warn({ annotation, artifactData }, "Removed failed artifact:create annotation from output");
2033
+ logger8.warn(
2034
+ { annotation, artifactData },
2035
+ "Removed failed artifact:create annotation from output"
2036
+ );
1881
2037
  }
1882
2038
  } catch (error) {
1883
2039
  const errorMsg = error instanceof Error ? error.message : "Unknown error";
@@ -1885,14 +2041,17 @@ var _ArtifactParser = class _ArtifactParser {
1885
2041
  if (annotation.raw) {
1886
2042
  processedText = processedText.replace(annotation.raw, "");
1887
2043
  }
1888
- logger7.error({ annotation, error }, "Failed to extract artifact from create annotation");
2044
+ logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
1889
2045
  }
1890
2046
  }
1891
2047
  if (failedAnnotations.length > 0) {
1892
- logger7.warn({
1893
- failedCount: failedAnnotations.length,
1894
- failures: failedAnnotations
1895
- }, "Some artifact creation attempts failed");
2048
+ logger8.warn(
2049
+ {
2050
+ failedCount: failedAnnotations.length,
2051
+ failures: failedAnnotations
2052
+ },
2053
+ "Some artifact creation attempts failed"
2054
+ );
1896
2055
  }
1897
2056
  const parts = [];
1898
2057
  const createRegex = /<artifact:create\s+([^>]+?)(?:\s*\/)?>(?:(.*?)<\/artifact:create>)?/gs;
@@ -1925,7 +2084,17 @@ var _ArtifactParser = class _ArtifactParser {
1925
2084
  artifactData = await this.getArtifactData(artifactId, toolCallId, artifactMap);
1926
2085
  }
1927
2086
  if (artifactData) {
1928
- parts.push({ kind: "data", data: artifactData });
2087
+ parts.push({
2088
+ kind: "data",
2089
+ data: {
2090
+ artifactId: artifactData.artifactId,
2091
+ toolCallId: artifactData.toolCallId,
2092
+ name: artifactData.name,
2093
+ description: artifactData.description,
2094
+ type: artifactData.type,
2095
+ artifactSummary: artifactData.data
2096
+ }
2097
+ });
1929
2098
  }
1930
2099
  lastIndex = matchStart + fullMatch.length;
1931
2100
  }
@@ -1951,12 +2120,32 @@ var _ArtifactParser = class _ArtifactParser {
1951
2120
  artifactMap
1952
2121
  );
1953
2122
  if (artifactData) {
1954
- parts.push({ kind: "data", data: artifactData });
2123
+ parts.push({
2124
+ kind: "data",
2125
+ data: {
2126
+ artifactId: artifactData.artifactId,
2127
+ toolCallId: artifactData.toolCallId,
2128
+ name: artifactData.name,
2129
+ description: artifactData.description,
2130
+ type: artifactData.type,
2131
+ artifactSummary: artifactData.data
2132
+ }
2133
+ });
1955
2134
  }
1956
2135
  } else if (this.isArtifactCreateComponent(component)) {
1957
2136
  const createData = await this.extractFromArtifactCreateComponent(component, agentId);
1958
2137
  if (createData) {
1959
- parts.push({ kind: "data", data: createData });
2138
+ parts.push({
2139
+ kind: "data",
2140
+ data: {
2141
+ artifactId: createData.artifactId,
2142
+ toolCallId: createData.toolCallId,
2143
+ name: createData.name,
2144
+ description: createData.description,
2145
+ type: createData.type,
2146
+ artifactSummary: createData.data
2147
+ }
2148
+ });
1960
2149
  }
1961
2150
  } else {
1962
2151
  parts.push({ kind: "data", data: component });
@@ -1970,11 +2159,35 @@ var _ArtifactParser = class _ArtifactParser {
1970
2159
  obj.props.tool_call_id,
1971
2160
  artifactMap
1972
2161
  );
1973
- return artifactData ? [{ kind: "data", data: artifactData }] : [];
2162
+ return artifactData ? [
2163
+ {
2164
+ kind: "data",
2165
+ data: {
2166
+ artifactId: artifactData.artifactId,
2167
+ toolCallId: artifactData.toolCallId,
2168
+ name: artifactData.name,
2169
+ description: artifactData.description,
2170
+ type: artifactData.type,
2171
+ artifactSummary: artifactData.data
2172
+ }
2173
+ }
2174
+ ] : [];
1974
2175
  }
1975
2176
  if (this.isArtifactCreateComponent(obj)) {
1976
2177
  const createData = await this.extractFromArtifactCreateComponent(obj, agentId);
1977
- return createData ? [{ kind: "data", data: createData }] : [];
2178
+ return createData ? [
2179
+ {
2180
+ kind: "data",
2181
+ data: {
2182
+ artifactId: createData.artifactId,
2183
+ toolCallId: createData.toolCallId,
2184
+ name: createData.name,
2185
+ description: createData.description,
2186
+ type: createData.type,
2187
+ artifactSummary: createData.data
2188
+ }
2189
+ }
2190
+ ] : [];
1978
2191
  }
1979
2192
  return [{ kind: "data", data: obj }];
1980
2193
  }
@@ -2003,8 +2216,7 @@ var _ArtifactParser = class _ArtifactParser {
2003
2216
  toolCallId: props.tool_call_id,
2004
2217
  type: props.type,
2005
2218
  baseSelector: props.base_selector,
2006
- summaryProps: props.summary_props || {},
2007
- fullProps: props.full_props || {}
2219
+ detailsSelector: props.details_selector || {}
2008
2220
  };
2009
2221
  return await this.extractFromCreateAnnotation(annotation, agentId);
2010
2222
  }
@@ -2012,7 +2224,7 @@ var _ArtifactParser = class _ArtifactParser {
2012
2224
  * Get artifact data - delegates to service
2013
2225
  */
2014
2226
  async getArtifactData(artifactId, toolCallId, artifactMap) {
2015
- return this.artifactService.getArtifactData(artifactId, toolCallId, artifactMap);
2227
+ return await this.artifactService.getArtifactSummary(artifactId, toolCallId, artifactMap);
2016
2228
  }
2017
2229
  };
2018
2230
  // Shared regex patterns - support both single and double quotes
@@ -2046,7 +2258,7 @@ __publicField(_ArtifactParser, "INCOMPLETE_CREATE_REGEX", /<artifact:create(?![^
2046
2258
  var ArtifactParser = _ArtifactParser;
2047
2259
 
2048
2260
  // src/services/GraphSession.ts
2049
- var logger8 = getLogger("GraphSession");
2261
+ var logger9 = getLogger("GraphSession");
2050
2262
  var GraphSession = class {
2051
2263
  // Whether to send data operations
2052
2264
  constructor(sessionId, messageId, graphId, tenantId, projectId, contextId) {
@@ -2079,7 +2291,7 @@ var GraphSession = class {
2079
2291
  __publicField(this, "artifactParser");
2080
2292
  // Session-scoped ArtifactParser instance
2081
2293
  __publicField(this, "isEmitOperations", false);
2082
- logger8.debug({ sessionId, messageId, graphId }, "GraphSession created");
2294
+ logger9.debug({ sessionId, messageId, graphId }, "GraphSession created");
2083
2295
  if (tenantId && projectId) {
2084
2296
  toolSessionManager.createSessionWithId(
2085
2297
  sessionId,
@@ -2103,7 +2315,9 @@ var GraphSession = class {
2103
2315
  sessionId,
2104
2316
  contextId,
2105
2317
  taskId: `task_${contextId}-${messageId}`,
2106
- streamRequestId: sessionId
2318
+ streamRequestId: sessionId,
2319
+ artifactService: this.artifactService
2320
+ // Pass the shared ArtifactService
2107
2321
  });
2108
2322
  }
2109
2323
  }
@@ -2112,7 +2326,7 @@ var GraphSession = class {
2112
2326
  */
2113
2327
  enableEmitOperations() {
2114
2328
  this.isEmitOperations = true;
2115
- logger8.info(
2329
+ logger9.info(
2116
2330
  { sessionId: this.sessionId },
2117
2331
  "\u{1F50D} DEBUG: Emit operations enabled for GraphSession"
2118
2332
  );
@@ -2136,7 +2350,7 @@ var GraphSession = class {
2136
2350
  await streamHelper.writeOperation(formattedOperation);
2137
2351
  }
2138
2352
  } catch (error) {
2139
- logger8.error(
2353
+ logger9.error(
2140
2354
  {
2141
2355
  sessionId: this.sessionId,
2142
2356
  eventType: event.eventType,
@@ -2199,7 +2413,7 @@ var GraphSession = class {
2199
2413
  if (this.statusUpdateState.config.timeInSeconds) {
2200
2414
  this.statusUpdateTimer = setInterval(async () => {
2201
2415
  if (!this.statusUpdateState || this.isEnded) {
2202
- logger8.debug(
2416
+ logger9.debug(
2203
2417
  { sessionId: this.sessionId },
2204
2418
  "Timer triggered but session already cleaned up or ended"
2205
2419
  );
@@ -2211,7 +2425,7 @@ var GraphSession = class {
2211
2425
  }
2212
2426
  await this.checkAndSendTimeBasedUpdate();
2213
2427
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2214
- logger8.info(
2428
+ logger9.info(
2215
2429
  {
2216
2430
  sessionId: this.sessionId,
2217
2431
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -2233,7 +2447,7 @@ var GraphSession = class {
2233
2447
  });
2234
2448
  }
2235
2449
  if (this.isEnded) {
2236
- logger8.debug(
2450
+ logger9.debug(
2237
2451
  {
2238
2452
  sessionId: this.sessionId,
2239
2453
  eventType,
@@ -2253,7 +2467,7 @@ var GraphSession = class {
2253
2467
  if (eventType === "artifact_saved" && data.pendingGeneration) {
2254
2468
  const artifactId = data.artifactId;
2255
2469
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2256
- logger8.warn(
2470
+ logger9.warn(
2257
2471
  {
2258
2472
  sessionId: this.sessionId,
2259
2473
  artifactId,
@@ -2275,7 +2489,7 @@ var GraphSession = class {
2275
2489
  this.artifactProcessingErrors.set(artifactId, errorCount);
2276
2490
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2277
2491
  this.pendingArtifacts.delete(artifactId);
2278
- logger8.error(
2492
+ logger9.error(
2279
2493
  {
2280
2494
  sessionId: this.sessionId,
2281
2495
  artifactId,
@@ -2287,7 +2501,7 @@ var GraphSession = class {
2287
2501
  "Artifact processing failed after max retries, giving up"
2288
2502
  );
2289
2503
  } else {
2290
- logger8.warn(
2504
+ logger9.warn(
2291
2505
  {
2292
2506
  sessionId: this.sessionId,
2293
2507
  artifactId,
@@ -2309,14 +2523,14 @@ var GraphSession = class {
2309
2523
  */
2310
2524
  checkStatusUpdates() {
2311
2525
  if (this.isEnded) {
2312
- logger8.debug(
2526
+ logger9.debug(
2313
2527
  { sessionId: this.sessionId },
2314
2528
  "Session has ended - skipping status update check"
2315
2529
  );
2316
2530
  return;
2317
2531
  }
2318
2532
  if (!this.statusUpdateState) {
2319
- logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2533
+ logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2320
2534
  return;
2321
2535
  }
2322
2536
  const statusUpdateState = this.statusUpdateState;
@@ -2327,11 +2541,11 @@ var GraphSession = class {
2327
2541
  */
2328
2542
  async checkAndSendTimeBasedUpdate() {
2329
2543
  if (this.isEnded) {
2330
- logger8.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2544
+ logger9.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2331
2545
  return;
2332
2546
  }
2333
2547
  if (!this.statusUpdateState) {
2334
- logger8.debug(
2548
+ logger9.debug(
2335
2549
  { sessionId: this.sessionId },
2336
2550
  "No status updates configured for time-based check"
2337
2551
  );
@@ -2344,7 +2558,7 @@ var GraphSession = class {
2344
2558
  try {
2345
2559
  await this.generateAndSendUpdate();
2346
2560
  } catch (error) {
2347
- logger8.error(
2561
+ logger9.error(
2348
2562
  {
2349
2563
  sessionId: this.sessionId,
2350
2564
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2447,29 +2661,29 @@ var GraphSession = class {
2447
2661
  */
2448
2662
  async generateAndSendUpdate() {
2449
2663
  if (this.isEnded) {
2450
- logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2664
+ logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2451
2665
  return;
2452
2666
  }
2453
2667
  if (this.isTextStreaming) {
2454
- logger8.debug(
2668
+ logger9.debug(
2455
2669
  { sessionId: this.sessionId },
2456
2670
  "Text is currently streaming - skipping status update"
2457
2671
  );
2458
2672
  return;
2459
2673
  }
2460
2674
  if (this.isGeneratingUpdate) {
2461
- logger8.debug(
2675
+ logger9.debug(
2462
2676
  { sessionId: this.sessionId },
2463
2677
  "Update already in progress - skipping duplicate generation"
2464
2678
  );
2465
2679
  return;
2466
2680
  }
2467
2681
  if (!this.statusUpdateState) {
2468
- logger8.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2682
+ logger9.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2469
2683
  return;
2470
2684
  }
2471
2685
  if (!this.graphId) {
2472
- logger8.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2686
+ logger9.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2473
2687
  return;
2474
2688
  }
2475
2689
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -2481,7 +2695,7 @@ var GraphSession = class {
2481
2695
  try {
2482
2696
  const streamHelper = getStreamHelper(this.sessionId);
2483
2697
  if (!streamHelper) {
2484
- logger8.warn(
2698
+ logger9.warn(
2485
2699
  { sessionId: this.sessionId },
2486
2700
  "No stream helper found - cannot send status update"
2487
2701
  );
@@ -2501,7 +2715,7 @@ var GraphSession = class {
2501
2715
  if (result.summaries && result.summaries.length > 0) {
2502
2716
  for (const summary of result.summaries) {
2503
2717
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
2504
- logger8.warn(
2718
+ logger9.warn(
2505
2719
  {
2506
2720
  sessionId: this.sessionId,
2507
2721
  summary
@@ -2538,7 +2752,7 @@ var GraphSession = class {
2538
2752
  this.statusUpdateState.lastEventCount = this.events.length;
2539
2753
  }
2540
2754
  } catch (error) {
2541
- logger8.error(
2755
+ logger9.error(
2542
2756
  {
2543
2757
  sessionId: this.sessionId,
2544
2758
  error: error instanceof Error ? error.message : "Unknown error",
@@ -2576,7 +2790,7 @@ var GraphSession = class {
2576
2790
  this.releaseUpdateLock();
2577
2791
  }
2578
2792
  } catch (error) {
2579
- logger8.error(
2793
+ logger9.error(
2580
2794
  {
2581
2795
  sessionId: this.sessionId,
2582
2796
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2654,7 +2868,7 @@ User's Question/Context:
2654
2868
  ${conversationHistory}
2655
2869
  ` : "";
2656
2870
  } catch (error) {
2657
- logger8.warn(
2871
+ logger9.warn(
2658
2872
  { sessionId: this.sessionId, error },
2659
2873
  "Failed to fetch conversation history for structured status update"
2660
2874
  );
@@ -2788,7 +3002,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2788
3002
  return { summaries };
2789
3003
  } catch (error) {
2790
3004
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
2791
- logger8.error({ error }, "Failed to generate structured update, using fallback");
3005
+ logger9.error({ error }, "Failed to generate structured update, using fallback");
2792
3006
  return { summaries: [] };
2793
3007
  } finally {
2794
3008
  span.end();
@@ -2933,6 +3147,9 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2933
3147
  "graph_session.id": this.sessionId,
2934
3148
  "artifact.id": artifactData.artifactId,
2935
3149
  "artifact.type": artifactData.artifactType || "unknown",
3150
+ "artifact.agent_id": artifactData.agentId || "unknown",
3151
+ "artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
3152
+ "artifact.data": JSON.stringify(artifactData.data, null, 2),
2936
3153
  "tenant.id": artifactData.tenantId || "unknown",
2937
3154
  "project.id": artifactData.projectId || "unknown",
2938
3155
  "context.id": artifactData.contextId || "unknown",
@@ -2983,8 +3200,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2983
3200
  Tool Context: ${toolContext ? JSON.stringify(toolContext, null, 2) : "No tool context"}
2984
3201
  Context: ${conversationHistory?.slice(-200) || "Processing"}
2985
3202
  Type: ${artifactData.artifactType || "data"}
2986
- Summary: ${JSON.stringify(artifactData.summaryProps, null, 2)}
2987
- Full: ${JSON.stringify(artifactData.fullProps, null, 2)}
3203
+ Data: ${JSON.stringify(artifactData.data || artifactData.summaryData, null, 2)}
2988
3204
 
2989
3205
  Make it specific and relevant.`;
2990
3206
  let modelToUse = this.statusUpdateState?.summarizerModel;
@@ -3002,7 +3218,7 @@ Make it specific and relevant.`;
3002
3218
  });
3003
3219
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
3004
3220
  modelToUse = agentData.models.base;
3005
- logger8.info(
3221
+ logger9.info(
3006
3222
  {
3007
3223
  sessionId: this.sessionId,
3008
3224
  artifactId: artifactData.artifactId,
@@ -3013,7 +3229,7 @@ Make it specific and relevant.`;
3013
3229
  );
3014
3230
  }
3015
3231
  } catch (error) {
3016
- logger8.warn(
3232
+ logger9.warn(
3017
3233
  {
3018
3234
  sessionId: this.sessionId,
3019
3235
  artifactId: artifactData.artifactId,
@@ -3025,7 +3241,7 @@ Make it specific and relevant.`;
3025
3241
  }
3026
3242
  }
3027
3243
  if (!modelToUse?.model?.trim()) {
3028
- logger8.warn(
3244
+ logger9.warn(
3029
3245
  {
3030
3246
  sessionId: this.sessionId,
3031
3247
  artifactId: artifactData.artifactId
@@ -3058,8 +3274,12 @@ Make it specific and relevant.`;
3058
3274
  "llm.operation": "generate_object",
3059
3275
  "artifact.id": artifactData.artifactId,
3060
3276
  "artifact.type": artifactData.artifactType,
3061
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3062
- "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
3277
+ "artifact.summary": JSON.stringify(artifactData.summaryData, null, 2),
3278
+ "artifact.full": JSON.stringify(
3279
+ artifactData.data || artifactData.summaryData,
3280
+ null,
3281
+ 2
3282
+ ),
3063
3283
  "prompt.length": prompt.length
3064
3284
  }
3065
3285
  },
@@ -3089,8 +3309,12 @@ Make it specific and relevant.`;
3089
3309
  "artifact.type": artifactData.artifactType,
3090
3310
  "artifact.name": result2.object.name,
3091
3311
  "artifact.description": result2.object.description,
3092
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3093
- "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
3312
+ "artifact.summary": JSON.stringify(artifactData.summaryData, null, 2),
3313
+ "artifact.full": JSON.stringify(
3314
+ artifactData.data || artifactData.summaryData,
3315
+ null,
3316
+ 2
3317
+ ),
3094
3318
  "generation.name_length": result2.object.name.length,
3095
3319
  "generation.description_length": result2.object.description.length,
3096
3320
  "generation.attempts": attempt
@@ -3099,7 +3323,7 @@ Make it specific and relevant.`;
3099
3323
  return result2;
3100
3324
  } catch (error) {
3101
3325
  lastError = error instanceof Error ? error : new Error(String(error));
3102
- logger8.warn(
3326
+ logger9.warn(
3103
3327
  {
3104
3328
  sessionId: this.sessionId,
3105
3329
  artifactId: artifactData.artifactId,
@@ -3139,9 +3363,9 @@ Make it specific and relevant.`;
3139
3363
  name: result.name,
3140
3364
  description: result.description,
3141
3365
  type: artifactData.artifactType || "source",
3142
- summaryProps: artifactData.summaryProps || {},
3143
- fullProps: artifactData.fullProps || {},
3144
- metadata: artifactData.metadata || {}
3366
+ data: artifactData.data || {},
3367
+ metadata: artifactData.metadata || {},
3368
+ toolCallId: artifactData.toolCallId
3145
3369
  });
3146
3370
  mainSaveSucceeded = true;
3147
3371
  span.setAttributes({
@@ -3151,7 +3375,7 @@ Make it specific and relevant.`;
3151
3375
  });
3152
3376
  span.setStatus({ code: SpanStatusCode.OK });
3153
3377
  } catch (saveError) {
3154
- logger8.error(
3378
+ logger9.error(
3155
3379
  {
3156
3380
  sessionId: this.sessionId,
3157
3381
  artifactId: artifactData.artifactId,
@@ -3175,11 +3399,11 @@ Make it specific and relevant.`;
3175
3399
  name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
3176
3400
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool results"}`,
3177
3401
  type: artifactData.artifactType || "source",
3178
- summaryProps: artifactData.summaryProps || {},
3179
- fullProps: artifactData.fullProps || {},
3180
- metadata: artifactData.metadata || {}
3402
+ data: artifactData.data || {},
3403
+ metadata: artifactData.metadata || {},
3404
+ toolCallId: artifactData.toolCallId
3181
3405
  });
3182
- logger8.info(
3406
+ logger9.info(
3183
3407
  {
3184
3408
  sessionId: this.sessionId,
3185
3409
  artifactId: artifactData.artifactId
@@ -3190,7 +3414,7 @@ Make it specific and relevant.`;
3190
3414
  } catch (fallbackError) {
3191
3415
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
3192
3416
  if (isDuplicateError) ; else {
3193
- logger8.error(
3417
+ logger9.error(
3194
3418
  {
3195
3419
  sessionId: this.sessionId,
3196
3420
  artifactId: artifactData.artifactId,
@@ -3203,7 +3427,7 @@ Make it specific and relevant.`;
3203
3427
  }
3204
3428
  } catch (error) {
3205
3429
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3206
- logger8.error(
3430
+ logger9.error(
3207
3431
  {
3208
3432
  sessionId: this.sessionId,
3209
3433
  artifactId: artifactData.artifactId,
@@ -3222,7 +3446,7 @@ Make it specific and relevant.`;
3222
3446
  */
3223
3447
  setArtifactCache(key, artifact) {
3224
3448
  this.artifactCache.set(key, artifact);
3225
- logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3449
+ logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3226
3450
  }
3227
3451
  /**
3228
3452
  * Get session-scoped ArtifactService instance
@@ -3241,9 +3465,17 @@ Make it specific and relevant.`;
3241
3465
  */
3242
3466
  getArtifactCache(key) {
3243
3467
  const artifact = this.artifactCache.get(key);
3244
- logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3468
+ logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3245
3469
  return artifact || null;
3246
3470
  }
3471
+ /**
3472
+ * Update artifact components in the shared ArtifactService
3473
+ */
3474
+ updateArtifactComponents(artifactComponents) {
3475
+ if (this.artifactService) {
3476
+ this.artifactService.updateArtifactComponents(artifactComponents);
3477
+ }
3478
+ }
3247
3479
  };
3248
3480
  var GraphSessionManager = class {
3249
3481
  constructor() {
@@ -3256,7 +3488,7 @@ var GraphSessionManager = class {
3256
3488
  const sessionId = messageId;
3257
3489
  const session = new GraphSession(sessionId, messageId, graphId, tenantId, projectId, contextId);
3258
3490
  this.sessions.set(sessionId, session);
3259
- logger8.info(
3491
+ logger9.info(
3260
3492
  { sessionId, messageId, graphId, tenantId, projectId, contextId },
3261
3493
  "GraphSession created"
3262
3494
  );
@@ -3270,7 +3502,7 @@ var GraphSessionManager = class {
3270
3502
  if (session) {
3271
3503
  session.initializeStatusUpdates(config, summarizerModel);
3272
3504
  } else {
3273
- logger8.error(
3505
+ logger9.error(
3274
3506
  {
3275
3507
  sessionId,
3276
3508
  availableSessions: Array.from(this.sessions.keys())
@@ -3287,7 +3519,7 @@ var GraphSessionManager = class {
3287
3519
  if (session) {
3288
3520
  session.enableEmitOperations();
3289
3521
  } else {
3290
- logger8.error(
3522
+ logger9.error(
3291
3523
  {
3292
3524
  sessionId,
3293
3525
  availableSessions: Array.from(this.sessions.keys())
@@ -3308,7 +3540,7 @@ var GraphSessionManager = class {
3308
3540
  recordEvent(sessionId, eventType, agentId, data) {
3309
3541
  const session = this.sessions.get(sessionId);
3310
3542
  if (!session) {
3311
- logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
3543
+ logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
3312
3544
  return;
3313
3545
  }
3314
3546
  session.recordEvent(eventType, agentId, data);
@@ -3319,12 +3551,12 @@ var GraphSessionManager = class {
3319
3551
  endSession(sessionId) {
3320
3552
  const session = this.sessions.get(sessionId);
3321
3553
  if (!session) {
3322
- logger8.warn({ sessionId }, "Attempted to end non-existent session");
3554
+ logger9.warn({ sessionId }, "Attempted to end non-existent session");
3323
3555
  return [];
3324
3556
  }
3325
3557
  const events = session.getEvents();
3326
3558
  const summary = session.getSummary();
3327
- logger8.info({ sessionId, summary }, "GraphSession ended");
3559
+ logger9.info({ sessionId, summary }, "GraphSession ended");
3328
3560
  session.cleanup();
3329
3561
  this.sessions.delete(sessionId);
3330
3562
  return events;
@@ -3378,11 +3610,52 @@ var GraphSessionManager = class {
3378
3610
  const session = this.sessions.get(sessionId);
3379
3611
  return session ? session.getArtifactParser() : null;
3380
3612
  }
3613
+ /**
3614
+ * Update artifact components for a session
3615
+ */
3616
+ updateArtifactComponents(sessionId, artifactComponents) {
3617
+ const session = this.sessions.get(sessionId);
3618
+ if (session) {
3619
+ session.updateArtifactComponents(artifactComponents);
3620
+ }
3621
+ }
3381
3622
  };
3382
3623
  var graphSessionManager = new GraphSessionManager();
3624
+ async function resolveModelConfig(graphId, agent) {
3625
+ if (agent.models?.base?.model) {
3626
+ return {
3627
+ base: agent.models.base,
3628
+ structuredOutput: agent.models.structuredOutput || agent.models.base,
3629
+ summarizer: agent.models.summarizer || agent.models.base
3630
+ };
3631
+ }
3632
+ const graph = await getAgentGraphById(dbClient_default)({
3633
+ scopes: { tenantId: agent.tenantId, projectId: agent.projectId, graphId }
3634
+ });
3635
+ if (graph?.models?.base?.model) {
3636
+ return {
3637
+ base: graph.models.base,
3638
+ structuredOutput: agent.models?.structuredOutput || graph.models.structuredOutput || graph.models.base,
3639
+ summarizer: agent.models?.summarizer || graph.models.summarizer || graph.models.base
3640
+ };
3641
+ }
3642
+ const project = await getProject(dbClient_default)({
3643
+ scopes: { tenantId: agent.tenantId, projectId: agent.projectId }
3644
+ });
3645
+ if (project?.models?.base?.model) {
3646
+ return {
3647
+ base: project.models.base,
3648
+ structuredOutput: agent.models?.structuredOutput || project.models.structuredOutput || project.models.base,
3649
+ summarizer: agent.models?.summarizer || project.models.summarizer || project.models.base
3650
+ };
3651
+ }
3652
+ throw new Error(
3653
+ "Base model configuration is required. Please configure models at the project level."
3654
+ );
3655
+ }
3383
3656
 
3384
3657
  // src/services/IncrementalStreamParser.ts
3385
- var logger9 = getLogger("IncrementalStreamParser");
3658
+ var logger10 = getLogger("IncrementalStreamParser");
3386
3659
  var _IncrementalStreamParser = class _IncrementalStreamParser {
3387
3660
  // Max number of collected parts to prevent unbounded growth
3388
3661
  constructor(streamHelper, tenantId, contextId, artifactParserOptions) {
@@ -3411,9 +3684,20 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3411
3684
  return;
3412
3685
  }
3413
3686
  }
3687
+ let sharedArtifactService = null;
3688
+ if (artifactParserOptions?.streamRequestId && typeof graphSessionManager.getArtifactService === "function") {
3689
+ try {
3690
+ sharedArtifactService = graphSessionManager.getArtifactService(
3691
+ artifactParserOptions.streamRequestId
3692
+ );
3693
+ } catch (error) {
3694
+ }
3695
+ }
3414
3696
  this.artifactParser = new ArtifactParser(tenantId, {
3415
3697
  ...artifactParserOptions,
3416
- contextId
3698
+ contextId,
3699
+ artifactService: sharedArtifactService
3700
+ // Use shared ArtifactService if available
3417
3701
  });
3418
3702
  }
3419
3703
  /**
@@ -3423,7 +3707,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3423
3707
  async initializeArtifactMap() {
3424
3708
  try {
3425
3709
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
3426
- logger9.debug(
3710
+ logger10.debug(
3427
3711
  {
3428
3712
  contextId: this.contextId,
3429
3713
  artifactMapSize: this.artifactMap.size
@@ -3431,7 +3715,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3431
3715
  "Initialized artifact map for streaming"
3432
3716
  );
3433
3717
  } catch (error) {
3434
- logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3718
+ logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3435
3719
  this.artifactMap = /* @__PURE__ */ new Map();
3436
3720
  }
3437
3721
  }
@@ -3528,9 +3812,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3528
3812
  * Note: Text components are handled separately with incremental streaming
3529
3813
  */
3530
3814
  async streamComponent(component) {
3531
- const parts = await this.artifactParser.parseObject({
3532
- dataComponents: [component]
3533
- }, this.artifactMap, this.agentId);
3815
+ const parts = await this.artifactParser.parseObject(
3816
+ {
3817
+ dataComponents: [component]
3818
+ },
3819
+ this.artifactMap,
3820
+ this.agentId
3821
+ );
3534
3822
  if (!Array.isArray(parts)) {
3535
3823
  console.warn("parseObject returned non-array:", parts);
3536
3824
  return;
@@ -3600,9 +3888,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3600
3888
  const componentKey = component.id;
3601
3889
  const hasBeenStreamed = this.lastStreamedComponents.has(componentKey);
3602
3890
  if (!hasBeenStreamed && this.isComponentComplete(component) && component.name !== "Text") {
3603
- const parts = await this.artifactParser.parseObject({
3604
- dataComponents: [component]
3605
- }, this.artifactMap, this.agentId);
3891
+ const parts = await this.artifactParser.parseObject(
3892
+ {
3893
+ dataComponents: [component]
3894
+ },
3895
+ this.artifactMap,
3896
+ this.agentId
3897
+ );
3606
3898
  for (const part of parts) {
3607
3899
  await this.streamPart(part);
3608
3900
  }
@@ -3667,7 +3959,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3667
3959
  remainingBuffer: workingBuffer
3668
3960
  };
3669
3961
  }
3670
- const parts = await this.artifactParser.parseText(workingBuffer, this.artifactMap, this.agentId);
3962
+ const parts = await this.artifactParser.parseText(
3963
+ workingBuffer,
3964
+ this.artifactMap,
3965
+ this.agentId
3966
+ );
3671
3967
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
3672
3968
  const lastPart = parts[parts.length - 1];
3673
3969
  const lastText = lastPart.text || "";
@@ -3739,20 +4035,35 @@ __publicField(_IncrementalStreamParser, "MAX_COLLECTED_PARTS", 1e4);
3739
4035
  var IncrementalStreamParser = _IncrementalStreamParser;
3740
4036
 
3741
4037
  // src/services/ResponseFormatter.ts
3742
- var logger10 = getLogger("ResponseFormatter");
4038
+ var logger11 = getLogger("ResponseFormatter");
3743
4039
  var ResponseFormatter = class {
3744
4040
  constructor(tenantId, artifactParserOptions) {
3745
4041
  __publicField(this, "artifactParser");
3746
4042
  __publicField(this, "agentId");
3747
4043
  this.agentId = artifactParserOptions?.agentId;
3748
4044
  if (artifactParserOptions?.streamRequestId) {
3749
- const sessionParser = graphSessionManager.getArtifactParser(artifactParserOptions.streamRequestId);
4045
+ const sessionParser = graphSessionManager.getArtifactParser(
4046
+ artifactParserOptions.streamRequestId
4047
+ );
3750
4048
  if (sessionParser) {
3751
4049
  this.artifactParser = sessionParser;
3752
4050
  return;
3753
4051
  }
3754
4052
  }
3755
- this.artifactParser = new ArtifactParser(tenantId, artifactParserOptions);
4053
+ let sharedArtifactService = null;
4054
+ if (artifactParserOptions?.streamRequestId && typeof graphSessionManager.getArtifactService === "function") {
4055
+ try {
4056
+ sharedArtifactService = graphSessionManager.getArtifactService(
4057
+ artifactParserOptions.streamRequestId
4058
+ );
4059
+ } catch (error) {
4060
+ }
4061
+ }
4062
+ this.artifactParser = new ArtifactParser(tenantId, {
4063
+ ...artifactParserOptions,
4064
+ artifactService: sharedArtifactService
4065
+ // Use shared ArtifactService if available
4066
+ });
3756
4067
  }
3757
4068
  /**
3758
4069
  * Process structured object response and replace artifact markers with actual artifacts
@@ -3765,7 +4076,11 @@ var ResponseFormatter = class {
3765
4076
  "response.type": "object",
3766
4077
  "response.availableArtifacts": artifactMap.size
3767
4078
  });
3768
- const parts = await this.artifactParser.parseObject(responseObject, artifactMap, this.agentId);
4079
+ const parts = await this.artifactParser.parseObject(
4080
+ responseObject,
4081
+ artifactMap,
4082
+ this.agentId
4083
+ );
3769
4084
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
3770
4085
  span.setAttributes({
3771
4086
  "response.dataPartsCount": parts.length,
@@ -3779,7 +4094,7 @@ var ResponseFormatter = class {
3779
4094
  return { parts };
3780
4095
  } catch (error) {
3781
4096
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3782
- logger10.error({ error, responseObject }, "Error formatting object response");
4097
+ logger11.error({ error, responseObject }, "Error formatting object response");
3783
4098
  return {
3784
4099
  parts: [{ kind: "data", data: responseObject }]
3785
4100
  };
@@ -3831,7 +4146,7 @@ var ResponseFormatter = class {
3831
4146
  return { parts };
3832
4147
  } catch (error) {
3833
4148
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3834
- logger10.error({ error, responseText }, "Error formatting response");
4149
+ logger11.error({ error, responseText }, "Error formatting response");
3835
4150
  return { text: responseText };
3836
4151
  } finally {
3837
4152
  span.end();
@@ -3907,10 +4222,10 @@ function errorOp(message, agentId, severity = "error", code) {
3907
4222
  function generateToolId() {
3908
4223
  return `tool_${nanoid(8)}`;
3909
4224
  }
3910
- var logger11 = getLogger("DataComponentSchema");
4225
+ var logger12 = getLogger("DataComponentSchema");
3911
4226
  function jsonSchemaToZod(jsonSchema) {
3912
4227
  if (!jsonSchema || typeof jsonSchema !== "object") {
3913
- logger11.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
4228
+ logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
3914
4229
  return z.string();
3915
4230
  }
3916
4231
  switch (jsonSchema.type) {
@@ -3937,7 +4252,7 @@ function jsonSchemaToZod(jsonSchema) {
3937
4252
  case "null":
3938
4253
  return z.null();
3939
4254
  default:
3940
- logger11.warn(
4255
+ logger12.warn(
3941
4256
  {
3942
4257
  unsupportedType: jsonSchema.type,
3943
4258
  schema: jsonSchema
@@ -4213,8 +4528,7 @@ var ArtifactCreateSchema = class {
4213
4528
  */
4214
4529
  static getSchemas(artifactComponents) {
4215
4530
  return artifactComponents.map((component) => {
4216
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4217
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
4531
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4218
4532
  const propsSchema = {
4219
4533
  type: "object",
4220
4534
  properties: {
@@ -4233,10 +4547,9 @@ var ArtifactCreateSchema = class {
4233
4547
  },
4234
4548
  base_selector: {
4235
4549
  type: "string",
4236
- description: `JMESPath selector starting with "result." to navigate to ONE specific item. Summary/full props will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']"). EXAMPLE: For JSON {"result":{"structuredContent":{"content":[{"type":"document","title":"Guide"}]}}} - WRONG: "result.content[?type=='document']" (skips structuredContent) - RIGHT: "result.structuredContent.content[?type=='document']".`
4550
+ description: `JMESPath selector starting with "result." to navigate to ONE specific item. Details selector will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']").`
4237
4551
  },
4238
- summary_props: enhancedSummaryProps,
4239
- full_props: enhancedFullProps
4552
+ details_selector: enhancedSchema
4240
4553
  },
4241
4554
  required: ["id", "tool_call_id", "type", "base_selector"]
4242
4555
  };
@@ -4254,8 +4567,7 @@ var ArtifactCreateSchema = class {
4254
4567
  */
4255
4568
  static getDataComponents(tenantId, projectId = "", artifactComponents) {
4256
4569
  return artifactComponents.map((component) => {
4257
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4258
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
4570
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4259
4571
  const propsSchema = {
4260
4572
  type: "object",
4261
4573
  properties: {
@@ -4274,10 +4586,9 @@ var ArtifactCreateSchema = class {
4274
4586
  },
4275
4587
  base_selector: {
4276
4588
  type: "string",
4277
- description: `JMESPath selector starting with "result." to navigate to ONE specific item. Summary/full props will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']"). EXAMPLE: For JSON {"result":{"structuredContent":{"content":[{"type":"document","title":"Guide"}]}}} - WRONG: "result.content[?type=='document']" (skips structuredContent) - RIGHT: "result.structuredContent.content[?type=='document']".`
4589
+ description: `JMESPath selector starting with "result." to navigate to ONE specific item. Details selector will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']").`
4278
4590
  },
4279
- summary_props: enhancedSummaryProps,
4280
- full_props: enhancedFullProps
4591
+ details_selector: enhancedSchema
4281
4592
  },
4282
4593
  required: ["id", "tool_call_id", "type", "base_selector"]
4283
4594
  };
@@ -4304,7 +4615,7 @@ function parseEmbeddedJson(data) {
4304
4615
  }
4305
4616
 
4306
4617
  // src/a2a/client.ts
4307
- var logger12 = getLogger("a2aClient");
4618
+ var logger13 = getLogger("a2aClient");
4308
4619
  var DEFAULT_BACKOFF = {
4309
4620
  initialInterval: 500,
4310
4621
  maxInterval: 6e4,
@@ -4510,7 +4821,7 @@ var A2AClient = class {
4510
4821
  try {
4511
4822
  const res = await fn();
4512
4823
  if (attempt > 0) {
4513
- logger12.info(
4824
+ logger13.info(
4514
4825
  {
4515
4826
  attempts: attempt + 1,
4516
4827
  elapsedTime: Date.now() - start
@@ -4525,7 +4836,7 @@ var A2AClient = class {
4525
4836
  }
4526
4837
  const elapsed = Date.now() - start;
4527
4838
  if (elapsed > maxElapsedTime) {
4528
- logger12.warn(
4839
+ logger13.warn(
4529
4840
  {
4530
4841
  attempts: attempt + 1,
4531
4842
  elapsedTime: elapsed,
@@ -4546,7 +4857,7 @@ var A2AClient = class {
4546
4857
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
4547
4858
  }
4548
4859
  const delayMs = Math.min(retryInterval, maxInterval);
4549
- logger12.info(
4860
+ logger13.info(
4550
4861
  {
4551
4862
  attempt: attempt + 1,
4552
4863
  delayMs,
@@ -4631,7 +4942,7 @@ var A2AClient = class {
4631
4942
  }
4632
4943
  const rpcResponse = await httpResponse.json();
4633
4944
  if (rpcResponse.id !== requestId2) {
4634
- logger12.warn(
4945
+ logger13.warn(
4635
4946
  {
4636
4947
  method,
4637
4948
  expectedId: requestId2,
@@ -4830,7 +5141,7 @@ var A2AClient = class {
4830
5141
  try {
4831
5142
  while (true) {
4832
5143
  const { done, value } = await reader.read();
4833
- logger12.info({ done, value }, "parseA2ASseStream");
5144
+ logger13.info({ done, value }, "parseA2ASseStream");
4834
5145
  if (done) {
4835
5146
  if (eventDataBuffer.trim()) {
4836
5147
  const result = this._processSseEventData(
@@ -4917,7 +5228,7 @@ var A2AClient = class {
4917
5228
  };
4918
5229
 
4919
5230
  // src/agents/relationTools.ts
4920
- var logger13 = getLogger("relationships Tools");
5231
+ var logger14 = getLogger("relationships Tools");
4921
5232
  var generateTransferToolDescription = (config) => {
4922
5233
  return `Hand off the conversation to agent ${config.id}.
4923
5234
 
@@ -4946,7 +5257,7 @@ var createTransferToAgentTool = ({
4946
5257
  }) => {
4947
5258
  return tool({
4948
5259
  description: generateTransferToolDescription(transferConfig),
4949
- inputSchema: z4.object({}),
5260
+ inputSchema: z5.object({}),
4950
5261
  execute: async () => {
4951
5262
  const activeSpan = trace.getActiveSpan();
4952
5263
  if (activeSpan) {
@@ -4955,7 +5266,7 @@ var createTransferToAgentTool = ({
4955
5266
  "transfer.to_agent_id": transferConfig.id ?? "unknown"
4956
5267
  });
4957
5268
  }
4958
- logger13.info(
5269
+ logger14.info(
4959
5270
  {
4960
5271
  transferTo: transferConfig.id ?? "unknown",
4961
5272
  fromAgent: callingAgentId
@@ -4992,7 +5303,7 @@ function createDelegateToAgentTool({
4992
5303
  }) {
4993
5304
  return tool({
4994
5305
  description: generateDelegateToolDescription(delegateConfig.config),
4995
- inputSchema: z4.object({ message: z4.string() }),
5306
+ inputSchema: z5.object({ message: z5.string() }),
4996
5307
  execute: async (input, context) => {
4997
5308
  const delegationId = `del_${nanoid()}`;
4998
5309
  const activeSpan = trace.getActiveSpan();
@@ -5104,7 +5415,7 @@ function createDelegateToAgentTool({
5104
5415
  ...isInternal ? { fromAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
5105
5416
  }
5106
5417
  };
5107
- logger13.info({ messageToSend }, "messageToSend");
5418
+ logger14.info({ messageToSend }, "messageToSend");
5108
5419
  await createMessage(dbClient_default)({
5109
5420
  id: nanoid(),
5110
5421
  tenantId,
@@ -5166,7 +5477,7 @@ function createDelegateToAgentTool({
5166
5477
  }
5167
5478
 
5168
5479
  // src/agents/SystemPromptBuilder.ts
5169
- var logger14 = getLogger("SystemPromptBuilder");
5480
+ var logger15 = getLogger("SystemPromptBuilder");
5170
5481
  var SystemPromptBuilder = class {
5171
5482
  constructor(version, versionConfig) {
5172
5483
  this.version = version;
@@ -5182,12 +5493,12 @@ var SystemPromptBuilder = class {
5182
5493
  this.templates.set(name, content);
5183
5494
  }
5184
5495
  this.loaded = true;
5185
- logger14.debug(
5496
+ logger15.debug(
5186
5497
  { templateCount: this.templates.size, version: this.version },
5187
5498
  `Loaded ${this.templates.size} templates for version ${this.version}`
5188
5499
  );
5189
5500
  } catch (error) {
5190
- logger14.error({ error }, `Failed to load templates for version ${this.version}`);
5501
+ logger15.error({ error }, `Failed to load templates for version ${this.version}`);
5191
5502
  throw new Error(`Template loading failed: ${error}`);
5192
5503
  }
5193
5504
  }
@@ -5212,68 +5523,6 @@ var SystemPromptBuilder = class {
5212
5523
  }
5213
5524
  };
5214
5525
 
5215
- // templates/v1/shared/artifact.xml?raw
5216
- var artifact_default = "<artifact>\n <name>{{ARTIFACT_NAME}}</name>\n <description>{{ARTIFACT_DESCRIPTION}}</description>\n <task_id>{{TASK_ID}}</task_id>\n <artifact_id>{{ARTIFACT_ID}}</artifact_id>\n <tool_call_id>{{TOOL_CALL_ID}}</tool_call_id>\n <summary_data>{{ARTIFACT_SUMMARY}}</summary_data>\n</artifact> ";
5217
-
5218
- // templates/v1/shared/artifact-retrieval-guidance.xml?raw
5219
- var artifact_retrieval_guidance_default = `ARTIFACT RETRIEVAL: ACCESSING EXISTING ARTIFACT DATA
5220
-
5221
- \u{1F6A8} **CRITICAL: ALWAYS CHECK EXISTING ARTIFACTS FIRST** \u{1F6A8}
5222
- Before creating new artifacts, ALWAYS examine existing artifacts to see if they contain relevant information for the current topic or question.
5223
-
5224
- You CAN and SHOULD retrieve information from existing artifacts to answer user questions.
5225
- Available artifacts contain structured data that you can access in two ways:
5226
-
5227
- 1. **SUMMARY DATA**: Read the summary_data directly from available artifacts for basic information
5228
- 2. **FULL DATA**: Use the get_artifact tool to retrieve complete artifact data (both summary_data and full_data) when you need detailed information
5229
-
5230
- **REUSE EXISTING ARTIFACTS WHEN POSSIBLE:**
5231
- - Look for artifacts with similar topics, names, or descriptions
5232
- - Check if existing artifacts can answer the current question
5233
- - Use existing artifact data instead of creating duplicates
5234
- - Only create new artifacts if existing ones don't contain the needed information
5235
- - Prioritize reusing relevant existing artifacts over creating new ones
5236
-
5237
- HOW TO USE ARTIFACT DATA:
5238
- - Read summary_data from available artifacts for quick answers
5239
- - Use get_artifact tool when you need comprehensive details
5240
- - Extract specific information to answer user questions accurately
5241
- - Reference artifacts when citing the information source
5242
- - Combine information from multiple existing artifacts when relevant
5243
-
5244
- \u{1F6A8} **MANDATORY CITATION POLICY** \u{1F6A8}
5245
- EVERY piece of information from existing artifacts MUST be properly cited:
5246
- - When referencing information from existing artifacts = MUST cite with artifact reference
5247
- - When discussing artifact data = MUST cite the artifact source
5248
- - When using artifact information = MUST reference the artifact
5249
- - NO INFORMATION from existing artifacts can be presented without proper citation
5250
-
5251
- CITATION PLACEMENT RULES:
5252
- - ALWAYS place artifact citations AFTER complete thoughts and punctuation
5253
- - Never interrupt a sentence or thought with an artifact citation
5254
- - Complete your sentence or thought, add punctuation, THEN add the citation
5255
- - This maintains natural reading flow and professional presentation
5256
-
5257
- \u2705 CORRECT EXAMPLES:
5258
- - "The API uses OAuth 2.0 authentication. <artifact:create id='auth-doc' ...> This process involves three main steps..."
5259
- - "Based on the documentation, there are several authentication methods available. <artifact:create id='auth-methods' ...> The recommended approach is OAuth 2.0."
5260
-
5261
- \u274C WRONG EXAMPLES:
5262
- - "The API uses <artifact:create id='auth-doc' ...> OAuth 2.0 authentication which involves..."
5263
- - "According to <artifact:create id='auth-doc' ...>, the authentication method is OAuth 2.0."
5264
-
5265
- \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
5266
-
5267
- DELEGATION AND ARTIFACTS:
5268
- When you use delegation tools, the response may include artifacts in the parts array. These appear as objects with:
5269
- - kind: "data"
5270
- - data: { artifactId, toolCallId, name, description, type, artifactSummary }
5271
-
5272
- These artifacts become immediately available for you to reference using the artifactId and toolCallId from the response.
5273
- Present delegation results naturally without mentioning the delegation process itself.
5274
-
5275
- IMPORTANT: All agents can retrieve and use information from existing artifacts when the graph has artifact components, regardless of whether the individual agent can create new artifacts.`;
5276
-
5277
5526
  // templates/v1/phase1/system-prompt.xml?raw
5278
5527
  var system_prompt_default = `<system_message>
5279
5528
  <agent_identity>
@@ -5390,6 +5639,68 @@ var thinking_preparation_default = `<thinking_preparation_mode>
5390
5639
  // templates/v1/phase1/tool.xml?raw
5391
5640
  var tool_default = "<tool>\n <name>{{TOOL_NAME}}</name>\n <description>{{TOOL_DESCRIPTION}}</description>\n <parameters>\n <schema>\n {{TOOL_PARAMETERS_SCHEMA}}\n </schema>\n </parameters>\n <usage_guidelines>\n {{TOOL_USAGE_GUIDELINES}}\n </usage_guidelines>\n</tool> ";
5392
5641
 
5642
+ // templates/v1/shared/artifact.xml?raw
5643
+ var artifact_default = "<artifact>\n <name>{{ARTIFACT_NAME}}</name>\n <description>{{ARTIFACT_DESCRIPTION}}</description>\n <task_id>{{TASK_ID}}</task_id>\n <artifact_id>{{ARTIFACT_ID}}</artifact_id>\n <tool_call_id>{{TOOL_CALL_ID}}</tool_call_id>\n <summary_data>{{ARTIFACT_SUMMARY}}</summary_data>\n <!-- NOTE: This shows summary/preview data only. Use get_reference_artifact tool to get complete artifact data if needed. -->\n</artifact> ";
5644
+
5645
+ // templates/v1/shared/artifact-retrieval-guidance.xml?raw
5646
+ var artifact_retrieval_guidance_default = `ARTIFACT RETRIEVAL: ACCESSING EXISTING ARTIFACT DATA
5647
+
5648
+ \u{1F6A8} **CRITICAL: ALWAYS CHECK EXISTING ARTIFACTS FIRST** \u{1F6A8}
5649
+ Before creating new artifacts, ALWAYS examine existing artifacts to see if they contain relevant information for the current topic or question.
5650
+
5651
+ You CAN and SHOULD retrieve information from existing artifacts to answer user questions.
5652
+ Available artifacts contain structured data that you can access in two ways:
5653
+
5654
+ 1. **SUMMARY DATA**: Read the summary_data directly from available artifacts for basic information
5655
+ 2. **FULL DATA**: Use the get_artifact tool to retrieve complete artifact data (both summary_data and full_data) when you need detailed information
5656
+
5657
+ **REUSE EXISTING ARTIFACTS WHEN POSSIBLE:**
5658
+ - Look for artifacts with similar topics, names, or descriptions
5659
+ - Check if existing artifacts can answer the current question
5660
+ - Use existing artifact data instead of creating duplicates
5661
+ - Only create new artifacts if existing ones don't contain the needed information
5662
+ - Prioritize reusing relevant existing artifacts over creating new ones
5663
+
5664
+ HOW TO USE ARTIFACT DATA:
5665
+ - Read summary_data from available artifacts for quick answers
5666
+ - Use get_artifact tool when you need comprehensive details
5667
+ - Extract specific information to answer user questions accurately
5668
+ - Reference artifacts when citing the information source
5669
+ - Combine information from multiple existing artifacts when relevant
5670
+
5671
+ \u{1F6A8} **MANDATORY CITATION POLICY** \u{1F6A8}
5672
+ EVERY piece of information from existing artifacts MUST be properly cited:
5673
+ - When referencing information from existing artifacts = MUST cite with artifact reference
5674
+ - When discussing artifact data = MUST cite the artifact source
5675
+ - When using artifact information = MUST reference the artifact
5676
+ - NO INFORMATION from existing artifacts can be presented without proper citation
5677
+
5678
+ CITATION PLACEMENT RULES:
5679
+ - ALWAYS place artifact citations AFTER complete thoughts and punctuation
5680
+ - Never interrupt a sentence or thought with an artifact citation
5681
+ - Complete your sentence or thought, add punctuation, THEN add the citation
5682
+ - This maintains natural reading flow and professional presentation
5683
+
5684
+ \u2705 CORRECT EXAMPLES:
5685
+ - "The API uses OAuth 2.0 authentication. <artifact:create id='auth-doc' ...> This process involves three main steps..."
5686
+ - "Based on the documentation, there are several authentication methods available. <artifact:create id='auth-methods' ...> The recommended approach is OAuth 2.0."
5687
+
5688
+ \u274C WRONG EXAMPLES:
5689
+ - "The API uses <artifact:create id='auth-doc' ...> OAuth 2.0 authentication which involves..."
5690
+ - "According to <artifact:create id='auth-doc' ...>, the authentication method is OAuth 2.0."
5691
+
5692
+ \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
5693
+
5694
+ DELEGATION AND ARTIFACTS:
5695
+ When you use delegation tools, the response may include artifacts in the parts array. These appear as objects with:
5696
+ - kind: "data"
5697
+ - data: { artifactId, toolCallId, name, description, type, artifactSummary }
5698
+
5699
+ These artifacts become immediately available for you to reference using the artifactId and toolCallId from the response.
5700
+ Present delegation results naturally without mentioning the delegation process itself.
5701
+
5702
+ IMPORTANT: All agents can retrieve and use information from existing artifacts when the graph has artifact components, regardless of whether the individual agent can create new artifacts.`;
5703
+
5393
5704
  // src/agents/versions/v1/Phase1Config.ts
5394
5705
  getLogger("Phase1Config");
5395
5706
  var Phase1Config = class _Phase1Config {
@@ -5525,8 +5836,8 @@ SELECTOR REQUIREMENTS:
5525
5836
 
5526
5837
  CRITICAL: SELECTOR HIERARCHY
5527
5838
  - base_selector: Points to ONE specific item in the tool result
5528
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
5529
- - Example: If base="result.documents[?type=='api']" then summary_props uses "title" not "documents[0].title"
5839
+ - details_selector: Contains JMESPath selectors RELATIVE to the base selector
5840
+ - Example: If base="result.documents[?type=='api']" then details_selector uses "title" not "documents[0].title"
5530
5841
 
5531
5842
  COMMON FAILURE POINTS (AVOID THESE):
5532
5843
  1. **Array Selection**: result.items (returns array) \u274C
@@ -5558,24 +5869,22 @@ You will create and reference artifacts using inline annotations in your text re
5558
5869
 
5559
5870
  CREATING ARTIFACTS (SERVES AS CITATION):
5560
5871
  Use the artifact:create annotation to extract data from tool results. The creation itself serves as a citation.
5561
- Format: <artifact:create id="unique-id" tool="tool_call_id" type="TypeName" base="selector.path" summary='{"key":"jmespath_selector"}' full='{"key":"jmespath_selector"}' />
5872
+ Format: <artifact:create id="unique-id" tool="tool_call_id" type="TypeName" base="selector.path" details='{"key":"jmespath_selector"}' />
5562
5873
 
5563
- \u{1F6A8} CRITICAL: SUMMARY AND FULL PROPS USE JMESPATH SELECTORS, NOT LITERAL VALUES! \u{1F6A8}
5874
+ \u{1F6A8} CRITICAL: DETAILS PROPS USE JMESPATH SELECTORS, NOT LITERAL VALUES! \u{1F6A8}
5564
5875
 
5565
5876
  \u274C WRONG - Using literal values:
5566
- summary='{"title":"API Documentation","type":"guide"}'
5567
- full='{"description":"This is a comprehensive guide..."}'
5877
+ details='{"title":"API Documentation","type":"guide"}'
5568
5878
 
5569
5879
  \u2705 CORRECT - Using JMESPath selectors (relative to base selector):
5570
- summary='{"title":"metadata.title","doc_type":"document_type"}'
5571
- full='{"description":"content.description","main_text":"content.text","author":"metadata.author"}'
5880
+ details='{"title":"metadata.title","doc_type":"document_type","description":"content.description","main_text":"content.text","author":"metadata.author"}'
5572
5881
 
5573
5882
  The selectors extract actual field values from the data structure selected by your base selector.
5574
5883
 
5575
- THE summary AND full PROPERTIES MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE TOOL RESULT!
5576
- - summary: Contains JMESPath selectors relative to the base selector
5577
- - full: Contains JMESPath selectors relative to the base selector
5884
+ THE details PROPERTY MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE TOOL RESULT!
5885
+ - details: Contains JMESPath selectors relative to the base selector that map to artifact schema fields
5578
5886
  - These selectors are evaluated against the tool result to extract the actual values
5887
+ - The system automatically determines which fields are preview vs full based on the artifact schema
5579
5888
  - NEVER put literal values like "Inkeep" or "2023" - always use selectors like "metadata.company" or "founded_year"
5580
5889
 
5581
5890
  \u{1F6AB} FORBIDDEN JMESPATH PATTERNS:
@@ -5635,7 +5944,7 @@ Only use artifact:ref when you need to cite the SAME artifact again for a differ
5635
5944
  Format: <artifact:ref id="artifact-id" tool="tool_call_id" />
5636
5945
 
5637
5946
  EXAMPLE TEXT RESPONSE:
5638
- "I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base='result.documents[?type=="auth"]' summary='{"title":"metadata.title","endpoint":"api.endpoint"}' full='{"description":"content.description","parameters":"spec.parameters","examples":"examples.sample_code"}' /> The documentation explains OAuth 2.0 implementation in detail.
5947
+ "I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base='result.documents[?type=="auth"]' details='{"title":"metadata.title","endpoint":"api.endpoint","description":"content.description","parameters":"spec.parameters","examples":"examples.sample_code"}' /> The documentation explains OAuth 2.0 implementation in detail.
5639
5948
 
5640
5949
  The process involves three main steps: registration, token exchange, and API calls. As mentioned in the authentication documentation <artifact:ref id='auth-doc-1' tool='call_xyz789' />, you'll need to register your application first."
5641
5950
 
@@ -5691,31 +6000,29 @@ IMPORTANT GUIDELINES:
5691
6000
  return "";
5692
6001
  }
5693
6002
  const typeDescriptions = artifactComponents.map((ac) => {
5694
- let summarySchema = "No schema defined";
5695
- let fullSchema = "No schema defined";
5696
- if (ac.summaryProps?.properties) {
5697
- const summaryDetails = Object.entries(ac.summaryProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
5698
- summarySchema = `Required: ${summaryDetails}`;
5699
- }
5700
- if (ac.fullProps?.properties) {
5701
- const fullDetails = Object.entries(ac.fullProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
5702
- fullSchema = `Available: ${fullDetails}`;
6003
+ let schemaDescription = "No schema defined";
6004
+ if (ac.props?.properties) {
6005
+ const fieldDetails = Object.entries(ac.props.properties).map(([key, value]) => {
6006
+ const inPreview = value.inPreview ? " [PREVIEW]" : " [FULL]";
6007
+ return `${key} (${value.description || value.type || "field"})${inPreview}`;
6008
+ }).join(", ");
6009
+ schemaDescription = `Fields: ${fieldDetails}`;
5703
6010
  }
5704
6011
  return ` - "${ac.name}": ${ac.description || "No description available"}
5705
- Summary Props: ${summarySchema}
5706
- Full Props: ${fullSchema}`;
6012
+ ${schemaDescription}`;
5707
6013
  }).join("\n\n");
5708
6014
  return `
5709
6015
  AVAILABLE ARTIFACT TYPES:
5710
6016
 
5711
6017
  ${typeDescriptions}
5712
6018
 
5713
- \u{1F6A8} CRITICAL: SUMMARY AND FULL PROPS MUST MATCH THE ARTIFACT SCHEMA! \u{1F6A8}
6019
+ \u{1F6A8} CRITICAL: DETAILS PROPS MUST MATCH THE ARTIFACT SCHEMA! \u{1F6A8}
5714
6020
  - Only use property names that are defined in the artifact component schema above
5715
6021
  - Do NOT make up arbitrary property names like "founders", "nick_details", "year"
5716
- - Each artifact type has specific required fields in summaryProps and available fields in fullProps
6022
+ - Each artifact type has specific fields defined in its schema
5717
6023
  - Your JMESPath selectors must extract values for these exact schema-defined properties
5718
- - Example: If schema defines "title" and "url", use summary='{"title":"title","url":"url"}' not made-up names
6024
+ - Example: If schema defines "title" and "url", use details='{"title":"title","url":"url"}' not made-up names
6025
+ - The system will automatically determine which fields are preview vs full based on schema configuration
5719
6026
 
5720
6027
  \u{1F6A8} CRITICAL: USE EXACT ARTIFACT TYPE NAMES IN QUOTES! \u{1F6A8}
5721
6028
  - MUST use the exact type name shown in quotes above
@@ -5726,7 +6033,11 @@ ${typeDescriptions}
5726
6033
  }
5727
6034
  generateArtifactsSection(templates, artifacts, hasArtifactComponents = false, artifactComponents, hasGraphArtifactComponents) {
5728
6035
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
5729
- const rules = this.getArtifactReferencingRules(hasArtifactComponents, templates, shouldShowReferencingRules);
6036
+ const rules = this.getArtifactReferencingRules(
6037
+ hasArtifactComponents,
6038
+ templates,
6039
+ shouldShowReferencingRules
6040
+ );
5730
6041
  const creationInstructions = this.getArtifactCreationInstructions(
5731
6042
  hasArtifactComponents,
5732
6043
  artifactComponents
@@ -5821,6 +6132,12 @@ ${propertiesXml}
5821
6132
  }
5822
6133
  };
5823
6134
 
6135
+ // templates/v1/phase2/data-component.xml?raw
6136
+ var data_component_default = "<data-component>\n <name>{{COMPONENT_NAME}}</name>\n <description>{{COMPONENT_DESCRIPTION}}</description>\n <props>\n <schema>\n {{COMPONENT_PROPS_SCHEMA}}\n </schema>\n </props>\n</data-component> ";
6137
+
6138
+ // templates/v1/phase2/data-components.xml?raw
6139
+ var data_components_default = '<data_components_section description="These are the data components available for you to use in generating responses. Each component represents a single structured piece of information. You can create multiple instances of the same component type when needed.\n\n***MANDATORY JSON RESPONSE FORMAT - ABSOLUTELY CRITICAL***:\n- WHEN DATA COMPONENTS ARE AVAILABLE, YOU MUST RESPOND IN JSON FORMAT ONLY\n- DO NOT respond with plain text when data components are defined\n- YOUR RESPONSE MUST BE STRUCTURED JSON WITH dataComponents ARRAY\n- THIS IS NON-NEGOTIABLE - JSON FORMAT IS REQUIRED\n\nCRITICAL JSON FORMATTING RULES - MUST FOLLOW EXACTLY:\n1. Each data component must include id, name, and props fields\n2. The id and name should match the exact component definition\n3. The props field contains the actual component data using exact property names from the schema\n4. NEVER omit the id and name fields\n\nCORRECT: [{\\"id\\": \\"component1\\", \\"name\\": \\"Component1\\", \\"props\\": {\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}, {\\"id\\": \\"component2\\", \\"name\\": \\"Component2\\", \\"props\\": {\\"field3\\": \\"value3\\"}}]\nWRONG: [{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}, {\\"field3\\": \\"value3\\"}]\n\nAVAILABLE DATA COMPONENTS: {{DATA_COMPONENTS_LIST}}">\n\n{{DATA_COMPONENTS_XML}}\n\n</data_components_section>';
6140
+
5824
6141
  // templates/v1/phase2/system-prompt.xml?raw
5825
6142
  var system_prompt_default2 = `<phase2_system_message>
5826
6143
  <instruction>
@@ -5860,12 +6177,6 @@ var system_prompt_default2 = `<phase2_system_message>
5860
6177
  </requirements>
5861
6178
  </phase2_system_message>`;
5862
6179
 
5863
- // templates/v1/phase2/data-components.xml?raw
5864
- var data_components_default = '<data_components_section description="These are the data components available for you to use in generating responses. Each component represents a single structured piece of information. You can create multiple instances of the same component type when needed.\n\n***MANDATORY JSON RESPONSE FORMAT - ABSOLUTELY CRITICAL***:\n- WHEN DATA COMPONENTS ARE AVAILABLE, YOU MUST RESPOND IN JSON FORMAT ONLY\n- DO NOT respond with plain text when data components are defined\n- YOUR RESPONSE MUST BE STRUCTURED JSON WITH dataComponents ARRAY\n- THIS IS NON-NEGOTIABLE - JSON FORMAT IS REQUIRED\n\nCRITICAL JSON FORMATTING RULES - MUST FOLLOW EXACTLY:\n1. Each data component must include id, name, and props fields\n2. The id and name should match the exact component definition\n3. The props field contains the actual component data using exact property names from the schema\n4. NEVER omit the id and name fields\n\nCORRECT: [{\\"id\\": \\"component1\\", \\"name\\": \\"Component1\\", \\"props\\": {\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}, {\\"id\\": \\"component2\\", \\"name\\": \\"Component2\\", \\"props\\": {\\"field3\\": \\"value3\\"}}]\nWRONG: [{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}, {\\"field3\\": \\"value3\\"}]\n\nAVAILABLE DATA COMPONENTS: {{DATA_COMPONENTS_LIST}}">\n\n{{DATA_COMPONENTS_XML}}\n\n</data_components_section>';
5865
-
5866
- // templates/v1/phase2/data-component.xml?raw
5867
- var data_component_default = "<data-component>\n <name>{{COMPONENT_NAME}}</name>\n <description>{{COMPONENT_DESCRIPTION}}</description>\n <props>\n <schema>\n {{COMPONENT_PROPS_SCHEMA}}\n </schema>\n </props>\n</data-component> ";
5868
-
5869
6180
  // src/agents/versions/v1/Phase2Config.ts
5870
6181
  var Phase2Config = class {
5871
6182
  getArtifactCreationGuidance() {
@@ -5911,17 +6222,15 @@ When the same field names appear at different levels (like 'content', 'title', '
5911
6222
 
5912
6223
  CRITICAL: SELECTOR HIERARCHY
5913
6224
  - base_selector: Points to ONE specific item in the tool result
5914
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
5915
- - Example: If base="result.documents[?type=='api']" then summary_props uses "title" not "documents[0].title"
6225
+ - details_selector: Contains JMESPath selectors RELATIVE to the base selector
6226
+ - Example: If base="result.documents[?type=='api']" then details_selector uses "title" not "documents[0].title"
5916
6227
 
5917
6228
  \u274C WRONG EXAMPLE:
5918
6229
  {
5919
6230
  "base_selector": "result.content[?title=='Guide']",
5920
- "summary_props": {
6231
+ "details_selector": {
5921
6232
  "title": "Guide", // \u274C This is a literal value, not a selector!
5922
- "url": "result.content[?title=='Guide'].url" // \u274C This is absolute, not relative!
5923
- },
5924
- "full_props": {
6233
+ "url": "result.content[?title=='Guide'].url", // \u274C This is absolute, not relative!
5925
6234
  "description": "A comprehensive guide", // \u274C Literal value instead of selector!
5926
6235
  "content": "result.content[?title=='Guide'].content" // \u274C Absolute path instead of relative!
5927
6236
  }
@@ -5930,11 +6239,9 @@ CRITICAL: SELECTOR HIERARCHY
5930
6239
  \u2705 CORRECT EXAMPLE:
5931
6240
  {
5932
6241
  "base_selector": "result.content[?title=='Guide']",
5933
- "summary_props": {
6242
+ "details_selector": {
5934
6243
  "title": "title", // \u2705 Relative selector to get title field
5935
- "url": "url" // \u2705 Relative selector to get url field
5936
- },
5937
- "full_props": {
6244
+ "url": "url", // \u2705 Relative selector to get url field
5938
6245
  "description": "description", // \u2705 Relative selector
5939
6246
  "content": "content", // \u2705 Relative selector
5940
6247
  "metadata": "metadata.details" // \u2705 Relative selector with nesting
@@ -6020,8 +6327,7 @@ EXAMPLE STRUCTURED RESPONSE:
6020
6327
  "tool_call_id": "call_abc123",
6021
6328
  "type": "APIDoc",
6022
6329
  "base_selector": "result.documents[?type=='api']",
6023
- "summary_props": {"title": "metadata.title", "endpoint": "api.endpoint"},
6024
- "full_props": {"description": "content.description", "parameters": "spec.parameters", "examples": "examples.sample_code"}
6330
+ "details_selector": {"title": "metadata.title", "endpoint": "api.endpoint", "description": "content.description", "parameters": "spec.parameters", "examples": "examples.sample_code"}
6025
6331
  }
6026
6332
  },
6027
6333
  {
@@ -6101,14 +6407,14 @@ IMPORTANT GUIDELINES:
6101
6407
  return "";
6102
6408
  }
6103
6409
  const componentDescriptions = artifactComponents.map((ac) => {
6104
- const summaryProps = ac.summaryProps?.properties ? Object.entries(ac.summaryProps.properties).map(([key, value]) => ` - ${key}: ${value.description || "Field from tool result"}`).join("\n") : " No properties defined";
6105
- const fullProps = ac.fullProps?.properties ? Object.entries(ac.fullProps.properties).map(([key, value]) => ` - ${key}: ${value.description || "Field from tool result"}`).join("\n") : " No properties defined";
6410
+ const schemaProps = ac.props?.properties ? Object.entries(ac.props.properties).map(([key, value]) => {
6411
+ const inPreview = value.inPreview ? " [PREVIEW]" : " [FULL]";
6412
+ return ` - ${key}: ${value.description || "Field from tool result"}${inPreview}`;
6413
+ }).join("\n") : " No properties defined";
6106
6414
  return ` ArtifactCreate_${ac.name}:
6107
6415
  Description: ${ac.description || "Extract and structure data"}
6108
- Summary Properties:
6109
- ${summaryProps}
6110
- Full Properties:
6111
- ${fullProps}`;
6416
+ Schema Properties:
6417
+ ${schemaProps}`;
6112
6418
  }).join("\n\n");
6113
6419
  return `
6114
6420
  AVAILABLE ARTIFACT TYPES:
@@ -6122,8 +6428,14 @@ ${componentDescriptions}`;
6122
6428
  const dataComponentsDescription = dataComponents.map((dc) => `${dc.name}: ${dc.description}`).join(", ");
6123
6429
  const dataComponentsXml = dataComponents.map((dataComponent) => this.generateDataComponentXml(dataComponent)).join("\n ");
6124
6430
  let dataComponentsSection = data_components_default;
6125
- dataComponentsSection = dataComponentsSection.replace("{{DATA_COMPONENTS_LIST}}", dataComponentsDescription);
6126
- dataComponentsSection = dataComponentsSection.replace("{{DATA_COMPONENTS_XML}}", dataComponentsXml);
6431
+ dataComponentsSection = dataComponentsSection.replace(
6432
+ "{{DATA_COMPONENTS_LIST}}",
6433
+ dataComponentsDescription
6434
+ );
6435
+ dataComponentsSection = dataComponentsSection.replace(
6436
+ "{{DATA_COMPONENTS_XML}}",
6437
+ dataComponentsXml
6438
+ );
6127
6439
  return dataComponentsSection;
6128
6440
  }
6129
6441
  generateDataComponentXml(dataComponent) {
@@ -6195,14 +6507,21 @@ ${artifact_retrieval_guidance_default}
6195
6507
  * Assemble the complete Phase 2 system prompt for structured output generation
6196
6508
  */
6197
6509
  assemblePhase2Prompt(config) {
6198
- const { corePrompt, dataComponents, artifactComponents, hasArtifactComponents, hasGraphArtifactComponents, artifacts = [] } = config;
6510
+ const {
6511
+ corePrompt,
6512
+ dataComponents,
6513
+ artifactComponents,
6514
+ hasArtifactComponents,
6515
+ hasGraphArtifactComponents,
6516
+ artifacts = []
6517
+ } = config;
6199
6518
  let allDataComponents = [...dataComponents];
6200
6519
  if (hasArtifactComponents && artifactComponents) {
6201
6520
  const artifactCreateComponents = ArtifactCreateSchema.getDataComponents(
6202
6521
  "tenant",
6203
6522
  // placeholder - not used in Phase2
6204
6523
  "",
6205
- // placeholder - not used in Phase2
6524
+ // placeholder - not used in Phase2
6206
6525
  artifactComponents
6207
6526
  );
6208
6527
  allDataComponents = [...dataComponents, ...artifactCreateComponents];
@@ -6210,8 +6529,15 @@ ${artifact_retrieval_guidance_default}
6210
6529
  const dataComponentsSection = this.generateDataComponentsSection(allDataComponents);
6211
6530
  const artifactsSection = this.generateArtifactsSection(artifacts);
6212
6531
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
6213
- const artifactGuidance = this.getStructuredArtifactGuidance(hasArtifactComponents, artifactComponents, shouldShowReferencingRules);
6214
- const artifactTypes = this.getArtifactCreationInstructions(hasArtifactComponents, artifactComponents);
6532
+ const artifactGuidance = this.getStructuredArtifactGuidance(
6533
+ hasArtifactComponents,
6534
+ artifactComponents,
6535
+ shouldShowReferencingRules
6536
+ );
6537
+ const artifactTypes = this.getArtifactCreationInstructions(
6538
+ hasArtifactComponents,
6539
+ artifactComponents
6540
+ );
6215
6541
  let phase2Prompt = system_prompt_default2;
6216
6542
  phase2Prompt = phase2Prompt.replace("{{CORE_INSTRUCTIONS}}", corePrompt);
6217
6543
  phase2Prompt = phase2Prompt.replace("{{DATA_COMPONENTS_SECTION}}", dataComponentsSection);
@@ -6232,7 +6558,7 @@ function hasToolCallWithPrefix(prefix) {
6232
6558
  return false;
6233
6559
  };
6234
6560
  }
6235
- var logger16 = getLogger("Agent");
6561
+ var logger17 = getLogger("Agent");
6236
6562
  var CONSTANTS = {
6237
6563
  MAX_GENERATION_STEPS: 12,
6238
6564
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -6513,7 +6839,10 @@ var Agent = class {
6513
6839
  ]);
6514
6840
  }
6515
6841
  async getMcpTools(sessionId, streamRequestId) {
6516
- const tools = await Promise.all(this.config.tools?.map((tool3) => this.getMcpTool(tool3)) || []) || [];
6842
+ const mcpTools = this.config.tools?.filter((tool3) => {
6843
+ return tool3.config?.type === "mcp";
6844
+ }) || [];
6845
+ const tools = await Promise.all(mcpTools.map((tool3) => this.getMcpTool(tool3)) || []) || [];
6517
6846
  if (!sessionId) {
6518
6847
  const combinedTools = tools.reduce((acc, tool3) => {
6519
6848
  return Object.assign(acc, tool3);
@@ -6533,14 +6862,14 @@ var Agent = class {
6533
6862
  for (const toolSet of tools) {
6534
6863
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
6535
6864
  if (!isValidTool(originalTool)) {
6536
- logger16.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6865
+ logger17.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6537
6866
  continue;
6538
6867
  }
6539
6868
  const sessionWrappedTool = tool({
6540
6869
  description: originalTool.description,
6541
6870
  inputSchema: originalTool.inputSchema,
6542
6871
  execute: async (args, { toolCallId }) => {
6543
- logger16.debug({ toolName, toolCallId }, "MCP Tool Called");
6872
+ logger17.debug({ toolName, toolCallId }, "MCP Tool Called");
6544
6873
  try {
6545
6874
  const rawResult = await originalTool.execute(args, { toolCallId });
6546
6875
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -6554,7 +6883,7 @@ var Agent = class {
6554
6883
  });
6555
6884
  return { result: enhancedResult, toolCallId };
6556
6885
  } catch (error) {
6557
- logger16.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6886
+ logger17.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6558
6887
  throw error;
6559
6888
  }
6560
6889
  }
@@ -6573,6 +6902,9 @@ var Agent = class {
6573
6902
  * Convert database McpTool to builder MCPToolConfig format
6574
6903
  */
6575
6904
  convertToMCPToolConfig(tool3, agentToolRelationHeaders) {
6905
+ if (tool3.config.type !== "mcp") {
6906
+ throw new Error(`Cannot convert non-MCP tool to MCP config: ${tool3.id}`);
6907
+ }
6576
6908
  return {
6577
6909
  id: tool3.id,
6578
6910
  name: tool3.name,
@@ -6641,6 +6973,9 @@ var Agent = class {
6641
6973
  selectedTools
6642
6974
  );
6643
6975
  } else {
6976
+ if (tool3.config.type !== "mcp") {
6977
+ throw new Error(`Cannot build server config for non-MCP tool: ${tool3.id}`);
6978
+ }
6644
6979
  serverConfig = {
6645
6980
  type: tool3.config.mcp.transport?.type || MCPTransportType.streamableHttp,
6646
6981
  url: tool3.config.mcp.server.url,
@@ -6649,7 +6984,7 @@ var Agent = class {
6649
6984
  headers: agentToolRelationHeaders
6650
6985
  };
6651
6986
  }
6652
- logger16.info(
6987
+ logger17.info(
6653
6988
  {
6654
6989
  toolName: tool3.name,
6655
6990
  credentialReferenceId,
@@ -6674,7 +7009,7 @@ var Agent = class {
6674
7009
  this.mcpClientCache.set(cacheKey, client);
6675
7010
  } catch (error) {
6676
7011
  this.mcpConnectionLocks.delete(cacheKey);
6677
- logger16.error(
7012
+ logger17.error(
6678
7013
  {
6679
7014
  toolName: tool3.name,
6680
7015
  agentId: this.config.id,
@@ -6698,7 +7033,7 @@ var Agent = class {
6698
7033
  await client.connect();
6699
7034
  return client;
6700
7035
  } catch (error) {
6701
- logger16.error(
7036
+ logger17.error(
6702
7037
  {
6703
7038
  toolName: tool3.name,
6704
7039
  agentId: this.config.id,
@@ -6709,31 +7044,98 @@ var Agent = class {
6709
7044
  throw error;
6710
7045
  }
6711
7046
  }
6712
- getFunctionTools(streamRequestId) {
6713
- if (!this.config.functionTools) return {};
7047
+ async getFunctionTools(sessionId, streamRequestId) {
6714
7048
  const functionTools = {};
6715
- for (const funcTool of this.config.functionTools) {
6716
- const aiTool = tool({
6717
- description: funcTool.description,
6718
- inputSchema: funcTool.schema || z.object({}),
6719
- execute: funcTool.execute
7049
+ try {
7050
+ const toolsForAgent = await getToolsForAgent(dbClient_default)({
7051
+ scopes: {
7052
+ tenantId: this.config.tenantId || "default",
7053
+ projectId: this.config.projectId || "default",
7054
+ graphId: this.config.graphId,
7055
+ agentId: this.config.id
7056
+ }
6720
7057
  });
6721
- functionTools[funcTool.name] = this.wrapToolWithStreaming(
6722
- funcTool.name,
6723
- aiTool,
6724
- streamRequestId,
6725
- "tool"
6726
- );
7058
+ const toolsData = toolsForAgent.data || [];
7059
+ const functionToolDefs = toolsData.filter((tool3) => tool3.tool.config.type === "function");
7060
+ if (functionToolDefs.length === 0) {
7061
+ return functionTools;
7062
+ }
7063
+ const { LocalSandboxExecutor } = await import('./LocalSandboxExecutor-JI4X2Z3N.js');
7064
+ const sandboxExecutor = LocalSandboxExecutor.getInstance();
7065
+ for (const toolDef of functionToolDefs) {
7066
+ if (toolDef.tool.config?.type === "function") {
7067
+ const functionId = toolDef.tool.functionId;
7068
+ if (!functionId) {
7069
+ logger17.warn({ toolId: toolDef.tool.id }, "Function tool missing functionId reference");
7070
+ continue;
7071
+ }
7072
+ const functionData = await getFunction(dbClient_default)({
7073
+ functionId,
7074
+ scopes: {
7075
+ tenantId: this.config.tenantId || "default",
7076
+ projectId: this.config.projectId || "default"
7077
+ }
7078
+ });
7079
+ if (!functionData) {
7080
+ logger17.warn(
7081
+ { functionId, toolId: toolDef.tool.id },
7082
+ "Function not found in functions table"
7083
+ );
7084
+ continue;
7085
+ }
7086
+ const zodSchema = jsonSchemaToZod(functionData.inputSchema);
7087
+ const aiTool = tool({
7088
+ description: toolDef.tool.description || toolDef.tool.name,
7089
+ inputSchema: zodSchema,
7090
+ execute: async (args, { toolCallId }) => {
7091
+ logger17.debug(
7092
+ { toolName: toolDef.tool.name, toolCallId, args },
7093
+ "Function Tool Called"
7094
+ );
7095
+ try {
7096
+ const result = await sandboxExecutor.executeFunctionTool(toolDef.tool.id, args, {
7097
+ description: toolDef.tool.description || toolDef.tool.name,
7098
+ inputSchema: functionData.inputSchema || {},
7099
+ executeCode: functionData.executeCode,
7100
+ dependencies: functionData.dependencies || {}
7101
+ });
7102
+ toolSessionManager.recordToolResult(sessionId || "", {
7103
+ toolCallId,
7104
+ toolName: toolDef.tool.name,
7105
+ args,
7106
+ result,
7107
+ timestamp: Date.now()
7108
+ });
7109
+ return { result, toolCallId };
7110
+ } catch (error) {
7111
+ logger17.error(
7112
+ { toolName: toolDef.tool.name, toolCallId, error },
7113
+ "Function tool execution failed"
7114
+ );
7115
+ throw error;
7116
+ }
7117
+ }
7118
+ });
7119
+ functionTools[toolDef.tool.name] = this.wrapToolWithStreaming(
7120
+ toolDef.tool.name,
7121
+ aiTool,
7122
+ streamRequestId || "",
7123
+ "tool"
7124
+ );
7125
+ }
7126
+ }
7127
+ } catch (error) {
7128
+ logger17.error({ error }, "Failed to load function tools from database");
6727
7129
  }
6728
7130
  return functionTools;
6729
7131
  }
6730
7132
  /**
6731
7133
  * Get resolved context using ContextResolver - will return cached data or fetch fresh data as needed
6732
7134
  */
6733
- async getResolvedContext(conversationId, requestContext) {
7135
+ async getResolvedContext(conversationId, headers) {
6734
7136
  try {
6735
7137
  if (!this.config.contextConfigId) {
6736
- logger16.debug({ graphId: this.config.graphId }, "No context config found for graph");
7138
+ logger17.debug({ graphId: this.config.graphId }, "No context config found for graph");
6737
7139
  return null;
6738
7140
  }
6739
7141
  const contextConfig = await getContextConfigById(dbClient_default)({
@@ -6745,7 +7147,7 @@ var Agent = class {
6745
7147
  id: this.config.contextConfigId
6746
7148
  });
6747
7149
  if (!contextConfig) {
6748
- logger16.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7150
+ logger17.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
6749
7151
  return null;
6750
7152
  }
6751
7153
  if (!this.contextResolver) {
@@ -6754,7 +7156,7 @@ var Agent = class {
6754
7156
  const result = await this.contextResolver.resolve(contextConfig, {
6755
7157
  triggerEvent: "invocation",
6756
7158
  conversationId,
6757
- requestContext: requestContext || {},
7159
+ headers: headers || {},
6758
7160
  tenantId: this.config.tenantId
6759
7161
  });
6760
7162
  const contextWithBuiltins = {
@@ -6762,7 +7164,7 @@ var Agent = class {
6762
7164
  $now: (/* @__PURE__ */ new Date()).toISOString(),
6763
7165
  $env: process.env
6764
7166
  };
6765
- logger16.debug(
7167
+ logger17.debug(
6766
7168
  {
6767
7169
  conversationId,
6768
7170
  contextConfigId: contextConfig.id,
@@ -6776,7 +7178,7 @@ var Agent = class {
6776
7178
  );
6777
7179
  return contextWithBuiltins;
6778
7180
  } catch (error) {
6779
- logger16.error(
7181
+ logger17.error(
6780
7182
  {
6781
7183
  conversationId,
6782
7184
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6800,7 +7202,7 @@ var Agent = class {
6800
7202
  });
6801
7203
  return graphDefinition?.graphPrompt || void 0;
6802
7204
  } catch (error) {
6803
- logger16.warn(
7205
+ logger17.warn(
6804
7206
  {
6805
7207
  graphId: this.config.graphId,
6806
7208
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6829,7 +7231,7 @@ var Agent = class {
6829
7231
  (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
6830
7232
  );
6831
7233
  } catch (error) {
6832
- logger16.warn(
7234
+ logger17.warn(
6833
7235
  {
6834
7236
  graphId: this.config.graphId,
6835
7237
  tenantId: this.config.tenantId,
@@ -6858,7 +7260,7 @@ var Agent = class {
6858
7260
  preserveUnresolved: false
6859
7261
  });
6860
7262
  } catch (error) {
6861
- logger16.error(
7263
+ logger17.error(
6862
7264
  {
6863
7265
  conversationId,
6864
7266
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6905,7 +7307,7 @@ var Agent = class {
6905
7307
  preserveUnresolved: false
6906
7308
  });
6907
7309
  } catch (error) {
6908
- logger16.error(
7310
+ logger17.error(
6909
7311
  {
6910
7312
  conversationId,
6911
7313
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6917,9 +7319,24 @@ var Agent = class {
6917
7319
  }
6918
7320
  const streamRequestId = runtimeContext?.metadata?.streamRequestId;
6919
7321
  const mcpTools = await this.getMcpTools(void 0, streamRequestId);
6920
- const functionTools = this.getFunctionTools(streamRequestId);
7322
+ const functionTools = await this.getFunctionTools(streamRequestId || "");
6921
7323
  const relationTools = this.getRelationTools(runtimeContext);
6922
7324
  const allTools = { ...mcpTools, ...functionTools, ...relationTools };
7325
+ logger17.info(
7326
+ {
7327
+ mcpTools: Object.keys(mcpTools),
7328
+ functionTools: Object.keys(functionTools),
7329
+ relationTools: Object.keys(relationTools),
7330
+ allTools: Object.keys(allTools),
7331
+ functionToolsDetails: Object.entries(functionTools).map(([name, tool3]) => ({
7332
+ name,
7333
+ hasExecute: typeof tool3.execute === "function",
7334
+ hasDescription: !!tool3.description,
7335
+ hasInputSchema: !!tool3.inputSchema
7336
+ }))
7337
+ },
7338
+ "Tools loaded for agent"
7339
+ );
6923
7340
  const toolDefinitions = Object.entries(allTools).map(([name, tool3]) => ({
6924
7341
  name,
6925
7342
  description: tool3.description || "",
@@ -6944,7 +7361,7 @@ var Agent = class {
6944
7361
  preserveUnresolved: false
6945
7362
  });
6946
7363
  } catch (error) {
6947
- logger16.error(
7364
+ logger17.error(
6948
7365
  {
6949
7366
  conversationId,
6950
7367
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6971,23 +7388,29 @@ var Agent = class {
6971
7388
  }
6972
7389
  getArtifactTools() {
6973
7390
  return tool({
6974
- description: "Call this tool to get the artifact with the given artifactId. Only retrieve this when the description of the artifact is insufficient to understand the artifact and you need to see the actual artifact for more context. Please refrain from using this tool unless absolutely necessary.",
7391
+ description: "Call this tool to get the complete artifact data with the given artifactId. This retrieves the full artifact content (not just the summary). Only use this when you need the complete artifact data and the summary shown in your context is insufficient.",
6975
7392
  inputSchema: z.object({
6976
- artifactId: z.string().describe("The unique identifier of the artifact to get.")
7393
+ artifactId: z.string().describe("The unique identifier of the artifact to get."),
7394
+ toolCallId: z.string().describe("The tool call ID associated with this artifact.")
6977
7395
  }),
6978
- execute: async ({ artifactId }) => {
6979
- logger16.info({ artifactId }, "get_artifact executed");
6980
- const artifact = await getLedgerArtifacts(dbClient_default)({
6981
- scopes: {
6982
- tenantId: this.config.tenantId,
6983
- projectId: this.config.projectId
6984
- },
6985
- artifactId
6986
- });
6987
- if (!artifact) {
6988
- throw new Error(`Artifact ${artifactId} not found`);
7396
+ execute: async ({ artifactId, toolCallId }) => {
7397
+ logger17.info({ artifactId, toolCallId }, "get_artifact_full executed");
7398
+ const streamRequestId = this.getStreamRequestId();
7399
+ const artifactService = graphSessionManager.getArtifactService(streamRequestId);
7400
+ if (!artifactService) {
7401
+ throw new Error(`ArtifactService not found for session ${streamRequestId}`);
7402
+ }
7403
+ const artifactData = await artifactService.getArtifactFull(artifactId, toolCallId);
7404
+ if (!artifactData) {
7405
+ throw new Error(`Artifact ${artifactId} with toolCallId ${toolCallId} not found`);
6989
7406
  }
6990
- return { artifact: artifact[0] };
7407
+ return {
7408
+ artifactId: artifactData.artifactId,
7409
+ name: artifactData.name,
7410
+ description: artifactData.description,
7411
+ type: artifactData.type,
7412
+ data: artifactData.data
7413
+ };
6991
7414
  }
6992
7415
  });
6993
7416
  }
@@ -7005,7 +7428,7 @@ var Agent = class {
7005
7428
  });
7006
7429
  }
7007
7430
  // Provide a default tool set that is always available to the agent.
7008
- async getDefaultTools(sessionId, streamRequestId) {
7431
+ async getDefaultTools(_sessionId, streamRequestId) {
7009
7432
  const defaultTools = {};
7010
7433
  if (await this.graphHasArtifactComponents()) {
7011
7434
  defaultTools.get_reference_artifact = this.getArtifactTools();
@@ -7093,13 +7516,19 @@ var Agent = class {
7093
7516
  if (Array.isArray(obj)) {
7094
7517
  obj.slice(0, 3).forEach((item) => {
7095
7518
  if (item && typeof item === "object") {
7096
- Object.keys(item).forEach((key) => fields.add(key));
7519
+ Object.keys(item).forEach((key) => {
7520
+ fields.add(key);
7521
+ });
7097
7522
  }
7098
7523
  });
7099
7524
  } else if (obj && typeof obj === "object") {
7100
- Object.keys(obj).forEach((key) => fields.add(key));
7525
+ Object.keys(obj).forEach((key) => {
7526
+ fields.add(key);
7527
+ });
7101
7528
  Object.values(obj).forEach((value) => {
7102
- findCommonFields(value, depth + 1).forEach((field) => fields.add(field));
7529
+ findCommonFields(value, depth + 1).forEach((field) => {
7530
+ fields.add(field);
7531
+ });
7103
7532
  });
7104
7533
  }
7105
7534
  return fields;
@@ -7198,8 +7627,7 @@ var Agent = class {
7198
7627
  artifactGuidance: {
7199
7628
  creationFirst: "\u{1F6A8} CRITICAL: Artifacts must be CREATED before they can be referenced. Use ArtifactCreate_[Type] components FIRST, then reference with Artifact components only if citing the SAME artifact again.",
7200
7629
  baseSelector: `\u{1F3AF} CRITICAL: Use base_selector to navigate to ONE specific item. For deeply nested structures with repeated keys, use full paths with specific filtering (e.g., "result.data.content.items[?type=='guide' && status=='active']")`,
7201
- summaryProps: '\u{1F4DD} Use relative selectors from that item (e.g., "title", "metadata.category", "properties.status")',
7202
- fullProps: '\u{1F4D6} Use relative selectors for detailed data (e.g., "content.details", "specifications.data", "attributes")',
7630
+ detailsSelector: '\u{1F4DD} Use relative selectors for specific fields (e.g., "title", "metadata.category", "properties.status", "content.details")',
7203
7631
  avoidLiterals: "\u274C NEVER use literal values - always use field selectors to extract from data",
7204
7632
  avoidArrays: "\u2728 ALWAYS filter arrays to single items using [?condition] - NEVER use [*] notation which returns arrays",
7205
7633
  nestedKeys: "\u{1F511} For structures with repeated keys (like result.content.data.content.items.content), use full paths with filtering at each level",
@@ -7226,7 +7654,7 @@ var Agent = class {
7226
7654
  };
7227
7655
  return enhanced;
7228
7656
  } catch (error) {
7229
- logger16.warn({ error }, "Failed to enhance tool result with structure hints");
7657
+ logger17.warn({ error }, "Failed to enhance tool result with structure hints");
7230
7658
  return result;
7231
7659
  }
7232
7660
  }
@@ -7241,7 +7669,7 @@ var Agent = class {
7241
7669
  }
7242
7670
  });
7243
7671
  } catch (error) {
7244
- logger16.error(
7672
+ logger17.error(
7245
7673
  { error, graphId: this.config.graphId },
7246
7674
  "Failed to check graph artifact components"
7247
7675
  );
@@ -7284,7 +7712,7 @@ var Agent = class {
7284
7712
  // Normal prompt with data components
7285
7713
  this.buildSystemPrompt(runtimeContext, true),
7286
7714
  // Thinking prompt without data components
7287
- Promise.resolve(this.getFunctionTools(streamRequestId)),
7715
+ this.getFunctionTools(sessionId, streamRequestId),
7288
7716
  Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
7289
7717
  this.getDefaultTools(sessionId, streamRequestId)
7290
7718
  ]);
@@ -7342,7 +7770,7 @@ var Agent = class {
7342
7770
  const configuredTimeout = modelSettings.maxDuration ? Math.min(modelSettings.maxDuration * 1e3, MAX_ALLOWED_TIMEOUT_MS) : shouldStreamPhase1 ? CONSTANTS.PHASE_1_TIMEOUT_MS : CONSTANTS.NON_STREAMING_PHASE_1_TIMEOUT_MS;
7343
7771
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
7344
7772
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
7345
- logger16.warn(
7773
+ logger17.warn(
7346
7774
  {
7347
7775
  requestedTimeout: modelSettings.maxDuration * 1e3,
7348
7776
  appliedTimeout: timeoutMs,
@@ -7384,7 +7812,7 @@ var Agent = class {
7384
7812
  }
7385
7813
  );
7386
7814
  } catch (error) {
7387
- logger16.debug({ error }, "Failed to track agent reasoning");
7815
+ logger17.debug({ error }, "Failed to track agent reasoning");
7388
7816
  }
7389
7817
  }
7390
7818
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7488,7 +7916,7 @@ var Agent = class {
7488
7916
  }
7489
7917
  );
7490
7918
  } catch (error) {
7491
- logger16.debug({ error }, "Failed to track agent reasoning");
7919
+ logger17.debug({ error }, "Failed to track agent reasoning");
7492
7920
  }
7493
7921
  }
7494
7922
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7780,7 +8208,7 @@ ${output}${structureHintsFormatted}`;
7780
8208
  };
7781
8209
 
7782
8210
  // src/agents/generateTaskHandler.ts
7783
- var logger17 = getLogger("generateTaskHandler");
8211
+ var logger18 = getLogger("generateTaskHandler");
7784
8212
  var createTaskHandler = (config, credentialStoreRegistry) => {
7785
8213
  return async (task) => {
7786
8214
  try {
@@ -7833,7 +8261,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7833
8261
  }
7834
8262
  })
7835
8263
  ]);
7836
- logger17.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8264
+ logger18.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
7837
8265
  const enhancedInternalRelations = await Promise.all(
7838
8266
  internalRelations.map(async (relation) => {
7839
8267
  try {
@@ -7862,7 +8290,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7862
8290
  return { ...relation, description: enhancedDescription };
7863
8291
  }
7864
8292
  } catch (error) {
7865
- logger17.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
8293
+ logger18.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
7866
8294
  }
7867
8295
  return relation;
7868
8296
  })
@@ -7957,12 +8385,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7957
8385
  },
7958
8386
  credentialStoreRegistry
7959
8387
  );
8388
+ const artifactStreamRequestId = task.context?.metadata?.streamRequestId;
8389
+ if (artifactStreamRequestId && artifactComponents.length > 0) {
8390
+ graphSessionManager.updateArtifactComponents(artifactStreamRequestId, artifactComponents);
8391
+ }
7960
8392
  let contextId = task.context?.conversationId;
7961
8393
  if (!contextId || contextId === "default" || contextId === "") {
7962
8394
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
7963
8395
  if (taskIdMatch) {
7964
8396
  contextId = taskIdMatch[1];
7965
- logger17.info(
8397
+ logger18.info(
7966
8398
  {
7967
8399
  taskId: task.id,
7968
8400
  extractedContextId: contextId,
@@ -7978,7 +8410,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7978
8410
  const isDelegation = task.context?.metadata?.isDelegation === true;
7979
8411
  agent.setDelegationStatus(isDelegation);
7980
8412
  if (isDelegation) {
7981
- logger17.info(
8413
+ logger18.info(
7982
8414
  { agentId: config.agentId, taskId: task.id },
7983
8415
  "Delegated agent - streaming disabled"
7984
8416
  );
@@ -8200,7 +8632,7 @@ async function getRegisteredGraph(executionContext) {
8200
8632
 
8201
8633
  // src/routes/agents.ts
8202
8634
  var app = new OpenAPIHono();
8203
- var logger18 = getLogger("agents");
8635
+ var logger19 = getLogger("agents");
8204
8636
  app.openapi(
8205
8637
  createRoute({
8206
8638
  method: "get",
@@ -8238,7 +8670,7 @@ app.openapi(
8238
8670
  tracestate: c.req.header("tracestate"),
8239
8671
  baggage: c.req.header("baggage")
8240
8672
  };
8241
- logger18.info(
8673
+ logger19.info(
8242
8674
  {
8243
8675
  otelHeaders,
8244
8676
  path: c.req.path,
@@ -8250,7 +8682,7 @@ app.openapi(
8250
8682
  const { tenantId, projectId, graphId, agentId } = executionContext;
8251
8683
  console.dir("executionContext", executionContext);
8252
8684
  if (agentId) {
8253
- logger18.info(
8685
+ logger19.info(
8254
8686
  {
8255
8687
  message: "getRegisteredAgent (agent-level)",
8256
8688
  tenantId,
@@ -8262,7 +8694,7 @@ app.openapi(
8262
8694
  );
8263
8695
  const credentialStores = c.get("credentialStores");
8264
8696
  const agent = await getRegisteredAgent(executionContext, credentialStores);
8265
- logger18.info({ agent }, "agent registered: well-known agent.json");
8697
+ logger19.info({ agent }, "agent registered: well-known agent.json");
8266
8698
  if (!agent) {
8267
8699
  throw createApiError({
8268
8700
  code: "not_found",
@@ -8271,7 +8703,7 @@ app.openapi(
8271
8703
  }
8272
8704
  return c.json(agent.agentCard);
8273
8705
  } else {
8274
- logger18.info(
8706
+ logger19.info(
8275
8707
  {
8276
8708
  message: "getRegisteredGraph (graph-level)",
8277
8709
  tenantId,
@@ -8297,7 +8729,7 @@ app.post("/a2a", async (c) => {
8297
8729
  tracestate: c.req.header("tracestate"),
8298
8730
  baggage: c.req.header("baggage")
8299
8731
  };
8300
- logger18.info(
8732
+ logger19.info(
8301
8733
  {
8302
8734
  otelHeaders,
8303
8735
  path: c.req.path,
@@ -8308,7 +8740,7 @@ app.post("/a2a", async (c) => {
8308
8740
  const executionContext = getRequestExecutionContext(c);
8309
8741
  const { tenantId, projectId, graphId, agentId } = executionContext;
8310
8742
  if (agentId) {
8311
- logger18.info(
8743
+ logger19.info(
8312
8744
  {
8313
8745
  message: "a2a (agent-level)",
8314
8746
  tenantId,
@@ -8332,7 +8764,7 @@ app.post("/a2a", async (c) => {
8332
8764
  }
8333
8765
  return a2aHandler(c, agent);
8334
8766
  } else {
8335
- logger18.info(
8767
+ logger19.info(
8336
8768
  {
8337
8769
  message: "a2a (graph-level)",
8338
8770
  tenantId,
@@ -8381,14 +8813,14 @@ app.post("/a2a", async (c) => {
8381
8813
  }
8382
8814
  });
8383
8815
  var agents_default = app;
8384
- var logger19 = getLogger("Transfer");
8816
+ var logger20 = getLogger("Transfer");
8385
8817
  async function executeTransfer({
8386
8818
  tenantId,
8387
8819
  threadId,
8388
8820
  projectId,
8389
8821
  targetAgentId
8390
8822
  }) {
8391
- logger19.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8823
+ logger20.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8392
8824
  await setActiveAgentForThread(dbClient_default)({
8393
8825
  scopes: { tenantId, projectId },
8394
8826
  threadId,
@@ -8970,7 +9402,7 @@ function createMCPStreamHelper() {
8970
9402
  }
8971
9403
 
8972
9404
  // src/handlers/executionHandler.ts
8973
- var logger20 = getLogger("ExecutionHandler");
9405
+ var logger21 = getLogger("ExecutionHandler");
8974
9406
  var ExecutionHandler = class {
8975
9407
  constructor() {
8976
9408
  // Hardcoded error limit - separate from configurable stopWhen
@@ -9006,7 +9438,7 @@ var ExecutionHandler = class {
9006
9438
  if (emitOperations) {
9007
9439
  graphSessionManager.enableEmitOperations(requestId2);
9008
9440
  }
9009
- logger20.info(
9441
+ logger21.info(
9010
9442
  { sessionId: requestId2, graphId, conversationId, emitOperations },
9011
9443
  "Created GraphSession for message execution"
9012
9444
  );
@@ -9021,7 +9453,7 @@ var ExecutionHandler = class {
9021
9453
  );
9022
9454
  }
9023
9455
  } catch (error) {
9024
- logger20.error(
9456
+ logger21.error(
9025
9457
  {
9026
9458
  error: error instanceof Error ? error.message : "Unknown error",
9027
9459
  stack: error instanceof Error ? error.stack : void 0
@@ -9037,7 +9469,7 @@ var ExecutionHandler = class {
9037
9469
  try {
9038
9470
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
9039
9471
  const taskId = `task_${conversationId}-${requestId2}`;
9040
- logger20.info(
9472
+ logger21.info(
9041
9473
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
9042
9474
  "Attempting to create or reuse existing task"
9043
9475
  );
@@ -9061,7 +9493,7 @@ var ExecutionHandler = class {
9061
9493
  agent_id: currentAgentId
9062
9494
  }
9063
9495
  });
9064
- logger20.info(
9496
+ logger21.info(
9065
9497
  {
9066
9498
  taskId,
9067
9499
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -9070,27 +9502,27 @@ var ExecutionHandler = class {
9070
9502
  );
9071
9503
  } catch (error) {
9072
9504
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
9073
- logger20.info(
9505
+ logger21.info(
9074
9506
  { taskId, error: error.message },
9075
9507
  "Task already exists, fetching existing task"
9076
9508
  );
9077
9509
  const existingTask = await getTask(dbClient_default)({ id: taskId });
9078
9510
  if (existingTask) {
9079
9511
  task = existingTask;
9080
- logger20.info(
9512
+ logger21.info(
9081
9513
  { taskId, existingTask },
9082
9514
  "Successfully reused existing task from race condition"
9083
9515
  );
9084
9516
  } else {
9085
- logger20.error({ taskId, error }, "Task constraint failed but task not found");
9517
+ logger21.error({ taskId, error }, "Task constraint failed but task not found");
9086
9518
  throw error;
9087
9519
  }
9088
9520
  } else {
9089
- logger20.error({ taskId, error }, "Failed to create task due to non-constraint error");
9521
+ logger21.error({ taskId, error }, "Failed to create task due to non-constraint error");
9090
9522
  throw error;
9091
9523
  }
9092
9524
  }
9093
- logger20.debug(
9525
+ logger21.debug(
9094
9526
  {
9095
9527
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9096
9528
  executionType: "create_initial_task",
@@ -9108,7 +9540,7 @@ var ExecutionHandler = class {
9108
9540
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
9109
9541
  while (iterations < maxTransfers) {
9110
9542
  iterations++;
9111
- logger20.info(
9543
+ logger21.info(
9112
9544
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
9113
9545
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
9114
9546
  );
@@ -9116,10 +9548,10 @@ var ExecutionHandler = class {
9116
9548
  scopes: { tenantId, projectId },
9117
9549
  conversationId
9118
9550
  });
9119
- logger20.info({ activeAgent }, "activeAgent");
9551
+ logger21.info({ activeAgent }, "activeAgent");
9120
9552
  if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
9121
9553
  currentAgentId = activeAgent.activeAgentId;
9122
- logger20.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9554
+ logger21.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9123
9555
  }
9124
9556
  const agentBaseUrl = `${baseUrl}/agents`;
9125
9557
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -9160,13 +9592,13 @@ var ExecutionHandler = class {
9160
9592
  });
9161
9593
  if (!messageResponse?.result) {
9162
9594
  errorCount++;
9163
- logger20.error(
9595
+ logger21.error(
9164
9596
  { currentAgentId, iterations, errorCount },
9165
9597
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9166
9598
  );
9167
9599
  if (errorCount >= this.MAX_ERRORS) {
9168
9600
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9169
- logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9601
+ logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9170
9602
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9171
9603
  if (task) {
9172
9604
  await updateTask(dbClient_default)({
@@ -9191,7 +9623,7 @@ var ExecutionHandler = class {
9191
9623
  const transferResponse = messageResponse.result;
9192
9624
  const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
9193
9625
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
9194
- logger20.info({ targetAgentId, transferReason }, "transfer response");
9626
+ logger21.info({ targetAgentId, transferReason }, "transfer response");
9195
9627
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
9196
9628
  const { success, targetAgentId: newAgentId } = await executeTransfer({
9197
9629
  projectId,
@@ -9202,7 +9634,7 @@ var ExecutionHandler = class {
9202
9634
  if (success) {
9203
9635
  fromAgentId = currentAgentId;
9204
9636
  currentAgentId = newAgentId;
9205
- logger20.info(
9637
+ logger21.info(
9206
9638
  {
9207
9639
  transferFrom: fromAgentId,
9208
9640
  transferTo: currentAgentId,
@@ -9220,7 +9652,7 @@ var ExecutionHandler = class {
9220
9652
  const graphSessionData = graphSessionManager.getSession(requestId2);
9221
9653
  if (graphSessionData) {
9222
9654
  const sessionSummary = graphSessionData.getSummary();
9223
- logger20.info(sessionSummary, "GraphSession data after completion");
9655
+ logger21.info(sessionSummary, "GraphSession data after completion");
9224
9656
  }
9225
9657
  let textContent = "";
9226
9658
  for (const part of responseParts) {
@@ -9274,22 +9706,22 @@ var ExecutionHandler = class {
9274
9706
  }
9275
9707
  });
9276
9708
  const updateTaskEnd = Date.now();
9277
- logger20.info(
9709
+ logger21.info(
9278
9710
  { duration: updateTaskEnd - updateTaskStart },
9279
9711
  "Completed updateTask operation"
9280
9712
  );
9281
9713
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
9282
9714
  await sseHelper.complete();
9283
- logger20.info({}, "Ending GraphSession and cleaning up");
9715
+ logger21.info({}, "Ending GraphSession and cleaning up");
9284
9716
  graphSessionManager.endSession(requestId2);
9285
- logger20.info({}, "Cleaning up streamHelper");
9717
+ logger21.info({}, "Cleaning up streamHelper");
9286
9718
  unregisterStreamHelper(requestId2);
9287
9719
  let response;
9288
9720
  if (sseHelper instanceof MCPStreamHelper) {
9289
9721
  const captured = sseHelper.getCapturedResponse();
9290
9722
  response = captured.text || "No response content";
9291
9723
  }
9292
- logger20.info({}, "ExecutionHandler returning success");
9724
+ logger21.info({}, "ExecutionHandler returning success");
9293
9725
  return { success: true, iterations, response };
9294
9726
  } catch (error) {
9295
9727
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -9300,13 +9732,13 @@ var ExecutionHandler = class {
9300
9732
  });
9301
9733
  }
9302
9734
  errorCount++;
9303
- logger20.warn(
9735
+ logger21.warn(
9304
9736
  { iterations, errorCount },
9305
9737
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9306
9738
  );
9307
9739
  if (errorCount >= this.MAX_ERRORS) {
9308
9740
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9309
- logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9741
+ logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9310
9742
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9311
9743
  if (task) {
9312
9744
  await updateTask(dbClient_default)({
@@ -9327,7 +9759,7 @@ var ExecutionHandler = class {
9327
9759
  }
9328
9760
  }
9329
9761
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
9330
- logger20.error({ maxTransfers, iterations }, errorMessage);
9762
+ logger21.error({ maxTransfers, iterations }, errorMessage);
9331
9763
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
9332
9764
  if (task) {
9333
9765
  await updateTask(dbClient_default)({
@@ -9346,7 +9778,7 @@ var ExecutionHandler = class {
9346
9778
  unregisterStreamHelper(requestId2);
9347
9779
  return { success: false, error: errorMessage, iterations };
9348
9780
  } catch (error) {
9349
- logger20.error({ error }, "Error in execution handler");
9781
+ logger21.error({ error }, "Error in execution handler");
9350
9782
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
9351
9783
  await sseHelper.writeOperation(
9352
9784
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -9373,7 +9805,7 @@ var ExecutionHandler = class {
9373
9805
 
9374
9806
  // src/routes/chat.ts
9375
9807
  var app2 = new OpenAPIHono();
9376
- var logger21 = getLogger("completionsHandler");
9808
+ var logger22 = getLogger("completionsHandler");
9377
9809
  var chatCompletionsRoute = createRoute({
9378
9810
  method: "post",
9379
9811
  path: "/completions",
@@ -9414,8 +9846,8 @@ var chatCompletionsRoute = createRoute({
9414
9846
  conversationId: z.string().optional().describe("Conversation ID for multi-turn chat"),
9415
9847
  tools: z.array(z.string()).optional().describe("Available tools"),
9416
9848
  runConfig: z.record(z.string(), z.unknown()).optional().describe("Run configuration"),
9417
- requestContext: z.record(z.string(), z.unknown()).optional().describe(
9418
- "Context data for template processing (validated against context config schema)"
9849
+ headers: z.record(z.string(), z.unknown()).optional().describe(
9850
+ "Headers data for template processing (validated against context config schema)"
9419
9851
  )
9420
9852
  })
9421
9853
  }
@@ -9491,7 +9923,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9491
9923
  tracestate: c.req.header("tracestate"),
9492
9924
  baggage: c.req.header("baggage")
9493
9925
  };
9494
- logger21.info(
9926
+ logger22.info(
9495
9927
  {
9496
9928
  otelHeaders,
9497
9929
  path: c.req.path,
@@ -9573,18 +10005,18 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9573
10005
  message: "Agent not found"
9574
10006
  });
9575
10007
  }
9576
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
10008
+ const validatedContext = c.get("validatedContext") || body.headers || {};
9577
10009
  const credentialStores = c.get("credentialStores");
9578
10010
  await handleContextResolution({
9579
10011
  tenantId,
9580
10012
  projectId,
9581
10013
  graphId,
9582
10014
  conversationId,
9583
- requestContext: validatedContext,
10015
+ headers: validatedContext,
9584
10016
  dbClient: dbClient_default,
9585
10017
  credentialStores
9586
10018
  });
9587
- logger21.info(
10019
+ logger22.info(
9588
10020
  {
9589
10021
  tenantId,
9590
10022
  projectId,
@@ -9593,7 +10025,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9593
10025
  defaultAgentId,
9594
10026
  activeAgentId: activeAgent?.activeAgentId || "none",
9595
10027
  hasContextConfig: !!agentGraph.contextConfigId,
9596
- hasRequestContext: !!body.requestContext,
10028
+ hasHeaders: !!body.headers,
9597
10029
  hasValidatedContext: !!validatedContext,
9598
10030
  validatedContextKeys: Object.keys(validatedContext)
9599
10031
  },
@@ -9632,7 +10064,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9632
10064
  try {
9633
10065
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
9634
10066
  await sseHelper.writeRole();
9635
- logger21.info({ agentId }, "Starting execution");
10067
+ logger22.info({ agentId }, "Starting execution");
9636
10068
  const emitOperationsHeader = c.req.header("x-emit-operations");
9637
10069
  const emitOperations = emitOperationsHeader === "true";
9638
10070
  const executionHandler = new ExecutionHandler();
@@ -9645,7 +10077,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9645
10077
  sseHelper,
9646
10078
  emitOperations
9647
10079
  });
9648
- logger21.info(
10080
+ logger22.info(
9649
10081
  { result },
9650
10082
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
9651
10083
  );
@@ -9659,7 +10091,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9659
10091
  }
9660
10092
  await sseHelper.complete();
9661
10093
  } catch (error) {
9662
- logger21.error(
10094
+ logger22.error(
9663
10095
  {
9664
10096
  error: error instanceof Error ? error.message : error,
9665
10097
  stack: error instanceof Error ? error.stack : void 0
@@ -9676,12 +10108,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9676
10108
  );
9677
10109
  await sseHelper.complete();
9678
10110
  } catch (streamError) {
9679
- logger21.error({ streamError }, "Failed to write error to stream");
10111
+ logger22.error({ streamError }, "Failed to write error to stream");
9680
10112
  }
9681
10113
  }
9682
10114
  });
9683
10115
  } catch (error) {
9684
- logger21.error(
10116
+ logger22.error(
9685
10117
  {
9686
10118
  error: error instanceof Error ? error.message : error,
9687
10119
  stack: error instanceof Error ? error.stack : void 0
@@ -9705,7 +10137,7 @@ var getMessageText = (content) => {
9705
10137
  };
9706
10138
  var chat_default = app2;
9707
10139
  var app3 = new OpenAPIHono();
9708
- var logger22 = getLogger("chatDataStream");
10140
+ var logger23 = getLogger("chatDataStream");
9709
10141
  var chatDataStreamRoute = createRoute({
9710
10142
  method: "post",
9711
10143
  path: "/chat",
@@ -9736,7 +10168,7 @@ var chatDataStreamRoute = createRoute({
9736
10168
  ),
9737
10169
  id: z$1.string().optional(),
9738
10170
  conversationId: z$1.string().optional(),
9739
- requestContext: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Context data for template processing")
10171
+ headers: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Headers data for template processing")
9740
10172
  })
9741
10173
  }
9742
10174
  }
@@ -9809,20 +10241,20 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9809
10241
  message: "Agent not found"
9810
10242
  });
9811
10243
  }
9812
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
10244
+ const validatedContext = c.get("validatedContext") || body.headers || {};
9813
10245
  const credentialStores = c.get("credentialStores");
9814
10246
  await handleContextResolution({
9815
10247
  tenantId,
9816
10248
  projectId,
9817
10249
  graphId,
9818
10250
  conversationId,
9819
- requestContext: validatedContext,
10251
+ headers: validatedContext,
9820
10252
  dbClient: dbClient_default,
9821
10253
  credentialStores
9822
10254
  });
9823
10255
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
9824
10256
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
9825
- logger22.info({ userText, lastUserMessage }, "userText");
10257
+ logger23.info({ userText, lastUserMessage }, "userText");
9826
10258
  const messageSpan = trace.getActiveSpan();
9827
10259
  if (messageSpan) {
9828
10260
  messageSpan.setAttributes({
@@ -9867,7 +10299,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9867
10299
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
9868
10300
  }
9869
10301
  } catch (err) {
9870
- logger22.error({ err }, "Streaming error");
10302
+ logger23.error({ err }, "Streaming error");
9871
10303
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
9872
10304
  } finally {
9873
10305
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -9888,7 +10320,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9888
10320
  )
9889
10321
  );
9890
10322
  } catch (error) {
9891
- logger22.error({ error }, "chatDataStream error");
10323
+ logger23.error({ error }, "chatDataStream error");
9892
10324
  throw createApiError({
9893
10325
  code: "internal_server_error",
9894
10326
  message: "Failed to process chat completion"
@@ -9899,7 +10331,7 @@ var chatDataStream_default = app3;
9899
10331
  function createMCPSchema(schema) {
9900
10332
  return schema;
9901
10333
  }
9902
- var logger23 = getLogger("mcp");
10334
+ var logger24 = getLogger("mcp");
9903
10335
  var _MockResponseSingleton = class _MockResponseSingleton {
9904
10336
  constructor() {
9905
10337
  __publicField(this, "mockRes");
@@ -9954,21 +10386,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
9954
10386
  id: 0
9955
10387
  });
9956
10388
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
9957
- logger23.info({ sessionId }, "Spoofing initialization message to set transport state");
10389
+ logger24.info({ sessionId }, "Spoofing initialization message to set transport state");
9958
10390
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
9959
10391
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
9960
10392
  try {
9961
10393
  await transport.handleRequest(req, mockRes, spoofInitMessage);
9962
- logger23.info({ sessionId }, "Successfully spoofed initialization");
10394
+ logger24.info({ sessionId }, "Successfully spoofed initialization");
9963
10395
  } catch (spoofError) {
9964
- logger23.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
10396
+ logger24.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
9965
10397
  }
9966
10398
  };
9967
10399
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9968
10400
  const sessionId = req.headers["mcp-session-id"];
9969
- logger23.info({ sessionId }, "Received MCP session ID");
10401
+ logger24.info({ sessionId }, "Received MCP session ID");
9970
10402
  if (!sessionId) {
9971
- logger23.info({ body }, "Missing session ID");
10403
+ logger24.info({ body }, "Missing session ID");
9972
10404
  res.writeHead(400).end(
9973
10405
  JSON.stringify({
9974
10406
  jsonrpc: "2.0",
@@ -9994,7 +10426,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9994
10426
  scopes: { tenantId, projectId },
9995
10427
  conversationId: sessionId
9996
10428
  });
9997
- logger23.info(
10429
+ logger24.info(
9998
10430
  {
9999
10431
  sessionId,
10000
10432
  conversationFound: !!conversation,
@@ -10005,7 +10437,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10005
10437
  "Conversation lookup result"
10006
10438
  );
10007
10439
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
10008
- logger23.info(
10440
+ logger24.info(
10009
10441
  { sessionId, conversationId: conversation?.id },
10010
10442
  "MCP session not found or invalid"
10011
10443
  );
@@ -10066,7 +10498,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10066
10498
  requestId: requestId2,
10067
10499
  sseHelper: mcpStreamHelper
10068
10500
  });
10069
- logger23.info(
10501
+ logger24.info(
10070
10502
  { result },
10071
10503
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10072
10504
  );
@@ -10090,7 +10522,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10090
10522
  ]
10091
10523
  };
10092
10524
  };
10093
- var getServer = async (requestContext, executionContext, conversationId, credentialStores) => {
10525
+ var getServer = async (headers, executionContext, conversationId, credentialStores) => {
10094
10526
  const { tenantId, projectId, graphId } = executionContext;
10095
10527
  setupTracing(conversationId, tenantId, graphId);
10096
10528
  const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
@@ -10146,18 +10578,18 @@ var getServer = async (requestContext, executionContext, conversationId, credent
10146
10578
  projectId,
10147
10579
  graphId,
10148
10580
  conversationId,
10149
- requestContext,
10581
+ headers,
10150
10582
  dbClient: dbClient_default,
10151
10583
  credentialStores
10152
10584
  });
10153
- logger23.info(
10585
+ logger24.info(
10154
10586
  {
10155
10587
  tenantId,
10156
10588
  projectId,
10157
10589
  graphId,
10158
10590
  conversationId,
10159
10591
  hasContextConfig: !!agentGraph.contextConfigId,
10160
- hasRequestContext: !!requestContext,
10592
+ hasHeaders: !!headers,
10161
10593
  hasValidatedContext: !!resolvedContext
10162
10594
  },
10163
10595
  "parameters"
@@ -10212,7 +10644,7 @@ var validateRequestParameters = (c) => {
10212
10644
  };
10213
10645
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
10214
10646
  const { tenantId, projectId, graphId } = executionContext;
10215
- logger23.info({ body }, "Received initialization request");
10647
+ logger24.info({ body }, "Received initialization request");
10216
10648
  const sessionId = getConversationId();
10217
10649
  const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
10218
10650
  scopes: { tenantId, projectId, graphId }
@@ -10252,7 +10684,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10252
10684
  }
10253
10685
  }
10254
10686
  });
10255
- logger23.info(
10687
+ logger24.info(
10256
10688
  { sessionId, conversationId: conversation.id },
10257
10689
  "Created MCP session as conversation"
10258
10690
  );
@@ -10261,9 +10693,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10261
10693
  });
10262
10694
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
10263
10695
  await server.connect(transport);
10264
- logger23.info({ sessionId }, "Server connected for initialization");
10696
+ logger24.info({ sessionId }, "Server connected for initialization");
10265
10697
  res.setHeader("Mcp-Session-Id", sessionId);
10266
- logger23.info(
10698
+ logger24.info(
10267
10699
  {
10268
10700
  sessionId,
10269
10701
  bodyMethod: body?.method,
@@ -10272,7 +10704,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10272
10704
  "About to handle initialization request"
10273
10705
  );
10274
10706
  await transport.handleRequest(req, res, body);
10275
- logger23.info({ sessionId }, "Successfully handled initialization request");
10707
+ logger24.info({ sessionId }, "Successfully handled initialization request");
10276
10708
  return toFetchResponse(res);
10277
10709
  };
10278
10710
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -10300,8 +10732,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10300
10732
  sessionId,
10301
10733
  conversation.metadata?.session_data?.mcpProtocolVersion
10302
10734
  );
10303
- logger23.info({ sessionId }, "Server connected and transport initialized");
10304
- logger23.info(
10735
+ logger24.info({ sessionId }, "Server connected and transport initialized");
10736
+ logger24.info(
10305
10737
  {
10306
10738
  sessionId,
10307
10739
  bodyKeys: Object.keys(body || {}),
@@ -10315,9 +10747,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10315
10747
  );
10316
10748
  try {
10317
10749
  await transport.handleRequest(req, res, body);
10318
- logger23.info({ sessionId }, "Successfully handled MCP request");
10750
+ logger24.info({ sessionId }, "Successfully handled MCP request");
10319
10751
  } catch (transportError) {
10320
- logger23.error(
10752
+ logger24.error(
10321
10753
  {
10322
10754
  sessionId,
10323
10755
  error: transportError,
@@ -10368,13 +10800,13 @@ app4.openapi(
10368
10800
  }
10369
10801
  const { executionContext } = paramValidation;
10370
10802
  const body = c.get("requestBody") || {};
10371
- logger23.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10803
+ logger24.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10372
10804
  const isInitRequest = body.method === "initialize";
10373
10805
  const { req, res } = toReqRes(c.req.raw);
10374
10806
  const validatedContext = c.get("validatedContext") || {};
10375
10807
  const credentialStores = c.get("credentialStores");
10376
- logger23.info({ validatedContext }, "Validated context");
10377
- logger23.info({ req }, "request");
10808
+ logger24.info({ validatedContext }, "Validated context");
10809
+ logger24.info({ req }, "request");
10378
10810
  if (isInitRequest) {
10379
10811
  return await handleInitializationRequest(
10380
10812
  body,
@@ -10396,7 +10828,7 @@ app4.openapi(
10396
10828
  );
10397
10829
  }
10398
10830
  } catch (e) {
10399
- logger23.error(
10831
+ logger24.error(
10400
10832
  {
10401
10833
  error: e instanceof Error ? e.message : e,
10402
10834
  stack: e instanceof Error ? e.stack : void 0
@@ -10408,7 +10840,7 @@ app4.openapi(
10408
10840
  }
10409
10841
  );
10410
10842
  app4.get("/", async (c) => {
10411
- logger23.info({}, "Received GET MCP request");
10843
+ logger24.info({}, "Received GET MCP request");
10412
10844
  return c.json(
10413
10845
  {
10414
10846
  jsonrpc: "2.0",
@@ -10422,7 +10854,7 @@ app4.get("/", async (c) => {
10422
10854
  );
10423
10855
  });
10424
10856
  app4.delete("/", async (c) => {
10425
- logger23.info({}, "Received DELETE MCP request");
10857
+ logger24.info({}, "Received DELETE MCP request");
10426
10858
  return c.json(
10427
10859
  {
10428
10860
  jsonrpc: "2.0",
@@ -10435,7 +10867,7 @@ app4.delete("/", async (c) => {
10435
10867
  var mcp_default = app4;
10436
10868
 
10437
10869
  // src/app.ts
10438
- var logger24 = getLogger("agents-run-api");
10870
+ var logger25 = getLogger("agents-run-api");
10439
10871
  function createExecutionHono(serverConfig, credentialStores) {
10440
10872
  const app6 = new OpenAPIHono();
10441
10873
  app6.use("*", otel());
@@ -10451,7 +10883,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10451
10883
  const body = await c.req.json();
10452
10884
  c.set("requestBody", body);
10453
10885
  } catch (error) {
10454
- logger24.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
10886
+ logger25.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
10455
10887
  }
10456
10888
  }
10457
10889
  return next();
@@ -10502,8 +10934,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10502
10934
  if (!isExpectedError) {
10503
10935
  const errorMessage = err instanceof Error ? err.message : String(err);
10504
10936
  const errorStack = err instanceof Error ? err.stack : void 0;
10505
- if (logger24) {
10506
- logger24.error(
10937
+ if (logger25) {
10938
+ logger25.error(
10507
10939
  {
10508
10940
  error: err,
10509
10941
  message: errorMessage,
@@ -10515,8 +10947,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10515
10947
  );
10516
10948
  }
10517
10949
  } else {
10518
- if (logger24) {
10519
- logger24.error(
10950
+ if (logger25) {
10951
+ logger25.error(
10520
10952
  {
10521
10953
  error: err,
10522
10954
  path: c.req.path,
@@ -10533,8 +10965,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10533
10965
  const response = err.getResponse();
10534
10966
  return response;
10535
10967
  } catch (responseError) {
10536
- if (logger24) {
10537
- logger24.error({ error: responseError }, "Error while handling HTTPException response");
10968
+ if (logger25) {
10969
+ logger25.error({ error: responseError }, "Error while handling HTTPException response");
10538
10970
  }
10539
10971
  }
10540
10972
  }
@@ -10568,7 +11000,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10568
11000
  app6.use("*", async (c, next) => {
10569
11001
  const executionContext = c.get("executionContext");
10570
11002
  if (!executionContext) {
10571
- logger24.debug({}, "Empty execution context");
11003
+ logger25.debug({}, "Empty execution context");
10572
11004
  return next();
10573
11005
  }
10574
11006
  const { tenantId, projectId, graphId } = executionContext;
@@ -10577,7 +11009,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10577
11009
  if (requestBody) {
10578
11010
  conversationId = requestBody.conversationId;
10579
11011
  if (!conversationId) {
10580
- logger24.debug({ requestBody }, "No conversation ID found in request body");
11012
+ logger25.debug({ requestBody }, "No conversation ID found in request body");
10581
11013
  }
10582
11014
  }
10583
11015
  const entries = Object.fromEntries(
@@ -10592,7 +11024,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10592
11024
  })
10593
11025
  );
10594
11026
  if (!Object.keys(entries).length) {
10595
- logger24.debug({}, "Empty entries for baggage");
11027
+ logger25.debug({}, "Empty entries for baggage");
10596
11028
  return next();
10597
11029
  }
10598
11030
  const bag = Object.entries(entries).reduce(