@inkeep/agents-run-api 0.14.16 → 0.16.0

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,9 +2258,9 @@ __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
- // Session-scoped ArtifactParser instance
2263
+ // Whether to send data operations
2052
2264
  constructor(sessionId, messageId, graphId, tenantId, projectId, contextId) {
2053
2265
  this.sessionId = sessionId;
2054
2266
  this.messageId = messageId;
@@ -2077,7 +2289,9 @@ var GraphSession = class {
2077
2289
  __publicField(this, "artifactService");
2078
2290
  // Session-scoped ArtifactService instance
2079
2291
  __publicField(this, "artifactParser");
2080
- logger8.debug({ sessionId, messageId, graphId }, "GraphSession created");
2292
+ // Session-scoped ArtifactParser instance
2293
+ __publicField(this, "isEmitOperations", false);
2294
+ logger9.debug({ sessionId, messageId, graphId }, "GraphSession created");
2081
2295
  if (tenantId && projectId) {
2082
2296
  toolSessionManager.createSessionWithId(
2083
2297
  sessionId,
@@ -2101,10 +2315,84 @@ var GraphSession = class {
2101
2315
  sessionId,
2102
2316
  contextId,
2103
2317
  taskId: `task_${contextId}-${messageId}`,
2104
- streamRequestId: sessionId
2318
+ streamRequestId: sessionId,
2319
+ artifactService: this.artifactService
2320
+ // Pass the shared ArtifactService
2105
2321
  });
2106
2322
  }
2107
2323
  }
2324
+ /**
2325
+ * Enable emit operations to send data operations
2326
+ */
2327
+ enableEmitOperations() {
2328
+ this.isEmitOperations = true;
2329
+ logger9.info(
2330
+ { sessionId: this.sessionId },
2331
+ "\u{1F50D} DEBUG: Emit operations enabled for GraphSession"
2332
+ );
2333
+ }
2334
+ /**
2335
+ * Send data operation to stream when emit operations is enabled
2336
+ */
2337
+ async sendDataOperation(event) {
2338
+ try {
2339
+ const streamHelper = getStreamHelper(this.sessionId);
2340
+ if (streamHelper) {
2341
+ const formattedOperation = {
2342
+ type: event.eventType,
2343
+ label: this.generateEventLabel(event),
2344
+ details: {
2345
+ timestamp: event.timestamp,
2346
+ agentId: event.agentId,
2347
+ data: event.data
2348
+ }
2349
+ };
2350
+ await streamHelper.writeOperation(formattedOperation);
2351
+ }
2352
+ } catch (error) {
2353
+ logger9.error(
2354
+ {
2355
+ sessionId: this.sessionId,
2356
+ eventType: event.eventType,
2357
+ error: error instanceof Error ? error.message : error
2358
+ },
2359
+ "\u274C DEBUG: Failed to send data operation"
2360
+ );
2361
+ }
2362
+ }
2363
+ /**
2364
+ * Generate human-readable labels for events
2365
+ */
2366
+ generateEventLabel(event) {
2367
+ switch (event.eventType) {
2368
+ case "agent_generate":
2369
+ return `Agent ${event.agentId} generating response`;
2370
+ case "agent_reasoning":
2371
+ return `Agent ${event.agentId} reasoning through request`;
2372
+ case "tool_execution": {
2373
+ const toolData = event.data;
2374
+ return `Tool execution: ${toolData.toolName || "unknown"}`;
2375
+ }
2376
+ case "transfer": {
2377
+ const transferData = event.data;
2378
+ return `Agent transfer: ${transferData.fromAgent} \u2192 ${transferData.targetAgent}`;
2379
+ }
2380
+ case "delegation_sent": {
2381
+ const delegationData = event.data;
2382
+ return `Task delegated: ${delegationData.fromAgent} \u2192 ${delegationData.targetAgent}`;
2383
+ }
2384
+ case "delegation_returned": {
2385
+ const returnData = event.data;
2386
+ return `Task completed: ${returnData.targetAgent} \u2192 ${returnData.fromAgent}`;
2387
+ }
2388
+ case "artifact_saved": {
2389
+ const artifactData = event.data;
2390
+ return `Artifact saved: ${artifactData.artifactType || "unknown type"}`;
2391
+ }
2392
+ default:
2393
+ return `${event.eventType} event`;
2394
+ }
2395
+ }
2108
2396
  /**
2109
2397
  * Initialize status updates for this session
2110
2398
  */
@@ -2125,7 +2413,7 @@ var GraphSession = class {
2125
2413
  if (this.statusUpdateState.config.timeInSeconds) {
2126
2414
  this.statusUpdateTimer = setInterval(async () => {
2127
2415
  if (!this.statusUpdateState || this.isEnded) {
2128
- logger8.debug(
2416
+ logger9.debug(
2129
2417
  { sessionId: this.sessionId },
2130
2418
  "Timer triggered but session already cleaned up or ended"
2131
2419
  );
@@ -2137,7 +2425,7 @@ var GraphSession = class {
2137
2425
  }
2138
2426
  await this.checkAndSendTimeBasedUpdate();
2139
2427
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2140
- logger8.info(
2428
+ logger9.info(
2141
2429
  {
2142
2430
  sessionId: this.sessionId,
2143
2431
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -2150,8 +2438,16 @@ var GraphSession = class {
2150
2438
  * Record an event in the session and trigger status updates if configured
2151
2439
  */
2152
2440
  recordEvent(eventType, agentId, data) {
2441
+ if (this.isEmitOperations) {
2442
+ this.sendDataOperation({
2443
+ timestamp: Date.now(),
2444
+ eventType,
2445
+ agentId,
2446
+ data
2447
+ });
2448
+ }
2153
2449
  if (this.isEnded) {
2154
- logger8.debug(
2450
+ logger9.debug(
2155
2451
  {
2156
2452
  sessionId: this.sessionId,
2157
2453
  eventType,
@@ -2171,7 +2467,7 @@ var GraphSession = class {
2171
2467
  if (eventType === "artifact_saved" && data.pendingGeneration) {
2172
2468
  const artifactId = data.artifactId;
2173
2469
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2174
- logger8.warn(
2470
+ logger9.warn(
2175
2471
  {
2176
2472
  sessionId: this.sessionId,
2177
2473
  artifactId,
@@ -2193,7 +2489,7 @@ var GraphSession = class {
2193
2489
  this.artifactProcessingErrors.set(artifactId, errorCount);
2194
2490
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2195
2491
  this.pendingArtifacts.delete(artifactId);
2196
- logger8.error(
2492
+ logger9.error(
2197
2493
  {
2198
2494
  sessionId: this.sessionId,
2199
2495
  artifactId,
@@ -2205,7 +2501,7 @@ var GraphSession = class {
2205
2501
  "Artifact processing failed after max retries, giving up"
2206
2502
  );
2207
2503
  } else {
2208
- logger8.warn(
2504
+ logger9.warn(
2209
2505
  {
2210
2506
  sessionId: this.sessionId,
2211
2507
  artifactId,
@@ -2227,14 +2523,14 @@ var GraphSession = class {
2227
2523
  */
2228
2524
  checkStatusUpdates() {
2229
2525
  if (this.isEnded) {
2230
- logger8.debug(
2526
+ logger9.debug(
2231
2527
  { sessionId: this.sessionId },
2232
2528
  "Session has ended - skipping status update check"
2233
2529
  );
2234
2530
  return;
2235
2531
  }
2236
2532
  if (!this.statusUpdateState) {
2237
- logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2533
+ logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2238
2534
  return;
2239
2535
  }
2240
2536
  const statusUpdateState = this.statusUpdateState;
@@ -2245,11 +2541,11 @@ var GraphSession = class {
2245
2541
  */
2246
2542
  async checkAndSendTimeBasedUpdate() {
2247
2543
  if (this.isEnded) {
2248
- 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");
2249
2545
  return;
2250
2546
  }
2251
2547
  if (!this.statusUpdateState) {
2252
- logger8.debug(
2548
+ logger9.debug(
2253
2549
  { sessionId: this.sessionId },
2254
2550
  "No status updates configured for time-based check"
2255
2551
  );
@@ -2262,7 +2558,7 @@ var GraphSession = class {
2262
2558
  try {
2263
2559
  await this.generateAndSendUpdate();
2264
2560
  } catch (error) {
2265
- logger8.error(
2561
+ logger9.error(
2266
2562
  {
2267
2563
  sessionId: this.sessionId,
2268
2564
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2365,29 +2661,29 @@ var GraphSession = class {
2365
2661
  */
2366
2662
  async generateAndSendUpdate() {
2367
2663
  if (this.isEnded) {
2368
- logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2664
+ logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2369
2665
  return;
2370
2666
  }
2371
2667
  if (this.isTextStreaming) {
2372
- logger8.debug(
2668
+ logger9.debug(
2373
2669
  { sessionId: this.sessionId },
2374
2670
  "Text is currently streaming - skipping status update"
2375
2671
  );
2376
2672
  return;
2377
2673
  }
2378
2674
  if (this.isGeneratingUpdate) {
2379
- logger8.debug(
2675
+ logger9.debug(
2380
2676
  { sessionId: this.sessionId },
2381
2677
  "Update already in progress - skipping duplicate generation"
2382
2678
  );
2383
2679
  return;
2384
2680
  }
2385
2681
  if (!this.statusUpdateState) {
2386
- 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");
2387
2683
  return;
2388
2684
  }
2389
2685
  if (!this.graphId) {
2390
- logger8.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2686
+ logger9.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2391
2687
  return;
2392
2688
  }
2393
2689
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -2399,7 +2695,7 @@ var GraphSession = class {
2399
2695
  try {
2400
2696
  const streamHelper = getStreamHelper(this.sessionId);
2401
2697
  if (!streamHelper) {
2402
- logger8.warn(
2698
+ logger9.warn(
2403
2699
  { sessionId: this.sessionId },
2404
2700
  "No stream helper found - cannot send status update"
2405
2701
  );
@@ -2419,7 +2715,7 @@ var GraphSession = class {
2419
2715
  if (result.summaries && result.summaries.length > 0) {
2420
2716
  for (const summary of result.summaries) {
2421
2717
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
2422
- logger8.warn(
2718
+ logger9.warn(
2423
2719
  {
2424
2720
  sessionId: this.sessionId,
2425
2721
  summary
@@ -2456,7 +2752,7 @@ var GraphSession = class {
2456
2752
  this.statusUpdateState.lastEventCount = this.events.length;
2457
2753
  }
2458
2754
  } catch (error) {
2459
- logger8.error(
2755
+ logger9.error(
2460
2756
  {
2461
2757
  sessionId: this.sessionId,
2462
2758
  error: error instanceof Error ? error.message : "Unknown error",
@@ -2494,7 +2790,7 @@ var GraphSession = class {
2494
2790
  this.releaseUpdateLock();
2495
2791
  }
2496
2792
  } catch (error) {
2497
- logger8.error(
2793
+ logger9.error(
2498
2794
  {
2499
2795
  sessionId: this.sessionId,
2500
2796
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2572,7 +2868,7 @@ User's Question/Context:
2572
2868
  ${conversationHistory}
2573
2869
  ` : "";
2574
2870
  } catch (error) {
2575
- logger8.warn(
2871
+ logger9.warn(
2576
2872
  { sessionId: this.sessionId, error },
2577
2873
  "Failed to fetch conversation history for structured status update"
2578
2874
  );
@@ -2706,7 +3002,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2706
3002
  return { summaries };
2707
3003
  } catch (error) {
2708
3004
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
2709
- logger8.error({ error }, "Failed to generate structured update, using fallback");
3005
+ logger9.error({ error }, "Failed to generate structured update, using fallback");
2710
3006
  return { summaries: [] };
2711
3007
  } finally {
2712
3008
  span.end();
@@ -2851,6 +3147,9 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2851
3147
  "graph_session.id": this.sessionId,
2852
3148
  "artifact.id": artifactData.artifactId,
2853
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),
2854
3153
  "tenant.id": artifactData.tenantId || "unknown",
2855
3154
  "project.id": artifactData.projectId || "unknown",
2856
3155
  "context.id": artifactData.contextId || "unknown",
@@ -2901,8 +3200,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2901
3200
  Tool Context: ${toolContext ? JSON.stringify(toolContext, null, 2) : "No tool context"}
2902
3201
  Context: ${conversationHistory?.slice(-200) || "Processing"}
2903
3202
  Type: ${artifactData.artifactType || "data"}
2904
- Summary: ${JSON.stringify(artifactData.summaryProps, null, 2)}
2905
- Full: ${JSON.stringify(artifactData.fullProps, null, 2)}
3203
+ Data: ${JSON.stringify(artifactData.data || artifactData.summaryData, null, 2)}
2906
3204
 
2907
3205
  Make it specific and relevant.`;
2908
3206
  let modelToUse = this.statusUpdateState?.summarizerModel;
@@ -2920,7 +3218,7 @@ Make it specific and relevant.`;
2920
3218
  });
2921
3219
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
2922
3220
  modelToUse = agentData.models.base;
2923
- logger8.info(
3221
+ logger9.info(
2924
3222
  {
2925
3223
  sessionId: this.sessionId,
2926
3224
  artifactId: artifactData.artifactId,
@@ -2931,7 +3229,7 @@ Make it specific and relevant.`;
2931
3229
  );
2932
3230
  }
2933
3231
  } catch (error) {
2934
- logger8.warn(
3232
+ logger9.warn(
2935
3233
  {
2936
3234
  sessionId: this.sessionId,
2937
3235
  artifactId: artifactData.artifactId,
@@ -2943,7 +3241,7 @@ Make it specific and relevant.`;
2943
3241
  }
2944
3242
  }
2945
3243
  if (!modelToUse?.model?.trim()) {
2946
- logger8.warn(
3244
+ logger9.warn(
2947
3245
  {
2948
3246
  sessionId: this.sessionId,
2949
3247
  artifactId: artifactData.artifactId
@@ -2976,8 +3274,12 @@ Make it specific and relevant.`;
2976
3274
  "llm.operation": "generate_object",
2977
3275
  "artifact.id": artifactData.artifactId,
2978
3276
  "artifact.type": artifactData.artifactType,
2979
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
2980
- "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
+ ),
2981
3283
  "prompt.length": prompt.length
2982
3284
  }
2983
3285
  },
@@ -3007,8 +3309,12 @@ Make it specific and relevant.`;
3007
3309
  "artifact.type": artifactData.artifactType,
3008
3310
  "artifact.name": result2.object.name,
3009
3311
  "artifact.description": result2.object.description,
3010
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3011
- "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
+ ),
3012
3318
  "generation.name_length": result2.object.name.length,
3013
3319
  "generation.description_length": result2.object.description.length,
3014
3320
  "generation.attempts": attempt
@@ -3017,7 +3323,7 @@ Make it specific and relevant.`;
3017
3323
  return result2;
3018
3324
  } catch (error) {
3019
3325
  lastError = error instanceof Error ? error : new Error(String(error));
3020
- logger8.warn(
3326
+ logger9.warn(
3021
3327
  {
3022
3328
  sessionId: this.sessionId,
3023
3329
  artifactId: artifactData.artifactId,
@@ -3033,7 +3339,10 @@ Make it specific and relevant.`;
3033
3339
  }
3034
3340
  }
3035
3341
  }
3036
- setSpanWithError(generationSpan, lastError instanceof Error ? lastError : new Error(String(lastError)));
3342
+ setSpanWithError(
3343
+ generationSpan,
3344
+ lastError instanceof Error ? lastError : new Error(String(lastError))
3345
+ );
3037
3346
  throw new Error(
3038
3347
  `Artifact name/description generation failed after ${maxRetries} attempts: ${lastError?.message}`
3039
3348
  );
@@ -3054,9 +3363,9 @@ Make it specific and relevant.`;
3054
3363
  name: result.name,
3055
3364
  description: result.description,
3056
3365
  type: artifactData.artifactType || "source",
3057
- summaryProps: artifactData.summaryProps || {},
3058
- fullProps: artifactData.fullProps || {},
3059
- metadata: artifactData.metadata || {}
3366
+ data: artifactData.data || {},
3367
+ metadata: artifactData.metadata || {},
3368
+ toolCallId: artifactData.toolCallId
3060
3369
  });
3061
3370
  mainSaveSucceeded = true;
3062
3371
  span.setAttributes({
@@ -3066,7 +3375,7 @@ Make it specific and relevant.`;
3066
3375
  });
3067
3376
  span.setStatus({ code: SpanStatusCode.OK });
3068
3377
  } catch (saveError) {
3069
- logger8.error(
3378
+ logger9.error(
3070
3379
  {
3071
3380
  sessionId: this.sessionId,
3072
3381
  artifactId: artifactData.artifactId,
@@ -3090,11 +3399,11 @@ Make it specific and relevant.`;
3090
3399
  name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
3091
3400
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool results"}`,
3092
3401
  type: artifactData.artifactType || "source",
3093
- summaryProps: artifactData.summaryProps || {},
3094
- fullProps: artifactData.fullProps || {},
3095
- metadata: artifactData.metadata || {}
3402
+ data: artifactData.data || {},
3403
+ metadata: artifactData.metadata || {},
3404
+ toolCallId: artifactData.toolCallId
3096
3405
  });
3097
- logger8.info(
3406
+ logger9.info(
3098
3407
  {
3099
3408
  sessionId: this.sessionId,
3100
3409
  artifactId: artifactData.artifactId
@@ -3105,7 +3414,7 @@ Make it specific and relevant.`;
3105
3414
  } catch (fallbackError) {
3106
3415
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
3107
3416
  if (isDuplicateError) ; else {
3108
- logger8.error(
3417
+ logger9.error(
3109
3418
  {
3110
3419
  sessionId: this.sessionId,
3111
3420
  artifactId: artifactData.artifactId,
@@ -3118,7 +3427,7 @@ Make it specific and relevant.`;
3118
3427
  }
3119
3428
  } catch (error) {
3120
3429
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3121
- logger8.error(
3430
+ logger9.error(
3122
3431
  {
3123
3432
  sessionId: this.sessionId,
3124
3433
  artifactId: artifactData.artifactId,
@@ -3137,7 +3446,7 @@ Make it specific and relevant.`;
3137
3446
  */
3138
3447
  setArtifactCache(key, artifact) {
3139
3448
  this.artifactCache.set(key, artifact);
3140
- logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3449
+ logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3141
3450
  }
3142
3451
  /**
3143
3452
  * Get session-scoped ArtifactService instance
@@ -3156,9 +3465,17 @@ Make it specific and relevant.`;
3156
3465
  */
3157
3466
  getArtifactCache(key) {
3158
3467
  const artifact = this.artifactCache.get(key);
3159
- logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3468
+ logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3160
3469
  return artifact || null;
3161
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
+ }
3162
3479
  };
3163
3480
  var GraphSessionManager = class {
3164
3481
  constructor() {
@@ -3171,7 +3488,7 @@ var GraphSessionManager = class {
3171
3488
  const sessionId = messageId;
3172
3489
  const session = new GraphSession(sessionId, messageId, graphId, tenantId, projectId, contextId);
3173
3490
  this.sessions.set(sessionId, session);
3174
- logger8.info(
3491
+ logger9.info(
3175
3492
  { sessionId, messageId, graphId, tenantId, projectId, contextId },
3176
3493
  "GraphSession created"
3177
3494
  );
@@ -3185,7 +3502,7 @@ var GraphSessionManager = class {
3185
3502
  if (session) {
3186
3503
  session.initializeStatusUpdates(config, summarizerModel);
3187
3504
  } else {
3188
- logger8.error(
3505
+ logger9.error(
3189
3506
  {
3190
3507
  sessionId,
3191
3508
  availableSessions: Array.from(this.sessions.keys())
@@ -3194,6 +3511,23 @@ var GraphSessionManager = class {
3194
3511
  );
3195
3512
  }
3196
3513
  }
3514
+ /**
3515
+ * Enable emit operations for a session to send data operations
3516
+ */
3517
+ enableEmitOperations(sessionId) {
3518
+ const session = this.sessions.get(sessionId);
3519
+ if (session) {
3520
+ session.enableEmitOperations();
3521
+ } else {
3522
+ logger9.error(
3523
+ {
3524
+ sessionId,
3525
+ availableSessions: Array.from(this.sessions.keys())
3526
+ },
3527
+ "Session not found for emit operations enablement"
3528
+ );
3529
+ }
3530
+ }
3197
3531
  /**
3198
3532
  * Get an existing session
3199
3533
  */
@@ -3206,7 +3540,7 @@ var GraphSessionManager = class {
3206
3540
  recordEvent(sessionId, eventType, agentId, data) {
3207
3541
  const session = this.sessions.get(sessionId);
3208
3542
  if (!session) {
3209
- logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
3543
+ logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
3210
3544
  return;
3211
3545
  }
3212
3546
  session.recordEvent(eventType, agentId, data);
@@ -3217,12 +3551,12 @@ var GraphSessionManager = class {
3217
3551
  endSession(sessionId) {
3218
3552
  const session = this.sessions.get(sessionId);
3219
3553
  if (!session) {
3220
- logger8.warn({ sessionId }, "Attempted to end non-existent session");
3554
+ logger9.warn({ sessionId }, "Attempted to end non-existent session");
3221
3555
  return [];
3222
3556
  }
3223
3557
  const events = session.getEvents();
3224
3558
  const summary = session.getSummary();
3225
- logger8.info({ sessionId, summary }, "GraphSession ended");
3559
+ logger9.info({ sessionId, summary }, "GraphSession ended");
3226
3560
  session.cleanup();
3227
3561
  this.sessions.delete(sessionId);
3228
3562
  return events;
@@ -3276,11 +3610,52 @@ var GraphSessionManager = class {
3276
3610
  const session = this.sessions.get(sessionId);
3277
3611
  return session ? session.getArtifactParser() : null;
3278
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
+ }
3279
3622
  };
3280
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
+ }
3281
3656
 
3282
3657
  // src/services/IncrementalStreamParser.ts
3283
- var logger9 = getLogger("IncrementalStreamParser");
3658
+ var logger10 = getLogger("IncrementalStreamParser");
3284
3659
  var _IncrementalStreamParser = class _IncrementalStreamParser {
3285
3660
  // Max number of collected parts to prevent unbounded growth
3286
3661
  constructor(streamHelper, tenantId, contextId, artifactParserOptions) {
@@ -3309,9 +3684,20 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3309
3684
  return;
3310
3685
  }
3311
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
+ }
3312
3696
  this.artifactParser = new ArtifactParser(tenantId, {
3313
3697
  ...artifactParserOptions,
3314
- contextId
3698
+ contextId,
3699
+ artifactService: sharedArtifactService
3700
+ // Use shared ArtifactService if available
3315
3701
  });
3316
3702
  }
3317
3703
  /**
@@ -3321,7 +3707,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3321
3707
  async initializeArtifactMap() {
3322
3708
  try {
3323
3709
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
3324
- logger9.debug(
3710
+ logger10.debug(
3325
3711
  {
3326
3712
  contextId: this.contextId,
3327
3713
  artifactMapSize: this.artifactMap.size
@@ -3329,7 +3715,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3329
3715
  "Initialized artifact map for streaming"
3330
3716
  );
3331
3717
  } catch (error) {
3332
- logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3718
+ logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3333
3719
  this.artifactMap = /* @__PURE__ */ new Map();
3334
3720
  }
3335
3721
  }
@@ -3426,9 +3812,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3426
3812
  * Note: Text components are handled separately with incremental streaming
3427
3813
  */
3428
3814
  async streamComponent(component) {
3429
- const parts = await this.artifactParser.parseObject({
3430
- dataComponents: [component]
3431
- }, this.artifactMap, this.agentId);
3815
+ const parts = await this.artifactParser.parseObject(
3816
+ {
3817
+ dataComponents: [component]
3818
+ },
3819
+ this.artifactMap,
3820
+ this.agentId
3821
+ );
3432
3822
  if (!Array.isArray(parts)) {
3433
3823
  console.warn("parseObject returned non-array:", parts);
3434
3824
  return;
@@ -3498,9 +3888,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3498
3888
  const componentKey = component.id;
3499
3889
  const hasBeenStreamed = this.lastStreamedComponents.has(componentKey);
3500
3890
  if (!hasBeenStreamed && this.isComponentComplete(component) && component.name !== "Text") {
3501
- const parts = await this.artifactParser.parseObject({
3502
- dataComponents: [component]
3503
- }, this.artifactMap, this.agentId);
3891
+ const parts = await this.artifactParser.parseObject(
3892
+ {
3893
+ dataComponents: [component]
3894
+ },
3895
+ this.artifactMap,
3896
+ this.agentId
3897
+ );
3504
3898
  for (const part of parts) {
3505
3899
  await this.streamPart(part);
3506
3900
  }
@@ -3565,7 +3959,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3565
3959
  remainingBuffer: workingBuffer
3566
3960
  };
3567
3961
  }
3568
- 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
+ );
3569
3967
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
3570
3968
  const lastPart = parts[parts.length - 1];
3571
3969
  const lastText = lastPart.text || "";
@@ -3637,20 +4035,35 @@ __publicField(_IncrementalStreamParser, "MAX_COLLECTED_PARTS", 1e4);
3637
4035
  var IncrementalStreamParser = _IncrementalStreamParser;
3638
4036
 
3639
4037
  // src/services/ResponseFormatter.ts
3640
- var logger10 = getLogger("ResponseFormatter");
4038
+ var logger11 = getLogger("ResponseFormatter");
3641
4039
  var ResponseFormatter = class {
3642
4040
  constructor(tenantId, artifactParserOptions) {
3643
4041
  __publicField(this, "artifactParser");
3644
4042
  __publicField(this, "agentId");
3645
4043
  this.agentId = artifactParserOptions?.agentId;
3646
4044
  if (artifactParserOptions?.streamRequestId) {
3647
- const sessionParser = graphSessionManager.getArtifactParser(artifactParserOptions.streamRequestId);
4045
+ const sessionParser = graphSessionManager.getArtifactParser(
4046
+ artifactParserOptions.streamRequestId
4047
+ );
3648
4048
  if (sessionParser) {
3649
4049
  this.artifactParser = sessionParser;
3650
4050
  return;
3651
4051
  }
3652
4052
  }
3653
- 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
+ });
3654
4067
  }
3655
4068
  /**
3656
4069
  * Process structured object response and replace artifact markers with actual artifacts
@@ -3663,7 +4076,11 @@ var ResponseFormatter = class {
3663
4076
  "response.type": "object",
3664
4077
  "response.availableArtifacts": artifactMap.size
3665
4078
  });
3666
- 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
+ );
3667
4084
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
3668
4085
  span.setAttributes({
3669
4086
  "response.dataPartsCount": parts.length,
@@ -3677,7 +4094,7 @@ var ResponseFormatter = class {
3677
4094
  return { parts };
3678
4095
  } catch (error) {
3679
4096
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3680
- logger10.error({ error, responseObject }, "Error formatting object response");
4097
+ logger11.error({ error, responseObject }, "Error formatting object response");
3681
4098
  return {
3682
4099
  parts: [{ kind: "data", data: responseObject }]
3683
4100
  };
@@ -3729,7 +4146,7 @@ var ResponseFormatter = class {
3729
4146
  return { parts };
3730
4147
  } catch (error) {
3731
4148
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3732
- logger10.error({ error, responseText }, "Error formatting response");
4149
+ logger11.error({ error, responseText }, "Error formatting response");
3733
4150
  return { text: responseText };
3734
4151
  } finally {
3735
4152
  span.end();
@@ -3777,7 +4194,7 @@ var ResponseFormatter = class {
3777
4194
  function agentInitializingOp(sessionId, graphId) {
3778
4195
  return {
3779
4196
  type: "agent_initializing",
3780
- ctx: {
4197
+ details: {
3781
4198
  sessionId,
3782
4199
  graphId
3783
4200
  }
@@ -3786,7 +4203,7 @@ function agentInitializingOp(sessionId, graphId) {
3786
4203
  function completionOp(agentId, iterations) {
3787
4204
  return {
3788
4205
  type: "completion",
3789
- ctx: {
4206
+ details: {
3790
4207
  agent: agentId,
3791
4208
  iteration: iterations
3792
4209
  }
@@ -3805,10 +4222,10 @@ function errorOp(message, agentId, severity = "error", code) {
3805
4222
  function generateToolId() {
3806
4223
  return `tool_${nanoid(8)}`;
3807
4224
  }
3808
- var logger11 = getLogger("DataComponentSchema");
4225
+ var logger12 = getLogger("DataComponentSchema");
3809
4226
  function jsonSchemaToZod(jsonSchema) {
3810
4227
  if (!jsonSchema || typeof jsonSchema !== "object") {
3811
- logger11.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
4228
+ logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
3812
4229
  return z.string();
3813
4230
  }
3814
4231
  switch (jsonSchema.type) {
@@ -3835,7 +4252,7 @@ function jsonSchemaToZod(jsonSchema) {
3835
4252
  case "null":
3836
4253
  return z.null();
3837
4254
  default:
3838
- logger11.warn(
4255
+ logger12.warn(
3839
4256
  {
3840
4257
  unsupportedType: jsonSchema.type,
3841
4258
  schema: jsonSchema
@@ -4111,8 +4528,7 @@ var ArtifactCreateSchema = class {
4111
4528
  */
4112
4529
  static getSchemas(artifactComponents) {
4113
4530
  return artifactComponents.map((component) => {
4114
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4115
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
4531
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4116
4532
  const propsSchema = {
4117
4533
  type: "object",
4118
4534
  properties: {
@@ -4131,10 +4547,9 @@ var ArtifactCreateSchema = class {
4131
4547
  },
4132
4548
  base_selector: {
4133
4549
  type: "string",
4134
- 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']").`
4135
4551
  },
4136
- summary_props: enhancedSummaryProps,
4137
- full_props: enhancedFullProps
4552
+ details_selector: enhancedSchema
4138
4553
  },
4139
4554
  required: ["id", "tool_call_id", "type", "base_selector"]
4140
4555
  };
@@ -4152,8 +4567,7 @@ var ArtifactCreateSchema = class {
4152
4567
  */
4153
4568
  static getDataComponents(tenantId, projectId = "", artifactComponents) {
4154
4569
  return artifactComponents.map((component) => {
4155
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4156
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
4570
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4157
4571
  const propsSchema = {
4158
4572
  type: "object",
4159
4573
  properties: {
@@ -4172,10 +4586,9 @@ var ArtifactCreateSchema = class {
4172
4586
  },
4173
4587
  base_selector: {
4174
4588
  type: "string",
4175
- 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']").`
4176
4590
  },
4177
- summary_props: enhancedSummaryProps,
4178
- full_props: enhancedFullProps
4591
+ details_selector: enhancedSchema
4179
4592
  },
4180
4593
  required: ["id", "tool_call_id", "type", "base_selector"]
4181
4594
  };
@@ -4202,7 +4615,7 @@ function parseEmbeddedJson(data) {
4202
4615
  }
4203
4616
 
4204
4617
  // src/a2a/client.ts
4205
- var logger12 = getLogger("a2aClient");
4618
+ var logger13 = getLogger("a2aClient");
4206
4619
  var DEFAULT_BACKOFF = {
4207
4620
  initialInterval: 500,
4208
4621
  maxInterval: 6e4,
@@ -4408,7 +4821,7 @@ var A2AClient = class {
4408
4821
  try {
4409
4822
  const res = await fn();
4410
4823
  if (attempt > 0) {
4411
- logger12.info(
4824
+ logger13.info(
4412
4825
  {
4413
4826
  attempts: attempt + 1,
4414
4827
  elapsedTime: Date.now() - start
@@ -4423,7 +4836,7 @@ var A2AClient = class {
4423
4836
  }
4424
4837
  const elapsed = Date.now() - start;
4425
4838
  if (elapsed > maxElapsedTime) {
4426
- logger12.warn(
4839
+ logger13.warn(
4427
4840
  {
4428
4841
  attempts: attempt + 1,
4429
4842
  elapsedTime: elapsed,
@@ -4444,7 +4857,7 @@ var A2AClient = class {
4444
4857
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
4445
4858
  }
4446
4859
  const delayMs = Math.min(retryInterval, maxInterval);
4447
- logger12.info(
4860
+ logger13.info(
4448
4861
  {
4449
4862
  attempt: attempt + 1,
4450
4863
  delayMs,
@@ -4529,7 +4942,7 @@ var A2AClient = class {
4529
4942
  }
4530
4943
  const rpcResponse = await httpResponse.json();
4531
4944
  if (rpcResponse.id !== requestId2) {
4532
- logger12.warn(
4945
+ logger13.warn(
4533
4946
  {
4534
4947
  method,
4535
4948
  expectedId: requestId2,
@@ -4728,7 +5141,7 @@ var A2AClient = class {
4728
5141
  try {
4729
5142
  while (true) {
4730
5143
  const { done, value } = await reader.read();
4731
- logger12.info({ done, value }, "parseA2ASseStream");
5144
+ logger13.info({ done, value }, "parseA2ASseStream");
4732
5145
  if (done) {
4733
5146
  if (eventDataBuffer.trim()) {
4734
5147
  const result = this._processSseEventData(
@@ -4815,7 +5228,7 @@ var A2AClient = class {
4815
5228
  };
4816
5229
 
4817
5230
  // src/agents/relationTools.ts
4818
- var logger13 = getLogger("relationships Tools");
5231
+ var logger14 = getLogger("relationships Tools");
4819
5232
  var generateTransferToolDescription = (config) => {
4820
5233
  return `Hand off the conversation to agent ${config.id}.
4821
5234
 
@@ -4844,7 +5257,7 @@ var createTransferToAgentTool = ({
4844
5257
  }) => {
4845
5258
  return tool({
4846
5259
  description: generateTransferToolDescription(transferConfig),
4847
- inputSchema: z4.object({}),
5260
+ inputSchema: z5.object({}),
4848
5261
  execute: async () => {
4849
5262
  const activeSpan = trace.getActiveSpan();
4850
5263
  if (activeSpan) {
@@ -4853,7 +5266,7 @@ var createTransferToAgentTool = ({
4853
5266
  "transfer.to_agent_id": transferConfig.id ?? "unknown"
4854
5267
  });
4855
5268
  }
4856
- logger13.info(
5269
+ logger14.info(
4857
5270
  {
4858
5271
  transferTo: transferConfig.id ?? "unknown",
4859
5272
  fromAgent: callingAgentId
@@ -4890,7 +5303,7 @@ function createDelegateToAgentTool({
4890
5303
  }) {
4891
5304
  return tool({
4892
5305
  description: generateDelegateToolDescription(delegateConfig.config),
4893
- inputSchema: z4.object({ message: z4.string() }),
5306
+ inputSchema: z5.object({ message: z5.string() }),
4894
5307
  execute: async (input, context) => {
4895
5308
  const delegationId = `del_${nanoid()}`;
4896
5309
  const activeSpan = trace.getActiveSpan();
@@ -5002,7 +5415,7 @@ function createDelegateToAgentTool({
5002
5415
  ...isInternal ? { fromAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
5003
5416
  }
5004
5417
  };
5005
- logger13.info({ messageToSend }, "messageToSend");
5418
+ logger14.info({ messageToSend }, "messageToSend");
5006
5419
  await createMessage(dbClient_default)({
5007
5420
  id: nanoid(),
5008
5421
  tenantId,
@@ -5064,7 +5477,7 @@ function createDelegateToAgentTool({
5064
5477
  }
5065
5478
 
5066
5479
  // src/agents/SystemPromptBuilder.ts
5067
- var logger14 = getLogger("SystemPromptBuilder");
5480
+ var logger15 = getLogger("SystemPromptBuilder");
5068
5481
  var SystemPromptBuilder = class {
5069
5482
  constructor(version, versionConfig) {
5070
5483
  this.version = version;
@@ -5080,12 +5493,12 @@ var SystemPromptBuilder = class {
5080
5493
  this.templates.set(name, content);
5081
5494
  }
5082
5495
  this.loaded = true;
5083
- logger14.debug(
5496
+ logger15.debug(
5084
5497
  { templateCount: this.templates.size, version: this.version },
5085
5498
  `Loaded ${this.templates.size} templates for version ${this.version}`
5086
5499
  );
5087
5500
  } catch (error) {
5088
- logger14.error({ error }, `Failed to load templates for version ${this.version}`);
5501
+ logger15.error({ error }, `Failed to load templates for version ${this.version}`);
5089
5502
  throw new Error(`Template loading failed: ${error}`);
5090
5503
  }
5091
5504
  }
@@ -5110,68 +5523,6 @@ var SystemPromptBuilder = class {
5110
5523
  }
5111
5524
  };
5112
5525
 
5113
- // templates/v1/shared/artifact.xml?raw
5114
- 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> ";
5115
-
5116
- // templates/v1/shared/artifact-retrieval-guidance.xml?raw
5117
- var artifact_retrieval_guidance_default = `ARTIFACT RETRIEVAL: ACCESSING EXISTING ARTIFACT DATA
5118
-
5119
- \u{1F6A8} **CRITICAL: ALWAYS CHECK EXISTING ARTIFACTS FIRST** \u{1F6A8}
5120
- Before creating new artifacts, ALWAYS examine existing artifacts to see if they contain relevant information for the current topic or question.
5121
-
5122
- You CAN and SHOULD retrieve information from existing artifacts to answer user questions.
5123
- Available artifacts contain structured data that you can access in two ways:
5124
-
5125
- 1. **SUMMARY DATA**: Read the summary_data directly from available artifacts for basic information
5126
- 2. **FULL DATA**: Use the get_artifact tool to retrieve complete artifact data (both summary_data and full_data) when you need detailed information
5127
-
5128
- **REUSE EXISTING ARTIFACTS WHEN POSSIBLE:**
5129
- - Look for artifacts with similar topics, names, or descriptions
5130
- - Check if existing artifacts can answer the current question
5131
- - Use existing artifact data instead of creating duplicates
5132
- - Only create new artifacts if existing ones don't contain the needed information
5133
- - Prioritize reusing relevant existing artifacts over creating new ones
5134
-
5135
- HOW TO USE ARTIFACT DATA:
5136
- - Read summary_data from available artifacts for quick answers
5137
- - Use get_artifact tool when you need comprehensive details
5138
- - Extract specific information to answer user questions accurately
5139
- - Reference artifacts when citing the information source
5140
- - Combine information from multiple existing artifacts when relevant
5141
-
5142
- \u{1F6A8} **MANDATORY CITATION POLICY** \u{1F6A8}
5143
- EVERY piece of information from existing artifacts MUST be properly cited:
5144
- - When referencing information from existing artifacts = MUST cite with artifact reference
5145
- - When discussing artifact data = MUST cite the artifact source
5146
- - When using artifact information = MUST reference the artifact
5147
- - NO INFORMATION from existing artifacts can be presented without proper citation
5148
-
5149
- CITATION PLACEMENT RULES:
5150
- - ALWAYS place artifact citations AFTER complete thoughts and punctuation
5151
- - Never interrupt a sentence or thought with an artifact citation
5152
- - Complete your sentence or thought, add punctuation, THEN add the citation
5153
- - This maintains natural reading flow and professional presentation
5154
-
5155
- \u2705 CORRECT EXAMPLES:
5156
- - "The API uses OAuth 2.0 authentication. <artifact:create id='auth-doc' ...> This process involves three main steps..."
5157
- - "Based on the documentation, there are several authentication methods available. <artifact:create id='auth-methods' ...> The recommended approach is OAuth 2.0."
5158
-
5159
- \u274C WRONG EXAMPLES:
5160
- - "The API uses <artifact:create id='auth-doc' ...> OAuth 2.0 authentication which involves..."
5161
- - "According to <artifact:create id='auth-doc' ...>, the authentication method is OAuth 2.0."
5162
-
5163
- \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
5164
-
5165
- DELEGATION AND ARTIFACTS:
5166
- When you use delegation tools, the response may include artifacts in the parts array. These appear as objects with:
5167
- - kind: "data"
5168
- - data: { artifactId, toolCallId, name, description, type, artifactSummary }
5169
-
5170
- These artifacts become immediately available for you to reference using the artifactId and toolCallId from the response.
5171
- Present delegation results naturally without mentioning the delegation process itself.
5172
-
5173
- 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.`;
5174
-
5175
5526
  // templates/v1/phase1/system-prompt.xml?raw
5176
5527
  var system_prompt_default = `<system_message>
5177
5528
  <agent_identity>
@@ -5288,6 +5639,68 @@ var thinking_preparation_default = `<thinking_preparation_mode>
5288
5639
  // templates/v1/phase1/tool.xml?raw
5289
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> ";
5290
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
+
5291
5704
  // src/agents/versions/v1/Phase1Config.ts
5292
5705
  getLogger("Phase1Config");
5293
5706
  var Phase1Config = class _Phase1Config {
@@ -5423,8 +5836,8 @@ SELECTOR REQUIREMENTS:
5423
5836
 
5424
5837
  CRITICAL: SELECTOR HIERARCHY
5425
5838
  - base_selector: Points to ONE specific item in the tool result
5426
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
5427
- - 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"
5428
5841
 
5429
5842
  COMMON FAILURE POINTS (AVOID THESE):
5430
5843
  1. **Array Selection**: result.items (returns array) \u274C
@@ -5456,24 +5869,22 @@ You will create and reference artifacts using inline annotations in your text re
5456
5869
 
5457
5870
  CREATING ARTIFACTS (SERVES AS CITATION):
5458
5871
  Use the artifact:create annotation to extract data from tool results. The creation itself serves as a citation.
5459
- 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"}' />
5460
5873
 
5461
- \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}
5462
5875
 
5463
5876
  \u274C WRONG - Using literal values:
5464
- summary='{"title":"API Documentation","type":"guide"}'
5465
- full='{"description":"This is a comprehensive guide..."}'
5877
+ details='{"title":"API Documentation","type":"guide"}'
5466
5878
 
5467
5879
  \u2705 CORRECT - Using JMESPath selectors (relative to base selector):
5468
- summary='{"title":"metadata.title","doc_type":"document_type"}'
5469
- 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"}'
5470
5881
 
5471
5882
  The selectors extract actual field values from the data structure selected by your base selector.
5472
5883
 
5473
- THE summary AND full PROPERTIES MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE TOOL RESULT!
5474
- - summary: Contains JMESPath selectors relative to the base selector
5475
- - 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
5476
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
5477
5888
  - NEVER put literal values like "Inkeep" or "2023" - always use selectors like "metadata.company" or "founded_year"
5478
5889
 
5479
5890
  \u{1F6AB} FORBIDDEN JMESPATH PATTERNS:
@@ -5533,7 +5944,7 @@ Only use artifact:ref when you need to cite the SAME artifact again for a differ
5533
5944
  Format: <artifact:ref id="artifact-id" tool="tool_call_id" />
5534
5945
 
5535
5946
  EXAMPLE TEXT RESPONSE:
5536
- "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.
5537
5948
 
5538
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."
5539
5950
 
@@ -5589,31 +6000,29 @@ IMPORTANT GUIDELINES:
5589
6000
  return "";
5590
6001
  }
5591
6002
  const typeDescriptions = artifactComponents.map((ac) => {
5592
- let summarySchema = "No schema defined";
5593
- let fullSchema = "No schema defined";
5594
- if (ac.summaryProps?.properties) {
5595
- const summaryDetails = Object.entries(ac.summaryProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
5596
- summarySchema = `Required: ${summaryDetails}`;
5597
- }
5598
- if (ac.fullProps?.properties) {
5599
- const fullDetails = Object.entries(ac.fullProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
5600
- 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}`;
5601
6010
  }
5602
6011
  return ` - "${ac.name}": ${ac.description || "No description available"}
5603
- Summary Props: ${summarySchema}
5604
- Full Props: ${fullSchema}`;
6012
+ ${schemaDescription}`;
5605
6013
  }).join("\n\n");
5606
6014
  return `
5607
6015
  AVAILABLE ARTIFACT TYPES:
5608
6016
 
5609
6017
  ${typeDescriptions}
5610
6018
 
5611
- \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}
5612
6020
  - Only use property names that are defined in the artifact component schema above
5613
6021
  - Do NOT make up arbitrary property names like "founders", "nick_details", "year"
5614
- - 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
5615
6023
  - Your JMESPath selectors must extract values for these exact schema-defined properties
5616
- - 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
5617
6026
 
5618
6027
  \u{1F6A8} CRITICAL: USE EXACT ARTIFACT TYPE NAMES IN QUOTES! \u{1F6A8}
5619
6028
  - MUST use the exact type name shown in quotes above
@@ -5624,7 +6033,11 @@ ${typeDescriptions}
5624
6033
  }
5625
6034
  generateArtifactsSection(templates, artifacts, hasArtifactComponents = false, artifactComponents, hasGraphArtifactComponents) {
5626
6035
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
5627
- const rules = this.getArtifactReferencingRules(hasArtifactComponents, templates, shouldShowReferencingRules);
6036
+ const rules = this.getArtifactReferencingRules(
6037
+ hasArtifactComponents,
6038
+ templates,
6039
+ shouldShowReferencingRules
6040
+ );
5628
6041
  const creationInstructions = this.getArtifactCreationInstructions(
5629
6042
  hasArtifactComponents,
5630
6043
  artifactComponents
@@ -5719,6 +6132,12 @@ ${propertiesXml}
5719
6132
  }
5720
6133
  };
5721
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
+
5722
6141
  // templates/v1/phase2/system-prompt.xml?raw
5723
6142
  var system_prompt_default2 = `<phase2_system_message>
5724
6143
  <instruction>
@@ -5758,12 +6177,6 @@ var system_prompt_default2 = `<phase2_system_message>
5758
6177
  </requirements>
5759
6178
  </phase2_system_message>`;
5760
6179
 
5761
- // templates/v1/phase2/data-components.xml?raw
5762
- 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>';
5763
-
5764
- // templates/v1/phase2/data-component.xml?raw
5765
- 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> ";
5766
-
5767
6180
  // src/agents/versions/v1/Phase2Config.ts
5768
6181
  var Phase2Config = class {
5769
6182
  getArtifactCreationGuidance() {
@@ -5809,17 +6222,15 @@ When the same field names appear at different levels (like 'content', 'title', '
5809
6222
 
5810
6223
  CRITICAL: SELECTOR HIERARCHY
5811
6224
  - base_selector: Points to ONE specific item in the tool result
5812
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
5813
- - 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"
5814
6227
 
5815
6228
  \u274C WRONG EXAMPLE:
5816
6229
  {
5817
6230
  "base_selector": "result.content[?title=='Guide']",
5818
- "summary_props": {
6231
+ "details_selector": {
5819
6232
  "title": "Guide", // \u274C This is a literal value, not a selector!
5820
- "url": "result.content[?title=='Guide'].url" // \u274C This is absolute, not relative!
5821
- },
5822
- "full_props": {
6233
+ "url": "result.content[?title=='Guide'].url", // \u274C This is absolute, not relative!
5823
6234
  "description": "A comprehensive guide", // \u274C Literal value instead of selector!
5824
6235
  "content": "result.content[?title=='Guide'].content" // \u274C Absolute path instead of relative!
5825
6236
  }
@@ -5828,11 +6239,9 @@ CRITICAL: SELECTOR HIERARCHY
5828
6239
  \u2705 CORRECT EXAMPLE:
5829
6240
  {
5830
6241
  "base_selector": "result.content[?title=='Guide']",
5831
- "summary_props": {
6242
+ "details_selector": {
5832
6243
  "title": "title", // \u2705 Relative selector to get title field
5833
- "url": "url" // \u2705 Relative selector to get url field
5834
- },
5835
- "full_props": {
6244
+ "url": "url", // \u2705 Relative selector to get url field
5836
6245
  "description": "description", // \u2705 Relative selector
5837
6246
  "content": "content", // \u2705 Relative selector
5838
6247
  "metadata": "metadata.details" // \u2705 Relative selector with nesting
@@ -5918,8 +6327,7 @@ EXAMPLE STRUCTURED RESPONSE:
5918
6327
  "tool_call_id": "call_abc123",
5919
6328
  "type": "APIDoc",
5920
6329
  "base_selector": "result.documents[?type=='api']",
5921
- "summary_props": {"title": "metadata.title", "endpoint": "api.endpoint"},
5922
- "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"}
5923
6331
  }
5924
6332
  },
5925
6333
  {
@@ -5999,14 +6407,14 @@ IMPORTANT GUIDELINES:
5999
6407
  return "";
6000
6408
  }
6001
6409
  const componentDescriptions = artifactComponents.map((ac) => {
6002
- 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";
6003
- 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";
6004
6414
  return ` ArtifactCreate_${ac.name}:
6005
6415
  Description: ${ac.description || "Extract and structure data"}
6006
- Summary Properties:
6007
- ${summaryProps}
6008
- Full Properties:
6009
- ${fullProps}`;
6416
+ Schema Properties:
6417
+ ${schemaProps}`;
6010
6418
  }).join("\n\n");
6011
6419
  return `
6012
6420
  AVAILABLE ARTIFACT TYPES:
@@ -6020,8 +6428,14 @@ ${componentDescriptions}`;
6020
6428
  const dataComponentsDescription = dataComponents.map((dc) => `${dc.name}: ${dc.description}`).join(", ");
6021
6429
  const dataComponentsXml = dataComponents.map((dataComponent) => this.generateDataComponentXml(dataComponent)).join("\n ");
6022
6430
  let dataComponentsSection = data_components_default;
6023
- dataComponentsSection = dataComponentsSection.replace("{{DATA_COMPONENTS_LIST}}", dataComponentsDescription);
6024
- 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
+ );
6025
6439
  return dataComponentsSection;
6026
6440
  }
6027
6441
  generateDataComponentXml(dataComponent) {
@@ -6093,14 +6507,21 @@ ${artifact_retrieval_guidance_default}
6093
6507
  * Assemble the complete Phase 2 system prompt for structured output generation
6094
6508
  */
6095
6509
  assemblePhase2Prompt(config) {
6096
- const { corePrompt, dataComponents, artifactComponents, hasArtifactComponents, hasGraphArtifactComponents, artifacts = [] } = config;
6510
+ const {
6511
+ corePrompt,
6512
+ dataComponents,
6513
+ artifactComponents,
6514
+ hasArtifactComponents,
6515
+ hasGraphArtifactComponents,
6516
+ artifacts = []
6517
+ } = config;
6097
6518
  let allDataComponents = [...dataComponents];
6098
6519
  if (hasArtifactComponents && artifactComponents) {
6099
6520
  const artifactCreateComponents = ArtifactCreateSchema.getDataComponents(
6100
6521
  "tenant",
6101
6522
  // placeholder - not used in Phase2
6102
6523
  "",
6103
- // placeholder - not used in Phase2
6524
+ // placeholder - not used in Phase2
6104
6525
  artifactComponents
6105
6526
  );
6106
6527
  allDataComponents = [...dataComponents, ...artifactCreateComponents];
@@ -6108,8 +6529,15 @@ ${artifact_retrieval_guidance_default}
6108
6529
  const dataComponentsSection = this.generateDataComponentsSection(allDataComponents);
6109
6530
  const artifactsSection = this.generateArtifactsSection(artifacts);
6110
6531
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
6111
- const artifactGuidance = this.getStructuredArtifactGuidance(hasArtifactComponents, artifactComponents, shouldShowReferencingRules);
6112
- 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
+ );
6113
6541
  let phase2Prompt = system_prompt_default2;
6114
6542
  phase2Prompt = phase2Prompt.replace("{{CORE_INSTRUCTIONS}}", corePrompt);
6115
6543
  phase2Prompt = phase2Prompt.replace("{{DATA_COMPONENTS_SECTION}}", dataComponentsSection);
@@ -6130,7 +6558,7 @@ function hasToolCallWithPrefix(prefix) {
6130
6558
  return false;
6131
6559
  };
6132
6560
  }
6133
- var logger16 = getLogger("Agent");
6561
+ var logger17 = getLogger("Agent");
6134
6562
  var CONSTANTS = {
6135
6563
  MAX_GENERATION_STEPS: 12,
6136
6564
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -6411,7 +6839,10 @@ var Agent = class {
6411
6839
  ]);
6412
6840
  }
6413
6841
  async getMcpTools(sessionId, streamRequestId) {
6414
- 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)) || []) || [];
6415
6846
  if (!sessionId) {
6416
6847
  const combinedTools = tools.reduce((acc, tool3) => {
6417
6848
  return Object.assign(acc, tool3);
@@ -6431,14 +6862,14 @@ var Agent = class {
6431
6862
  for (const toolSet of tools) {
6432
6863
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
6433
6864
  if (!isValidTool(originalTool)) {
6434
- logger16.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6865
+ logger17.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6435
6866
  continue;
6436
6867
  }
6437
6868
  const sessionWrappedTool = tool({
6438
6869
  description: originalTool.description,
6439
6870
  inputSchema: originalTool.inputSchema,
6440
6871
  execute: async (args, { toolCallId }) => {
6441
- logger16.debug({ toolName, toolCallId }, "MCP Tool Called");
6872
+ logger17.debug({ toolName, toolCallId }, "MCP Tool Called");
6442
6873
  try {
6443
6874
  const rawResult = await originalTool.execute(args, { toolCallId });
6444
6875
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -6452,7 +6883,7 @@ var Agent = class {
6452
6883
  });
6453
6884
  return { result: enhancedResult, toolCallId };
6454
6885
  } catch (error) {
6455
- logger16.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6886
+ logger17.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6456
6887
  throw error;
6457
6888
  }
6458
6889
  }
@@ -6471,6 +6902,9 @@ var Agent = class {
6471
6902
  * Convert database McpTool to builder MCPToolConfig format
6472
6903
  */
6473
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
+ }
6474
6908
  return {
6475
6909
  id: tool3.id,
6476
6910
  name: tool3.name,
@@ -6539,6 +6973,9 @@ var Agent = class {
6539
6973
  selectedTools
6540
6974
  );
6541
6975
  } else {
6976
+ if (tool3.config.type !== "mcp") {
6977
+ throw new Error(`Cannot build server config for non-MCP tool: ${tool3.id}`);
6978
+ }
6542
6979
  serverConfig = {
6543
6980
  type: tool3.config.mcp.transport?.type || MCPTransportType.streamableHttp,
6544
6981
  url: tool3.config.mcp.server.url,
@@ -6547,7 +6984,7 @@ var Agent = class {
6547
6984
  headers: agentToolRelationHeaders
6548
6985
  };
6549
6986
  }
6550
- logger16.info(
6987
+ logger17.info(
6551
6988
  {
6552
6989
  toolName: tool3.name,
6553
6990
  credentialReferenceId,
@@ -6572,7 +7009,7 @@ var Agent = class {
6572
7009
  this.mcpClientCache.set(cacheKey, client);
6573
7010
  } catch (error) {
6574
7011
  this.mcpConnectionLocks.delete(cacheKey);
6575
- logger16.error(
7012
+ logger17.error(
6576
7013
  {
6577
7014
  toolName: tool3.name,
6578
7015
  agentId: this.config.id,
@@ -6596,7 +7033,7 @@ var Agent = class {
6596
7033
  await client.connect();
6597
7034
  return client;
6598
7035
  } catch (error) {
6599
- logger16.error(
7036
+ logger17.error(
6600
7037
  {
6601
7038
  toolName: tool3.name,
6602
7039
  agentId: this.config.id,
@@ -6607,39 +7044,110 @@ var Agent = class {
6607
7044
  throw error;
6608
7045
  }
6609
7046
  }
6610
- getFunctionTools(streamRequestId) {
6611
- if (!this.config.functionTools) return {};
7047
+ async getFunctionTools(sessionId, streamRequestId) {
6612
7048
  const functionTools = {};
6613
- for (const funcTool of this.config.functionTools) {
6614
- const aiTool = tool({
6615
- description: funcTool.description,
6616
- inputSchema: funcTool.schema || z.object({}),
6617
- 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
+ }
6618
7057
  });
6619
- functionTools[funcTool.name] = this.wrapToolWithStreaming(
6620
- funcTool.name,
6621
- aiTool,
6622
- streamRequestId,
6623
- "tool"
6624
- );
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");
6625
7129
  }
6626
7130
  return functionTools;
6627
7131
  }
6628
7132
  /**
6629
7133
  * Get resolved context using ContextResolver - will return cached data or fetch fresh data as needed
6630
7134
  */
6631
- async getResolvedContext(conversationId, requestContext) {
7135
+ async getResolvedContext(conversationId, headers) {
6632
7136
  try {
6633
7137
  if (!this.config.contextConfigId) {
6634
- 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");
6635
7139
  return null;
6636
7140
  }
6637
7141
  const contextConfig = await getContextConfigById(dbClient_default)({
6638
- scopes: { tenantId: this.config.tenantId, projectId: this.config.projectId },
7142
+ scopes: {
7143
+ tenantId: this.config.tenantId,
7144
+ projectId: this.config.projectId,
7145
+ graphId: this.config.graphId
7146
+ },
6639
7147
  id: this.config.contextConfigId
6640
7148
  });
6641
7149
  if (!contextConfig) {
6642
- logger16.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7150
+ logger17.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
6643
7151
  return null;
6644
7152
  }
6645
7153
  if (!this.contextResolver) {
@@ -6648,7 +7156,7 @@ var Agent = class {
6648
7156
  const result = await this.contextResolver.resolve(contextConfig, {
6649
7157
  triggerEvent: "invocation",
6650
7158
  conversationId,
6651
- requestContext: requestContext || {},
7159
+ headers: headers || {},
6652
7160
  tenantId: this.config.tenantId
6653
7161
  });
6654
7162
  const contextWithBuiltins = {
@@ -6656,7 +7164,7 @@ var Agent = class {
6656
7164
  $now: (/* @__PURE__ */ new Date()).toISOString(),
6657
7165
  $env: process.env
6658
7166
  };
6659
- logger16.debug(
7167
+ logger17.debug(
6660
7168
  {
6661
7169
  conversationId,
6662
7170
  contextConfigId: contextConfig.id,
@@ -6670,7 +7178,7 @@ var Agent = class {
6670
7178
  );
6671
7179
  return contextWithBuiltins;
6672
7180
  } catch (error) {
6673
- logger16.error(
7181
+ logger17.error(
6674
7182
  {
6675
7183
  conversationId,
6676
7184
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6694,7 +7202,7 @@ var Agent = class {
6694
7202
  });
6695
7203
  return graphDefinition?.graphPrompt || void 0;
6696
7204
  } catch (error) {
6697
- logger16.warn(
7205
+ logger17.warn(
6698
7206
  {
6699
7207
  graphId: this.config.graphId,
6700
7208
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6723,7 +7231,7 @@ var Agent = class {
6723
7231
  (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
6724
7232
  );
6725
7233
  } catch (error) {
6726
- logger16.warn(
7234
+ logger17.warn(
6727
7235
  {
6728
7236
  graphId: this.config.graphId,
6729
7237
  tenantId: this.config.tenantId,
@@ -6752,7 +7260,7 @@ var Agent = class {
6752
7260
  preserveUnresolved: false
6753
7261
  });
6754
7262
  } catch (error) {
6755
- logger16.error(
7263
+ logger17.error(
6756
7264
  {
6757
7265
  conversationId,
6758
7266
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6799,7 +7307,7 @@ var Agent = class {
6799
7307
  preserveUnresolved: false
6800
7308
  });
6801
7309
  } catch (error) {
6802
- logger16.error(
7310
+ logger17.error(
6803
7311
  {
6804
7312
  conversationId,
6805
7313
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6811,9 +7319,24 @@ var Agent = class {
6811
7319
  }
6812
7320
  const streamRequestId = runtimeContext?.metadata?.streamRequestId;
6813
7321
  const mcpTools = await this.getMcpTools(void 0, streamRequestId);
6814
- const functionTools = this.getFunctionTools(streamRequestId);
7322
+ const functionTools = await this.getFunctionTools(streamRequestId || "");
6815
7323
  const relationTools = this.getRelationTools(runtimeContext);
6816
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
+ );
6817
7340
  const toolDefinitions = Object.entries(allTools).map(([name, tool3]) => ({
6818
7341
  name,
6819
7342
  description: tool3.description || "",
@@ -6838,7 +7361,7 @@ var Agent = class {
6838
7361
  preserveUnresolved: false
6839
7362
  });
6840
7363
  } catch (error) {
6841
- logger16.error(
7364
+ logger17.error(
6842
7365
  {
6843
7366
  conversationId,
6844
7367
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6865,23 +7388,29 @@ var Agent = class {
6865
7388
  }
6866
7389
  getArtifactTools() {
6867
7390
  return tool({
6868
- 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.",
6869
7392
  inputSchema: z.object({
6870
- 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.")
6871
7395
  }),
6872
- execute: async ({ artifactId }) => {
6873
- logger16.info({ artifactId }, "get_artifact executed");
6874
- const artifact = await getLedgerArtifacts(dbClient_default)({
6875
- scopes: {
6876
- tenantId: this.config.tenantId,
6877
- projectId: this.config.projectId
6878
- },
6879
- artifactId
6880
- });
6881
- if (!artifact) {
6882
- 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`);
6883
7406
  }
6884
- 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
+ };
6885
7414
  }
6886
7415
  });
6887
7416
  }
@@ -6899,7 +7428,7 @@ var Agent = class {
6899
7428
  });
6900
7429
  }
6901
7430
  // Provide a default tool set that is always available to the agent.
6902
- async getDefaultTools(sessionId, streamRequestId) {
7431
+ async getDefaultTools(_sessionId, streamRequestId) {
6903
7432
  const defaultTools = {};
6904
7433
  if (await this.graphHasArtifactComponents()) {
6905
7434
  defaultTools.get_reference_artifact = this.getArtifactTools();
@@ -6987,13 +7516,19 @@ var Agent = class {
6987
7516
  if (Array.isArray(obj)) {
6988
7517
  obj.slice(0, 3).forEach((item) => {
6989
7518
  if (item && typeof item === "object") {
6990
- Object.keys(item).forEach((key) => fields.add(key));
7519
+ Object.keys(item).forEach((key) => {
7520
+ fields.add(key);
7521
+ });
6991
7522
  }
6992
7523
  });
6993
7524
  } else if (obj && typeof obj === "object") {
6994
- Object.keys(obj).forEach((key) => fields.add(key));
7525
+ Object.keys(obj).forEach((key) => {
7526
+ fields.add(key);
7527
+ });
6995
7528
  Object.values(obj).forEach((value) => {
6996
- findCommonFields(value, depth + 1).forEach((field) => fields.add(field));
7529
+ findCommonFields(value, depth + 1).forEach((field) => {
7530
+ fields.add(field);
7531
+ });
6997
7532
  });
6998
7533
  }
6999
7534
  return fields;
@@ -7092,8 +7627,7 @@ var Agent = class {
7092
7627
  artifactGuidance: {
7093
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.",
7094
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']")`,
7095
- summaryProps: '\u{1F4DD} Use relative selectors from that item (e.g., "title", "metadata.category", "properties.status")',
7096
- 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")',
7097
7631
  avoidLiterals: "\u274C NEVER use literal values - always use field selectors to extract from data",
7098
7632
  avoidArrays: "\u2728 ALWAYS filter arrays to single items using [?condition] - NEVER use [*] notation which returns arrays",
7099
7633
  nestedKeys: "\u{1F511} For structures with repeated keys (like result.content.data.content.items.content), use full paths with filtering at each level",
@@ -7120,7 +7654,7 @@ var Agent = class {
7120
7654
  };
7121
7655
  return enhanced;
7122
7656
  } catch (error) {
7123
- logger16.warn({ error }, "Failed to enhance tool result with structure hints");
7657
+ logger17.warn({ error }, "Failed to enhance tool result with structure hints");
7124
7658
  return result;
7125
7659
  }
7126
7660
  }
@@ -7135,7 +7669,7 @@ var Agent = class {
7135
7669
  }
7136
7670
  });
7137
7671
  } catch (error) {
7138
- logger16.error(
7672
+ logger17.error(
7139
7673
  { error, graphId: this.config.graphId },
7140
7674
  "Failed to check graph artifact components"
7141
7675
  );
@@ -7178,7 +7712,7 @@ var Agent = class {
7178
7712
  // Normal prompt with data components
7179
7713
  this.buildSystemPrompt(runtimeContext, true),
7180
7714
  // Thinking prompt without data components
7181
- Promise.resolve(this.getFunctionTools(streamRequestId)),
7715
+ this.getFunctionTools(sessionId, streamRequestId),
7182
7716
  Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
7183
7717
  this.getDefaultTools(sessionId, streamRequestId)
7184
7718
  ]);
@@ -7236,7 +7770,7 @@ var Agent = class {
7236
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;
7237
7771
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
7238
7772
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
7239
- logger16.warn(
7773
+ logger17.warn(
7240
7774
  {
7241
7775
  requestedTimeout: modelSettings.maxDuration * 1e3,
7242
7776
  appliedTimeout: timeoutMs,
@@ -7278,7 +7812,7 @@ var Agent = class {
7278
7812
  }
7279
7813
  );
7280
7814
  } catch (error) {
7281
- logger16.debug({ error }, "Failed to track agent reasoning");
7815
+ logger17.debug({ error }, "Failed to track agent reasoning");
7282
7816
  }
7283
7817
  }
7284
7818
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7382,7 +7916,7 @@ var Agent = class {
7382
7916
  }
7383
7917
  );
7384
7918
  } catch (error) {
7385
- logger16.debug({ error }, "Failed to track agent reasoning");
7919
+ logger17.debug({ error }, "Failed to track agent reasoning");
7386
7920
  }
7387
7921
  }
7388
7922
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7674,7 +8208,7 @@ ${output}${structureHintsFormatted}`;
7674
8208
  };
7675
8209
 
7676
8210
  // src/agents/generateTaskHandler.ts
7677
- var logger17 = getLogger("generateTaskHandler");
8211
+ var logger18 = getLogger("generateTaskHandler");
7678
8212
  var createTaskHandler = (config, credentialStoreRegistry) => {
7679
8213
  return async (task) => {
7680
8214
  try {
@@ -7727,7 +8261,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7727
8261
  }
7728
8262
  })
7729
8263
  ]);
7730
- logger17.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8264
+ logger18.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
7731
8265
  const enhancedInternalRelations = await Promise.all(
7732
8266
  internalRelations.map(async (relation) => {
7733
8267
  try {
@@ -7756,7 +8290,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7756
8290
  return { ...relation, description: enhancedDescription };
7757
8291
  }
7758
8292
  } catch (error) {
7759
- logger17.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
8293
+ logger18.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
7760
8294
  }
7761
8295
  return relation;
7762
8296
  })
@@ -7851,12 +8385,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7851
8385
  },
7852
8386
  credentialStoreRegistry
7853
8387
  );
8388
+ const artifactStreamRequestId = task.context?.metadata?.streamRequestId;
8389
+ if (artifactStreamRequestId && artifactComponents.length > 0) {
8390
+ graphSessionManager.updateArtifactComponents(artifactStreamRequestId, artifactComponents);
8391
+ }
7854
8392
  let contextId = task.context?.conversationId;
7855
8393
  if (!contextId || contextId === "default" || contextId === "") {
7856
8394
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
7857
8395
  if (taskIdMatch) {
7858
8396
  contextId = taskIdMatch[1];
7859
- logger17.info(
8397
+ logger18.info(
7860
8398
  {
7861
8399
  taskId: task.id,
7862
8400
  extractedContextId: contextId,
@@ -7872,7 +8410,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7872
8410
  const isDelegation = task.context?.metadata?.isDelegation === true;
7873
8411
  agent.setDelegationStatus(isDelegation);
7874
8412
  if (isDelegation) {
7875
- logger17.info(
8413
+ logger18.info(
7876
8414
  { agentId: config.agentId, taskId: task.id },
7877
8415
  "Delegated agent - streaming disabled"
7878
8416
  );
@@ -8094,7 +8632,7 @@ async function getRegisteredGraph(executionContext) {
8094
8632
 
8095
8633
  // src/routes/agents.ts
8096
8634
  var app = new OpenAPIHono();
8097
- var logger18 = getLogger("agents");
8635
+ var logger19 = getLogger("agents");
8098
8636
  app.openapi(
8099
8637
  createRoute({
8100
8638
  method: "get",
@@ -8132,7 +8670,7 @@ app.openapi(
8132
8670
  tracestate: c.req.header("tracestate"),
8133
8671
  baggage: c.req.header("baggage")
8134
8672
  };
8135
- logger18.info(
8673
+ logger19.info(
8136
8674
  {
8137
8675
  otelHeaders,
8138
8676
  path: c.req.path,
@@ -8144,7 +8682,7 @@ app.openapi(
8144
8682
  const { tenantId, projectId, graphId, agentId } = executionContext;
8145
8683
  console.dir("executionContext", executionContext);
8146
8684
  if (agentId) {
8147
- logger18.info(
8685
+ logger19.info(
8148
8686
  {
8149
8687
  message: "getRegisteredAgent (agent-level)",
8150
8688
  tenantId,
@@ -8156,7 +8694,7 @@ app.openapi(
8156
8694
  );
8157
8695
  const credentialStores = c.get("credentialStores");
8158
8696
  const agent = await getRegisteredAgent(executionContext, credentialStores);
8159
- logger18.info({ agent }, "agent registered: well-known agent.json");
8697
+ logger19.info({ agent }, "agent registered: well-known agent.json");
8160
8698
  if (!agent) {
8161
8699
  throw createApiError({
8162
8700
  code: "not_found",
@@ -8165,7 +8703,7 @@ app.openapi(
8165
8703
  }
8166
8704
  return c.json(agent.agentCard);
8167
8705
  } else {
8168
- logger18.info(
8706
+ logger19.info(
8169
8707
  {
8170
8708
  message: "getRegisteredGraph (graph-level)",
8171
8709
  tenantId,
@@ -8191,7 +8729,7 @@ app.post("/a2a", async (c) => {
8191
8729
  tracestate: c.req.header("tracestate"),
8192
8730
  baggage: c.req.header("baggage")
8193
8731
  };
8194
- logger18.info(
8732
+ logger19.info(
8195
8733
  {
8196
8734
  otelHeaders,
8197
8735
  path: c.req.path,
@@ -8202,7 +8740,7 @@ app.post("/a2a", async (c) => {
8202
8740
  const executionContext = getRequestExecutionContext(c);
8203
8741
  const { tenantId, projectId, graphId, agentId } = executionContext;
8204
8742
  if (agentId) {
8205
- logger18.info(
8743
+ logger19.info(
8206
8744
  {
8207
8745
  message: "a2a (agent-level)",
8208
8746
  tenantId,
@@ -8226,7 +8764,7 @@ app.post("/a2a", async (c) => {
8226
8764
  }
8227
8765
  return a2aHandler(c, agent);
8228
8766
  } else {
8229
- logger18.info(
8767
+ logger19.info(
8230
8768
  {
8231
8769
  message: "a2a (graph-level)",
8232
8770
  tenantId,
@@ -8275,14 +8813,14 @@ app.post("/a2a", async (c) => {
8275
8813
  }
8276
8814
  });
8277
8815
  var agents_default = app;
8278
- var logger19 = getLogger("Transfer");
8816
+ var logger20 = getLogger("Transfer");
8279
8817
  async function executeTransfer({
8280
8818
  tenantId,
8281
8819
  threadId,
8282
8820
  projectId,
8283
8821
  targetAgentId
8284
8822
  }) {
8285
- logger19.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8823
+ logger20.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8286
8824
  await setActiveAgentForThread(dbClient_default)({
8287
8825
  scopes: { tenantId, projectId },
8288
8826
  threadId,
@@ -8864,7 +9402,7 @@ function createMCPStreamHelper() {
8864
9402
  }
8865
9403
 
8866
9404
  // src/handlers/executionHandler.ts
8867
- var logger20 = getLogger("ExecutionHandler");
9405
+ var logger21 = getLogger("ExecutionHandler");
8868
9406
  var ExecutionHandler = class {
8869
9407
  constructor() {
8870
9408
  // Hardcoded error limit - separate from configurable stopWhen
@@ -8885,12 +9423,23 @@ var ExecutionHandler = class {
8885
9423
  * @returns
8886
9424
  */
8887
9425
  async execute(params) {
8888
- const { executionContext, conversationId, userMessage, initialAgentId, requestId: requestId2, sseHelper } = params;
9426
+ const {
9427
+ executionContext,
9428
+ conversationId,
9429
+ userMessage,
9430
+ initialAgentId,
9431
+ requestId: requestId2,
9432
+ sseHelper,
9433
+ emitOperations
9434
+ } = params;
8889
9435
  const { tenantId, projectId, graphId, apiKey, baseUrl } = executionContext;
8890
9436
  registerStreamHelper(requestId2, sseHelper);
8891
9437
  graphSessionManager.createSession(requestId2, graphId, tenantId, projectId, conversationId);
8892
- logger20.info(
8893
- { sessionId: requestId2, graphId, conversationId },
9438
+ if (emitOperations) {
9439
+ graphSessionManager.enableEmitOperations(requestId2);
9440
+ }
9441
+ logger21.info(
9442
+ { sessionId: requestId2, graphId, conversationId, emitOperations },
8894
9443
  "Created GraphSession for message execution"
8895
9444
  );
8896
9445
  let graphConfig = null;
@@ -8904,7 +9453,7 @@ var ExecutionHandler = class {
8904
9453
  );
8905
9454
  }
8906
9455
  } catch (error) {
8907
- logger20.error(
9456
+ logger21.error(
8908
9457
  {
8909
9458
  error: error instanceof Error ? error.message : "Unknown error",
8910
9459
  stack: error instanceof Error ? error.stack : void 0
@@ -8920,7 +9469,7 @@ var ExecutionHandler = class {
8920
9469
  try {
8921
9470
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
8922
9471
  const taskId = `task_${conversationId}-${requestId2}`;
8923
- logger20.info(
9472
+ logger21.info(
8924
9473
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
8925
9474
  "Attempting to create or reuse existing task"
8926
9475
  );
@@ -8944,7 +9493,7 @@ var ExecutionHandler = class {
8944
9493
  agent_id: currentAgentId
8945
9494
  }
8946
9495
  });
8947
- logger20.info(
9496
+ logger21.info(
8948
9497
  {
8949
9498
  taskId,
8950
9499
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -8953,27 +9502,27 @@ var ExecutionHandler = class {
8953
9502
  );
8954
9503
  } catch (error) {
8955
9504
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
8956
- logger20.info(
9505
+ logger21.info(
8957
9506
  { taskId, error: error.message },
8958
9507
  "Task already exists, fetching existing task"
8959
9508
  );
8960
9509
  const existingTask = await getTask(dbClient_default)({ id: taskId });
8961
9510
  if (existingTask) {
8962
9511
  task = existingTask;
8963
- logger20.info(
9512
+ logger21.info(
8964
9513
  { taskId, existingTask },
8965
9514
  "Successfully reused existing task from race condition"
8966
9515
  );
8967
9516
  } else {
8968
- logger20.error({ taskId, error }, "Task constraint failed but task not found");
9517
+ logger21.error({ taskId, error }, "Task constraint failed but task not found");
8969
9518
  throw error;
8970
9519
  }
8971
9520
  } else {
8972
- 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");
8973
9522
  throw error;
8974
9523
  }
8975
9524
  }
8976
- logger20.debug(
9525
+ logger21.debug(
8977
9526
  {
8978
9527
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8979
9528
  executionType: "create_initial_task",
@@ -8991,7 +9540,7 @@ var ExecutionHandler = class {
8991
9540
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
8992
9541
  while (iterations < maxTransfers) {
8993
9542
  iterations++;
8994
- logger20.info(
9543
+ logger21.info(
8995
9544
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
8996
9545
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
8997
9546
  );
@@ -8999,10 +9548,10 @@ var ExecutionHandler = class {
8999
9548
  scopes: { tenantId, projectId },
9000
9549
  conversationId
9001
9550
  });
9002
- logger20.info({ activeAgent }, "activeAgent");
9551
+ logger21.info({ activeAgent }, "activeAgent");
9003
9552
  if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
9004
9553
  currentAgentId = activeAgent.activeAgentId;
9005
- logger20.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9554
+ logger21.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9006
9555
  }
9007
9556
  const agentBaseUrl = `${baseUrl}/agents`;
9008
9557
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -9043,13 +9592,13 @@ var ExecutionHandler = class {
9043
9592
  });
9044
9593
  if (!messageResponse?.result) {
9045
9594
  errorCount++;
9046
- logger20.error(
9595
+ logger21.error(
9047
9596
  { currentAgentId, iterations, errorCount },
9048
9597
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9049
9598
  );
9050
9599
  if (errorCount >= this.MAX_ERRORS) {
9051
9600
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9052
- logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9601
+ logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9053
9602
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9054
9603
  if (task) {
9055
9604
  await updateTask(dbClient_default)({
@@ -9074,7 +9623,7 @@ var ExecutionHandler = class {
9074
9623
  const transferResponse = messageResponse.result;
9075
9624
  const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
9076
9625
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
9077
- logger20.info({ targetAgentId, transferReason }, "transfer response");
9626
+ logger21.info({ targetAgentId, transferReason }, "transfer response");
9078
9627
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
9079
9628
  const { success, targetAgentId: newAgentId } = await executeTransfer({
9080
9629
  projectId,
@@ -9085,7 +9634,7 @@ var ExecutionHandler = class {
9085
9634
  if (success) {
9086
9635
  fromAgentId = currentAgentId;
9087
9636
  currentAgentId = newAgentId;
9088
- logger20.info(
9637
+ logger21.info(
9089
9638
  {
9090
9639
  transferFrom: fromAgentId,
9091
9640
  transferTo: currentAgentId,
@@ -9103,7 +9652,7 @@ var ExecutionHandler = class {
9103
9652
  const graphSessionData = graphSessionManager.getSession(requestId2);
9104
9653
  if (graphSessionData) {
9105
9654
  const sessionSummary = graphSessionData.getSummary();
9106
- logger20.info(sessionSummary, "GraphSession data after completion");
9655
+ logger21.info(sessionSummary, "GraphSession data after completion");
9107
9656
  }
9108
9657
  let textContent = "";
9109
9658
  for (const part of responseParts) {
@@ -9157,22 +9706,22 @@ var ExecutionHandler = class {
9157
9706
  }
9158
9707
  });
9159
9708
  const updateTaskEnd = Date.now();
9160
- logger20.info(
9709
+ logger21.info(
9161
9710
  { duration: updateTaskEnd - updateTaskStart },
9162
9711
  "Completed updateTask operation"
9163
9712
  );
9164
9713
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
9165
9714
  await sseHelper.complete();
9166
- logger20.info({}, "Ending GraphSession and cleaning up");
9715
+ logger21.info({}, "Ending GraphSession and cleaning up");
9167
9716
  graphSessionManager.endSession(requestId2);
9168
- logger20.info({}, "Cleaning up streamHelper");
9717
+ logger21.info({}, "Cleaning up streamHelper");
9169
9718
  unregisterStreamHelper(requestId2);
9170
9719
  let response;
9171
9720
  if (sseHelper instanceof MCPStreamHelper) {
9172
9721
  const captured = sseHelper.getCapturedResponse();
9173
9722
  response = captured.text || "No response content";
9174
9723
  }
9175
- logger20.info({}, "ExecutionHandler returning success");
9724
+ logger21.info({}, "ExecutionHandler returning success");
9176
9725
  return { success: true, iterations, response };
9177
9726
  } catch (error) {
9178
9727
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -9183,13 +9732,13 @@ var ExecutionHandler = class {
9183
9732
  });
9184
9733
  }
9185
9734
  errorCount++;
9186
- logger20.warn(
9735
+ logger21.warn(
9187
9736
  { iterations, errorCount },
9188
9737
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9189
9738
  );
9190
9739
  if (errorCount >= this.MAX_ERRORS) {
9191
9740
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9192
- logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9741
+ logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9193
9742
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9194
9743
  if (task) {
9195
9744
  await updateTask(dbClient_default)({
@@ -9210,7 +9759,7 @@ var ExecutionHandler = class {
9210
9759
  }
9211
9760
  }
9212
9761
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
9213
- logger20.error({ maxTransfers, iterations }, errorMessage);
9762
+ logger21.error({ maxTransfers, iterations }, errorMessage);
9214
9763
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
9215
9764
  if (task) {
9216
9765
  await updateTask(dbClient_default)({
@@ -9229,7 +9778,7 @@ var ExecutionHandler = class {
9229
9778
  unregisterStreamHelper(requestId2);
9230
9779
  return { success: false, error: errorMessage, iterations };
9231
9780
  } catch (error) {
9232
- logger20.error({ error }, "Error in execution handler");
9781
+ logger21.error({ error }, "Error in execution handler");
9233
9782
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
9234
9783
  await sseHelper.writeOperation(
9235
9784
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -9256,7 +9805,7 @@ var ExecutionHandler = class {
9256
9805
 
9257
9806
  // src/routes/chat.ts
9258
9807
  var app2 = new OpenAPIHono();
9259
- var logger21 = getLogger("completionsHandler");
9808
+ var logger22 = getLogger("completionsHandler");
9260
9809
  var chatCompletionsRoute = createRoute({
9261
9810
  method: "post",
9262
9811
  path: "/completions",
@@ -9297,8 +9846,8 @@ var chatCompletionsRoute = createRoute({
9297
9846
  conversationId: z.string().optional().describe("Conversation ID for multi-turn chat"),
9298
9847
  tools: z.array(z.string()).optional().describe("Available tools"),
9299
9848
  runConfig: z.record(z.string(), z.unknown()).optional().describe("Run configuration"),
9300
- requestContext: z.record(z.string(), z.unknown()).optional().describe(
9301
- "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)"
9302
9851
  )
9303
9852
  })
9304
9853
  }
@@ -9374,7 +9923,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9374
9923
  tracestate: c.req.header("tracestate"),
9375
9924
  baggage: c.req.header("baggage")
9376
9925
  };
9377
- logger21.info(
9926
+ logger22.info(
9378
9927
  {
9379
9928
  otelHeaders,
9380
9929
  path: c.req.path,
@@ -9456,18 +10005,18 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9456
10005
  message: "Agent not found"
9457
10006
  });
9458
10007
  }
9459
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
10008
+ const validatedContext = c.get("validatedContext") || body.headers || {};
9460
10009
  const credentialStores = c.get("credentialStores");
9461
10010
  await handleContextResolution({
9462
10011
  tenantId,
9463
10012
  projectId,
9464
10013
  graphId,
9465
10014
  conversationId,
9466
- requestContext: validatedContext,
10015
+ headers: validatedContext,
9467
10016
  dbClient: dbClient_default,
9468
10017
  credentialStores
9469
10018
  });
9470
- logger21.info(
10019
+ logger22.info(
9471
10020
  {
9472
10021
  tenantId,
9473
10022
  projectId,
@@ -9476,7 +10025,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9476
10025
  defaultAgentId,
9477
10026
  activeAgentId: activeAgent?.activeAgentId || "none",
9478
10027
  hasContextConfig: !!agentGraph.contextConfigId,
9479
- hasRequestContext: !!body.requestContext,
10028
+ hasHeaders: !!body.headers,
9480
10029
  hasValidatedContext: !!validatedContext,
9481
10030
  validatedContextKeys: Object.keys(validatedContext)
9482
10031
  },
@@ -9515,7 +10064,9 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9515
10064
  try {
9516
10065
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
9517
10066
  await sseHelper.writeRole();
9518
- logger21.info({ agentId }, "Starting execution");
10067
+ logger22.info({ agentId }, "Starting execution");
10068
+ const emitOperationsHeader = c.req.header("x-emit-operations");
10069
+ const emitOperations = emitOperationsHeader === "true";
9519
10070
  const executionHandler = new ExecutionHandler();
9520
10071
  const result = await executionHandler.execute({
9521
10072
  executionContext,
@@ -9523,9 +10074,10 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9523
10074
  userMessage,
9524
10075
  initialAgentId: agentId,
9525
10076
  requestId: requestId2,
9526
- sseHelper
10077
+ sseHelper,
10078
+ emitOperations
9527
10079
  });
9528
- logger21.info(
10080
+ logger22.info(
9529
10081
  { result },
9530
10082
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
9531
10083
  );
@@ -9539,7 +10091,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9539
10091
  }
9540
10092
  await sseHelper.complete();
9541
10093
  } catch (error) {
9542
- logger21.error(
10094
+ logger22.error(
9543
10095
  {
9544
10096
  error: error instanceof Error ? error.message : error,
9545
10097
  stack: error instanceof Error ? error.stack : void 0
@@ -9556,12 +10108,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9556
10108
  );
9557
10109
  await sseHelper.complete();
9558
10110
  } catch (streamError) {
9559
- logger21.error({ streamError }, "Failed to write error to stream");
10111
+ logger22.error({ streamError }, "Failed to write error to stream");
9560
10112
  }
9561
10113
  }
9562
10114
  });
9563
10115
  } catch (error) {
9564
- logger21.error(
10116
+ logger22.error(
9565
10117
  {
9566
10118
  error: error instanceof Error ? error.message : error,
9567
10119
  stack: error instanceof Error ? error.stack : void 0
@@ -9585,7 +10137,7 @@ var getMessageText = (content) => {
9585
10137
  };
9586
10138
  var chat_default = app2;
9587
10139
  var app3 = new OpenAPIHono();
9588
- var logger22 = getLogger("chatDataStream");
10140
+ var logger23 = getLogger("chatDataStream");
9589
10141
  var chatDataStreamRoute = createRoute({
9590
10142
  method: "post",
9591
10143
  path: "/chat",
@@ -9616,7 +10168,7 @@ var chatDataStreamRoute = createRoute({
9616
10168
  ),
9617
10169
  id: z$1.string().optional(),
9618
10170
  conversationId: z$1.string().optional(),
9619
- 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")
9620
10172
  })
9621
10173
  }
9622
10174
  }
@@ -9689,20 +10241,20 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9689
10241
  message: "Agent not found"
9690
10242
  });
9691
10243
  }
9692
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
10244
+ const validatedContext = c.get("validatedContext") || body.headers || {};
9693
10245
  const credentialStores = c.get("credentialStores");
9694
10246
  await handleContextResolution({
9695
10247
  tenantId,
9696
10248
  projectId,
9697
10249
  graphId,
9698
10250
  conversationId,
9699
- requestContext: validatedContext,
10251
+ headers: validatedContext,
9700
10252
  dbClient: dbClient_default,
9701
10253
  credentialStores
9702
10254
  });
9703
10255
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
9704
10256
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
9705
- logger22.info({ userText, lastUserMessage }, "userText");
10257
+ logger23.info({ userText, lastUserMessage }, "userText");
9706
10258
  const messageSpan = trace.getActiveSpan();
9707
10259
  if (messageSpan) {
9708
10260
  messageSpan.setAttributes({
@@ -9731,6 +10283,8 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9731
10283
  execute: async ({ writer }) => {
9732
10284
  const streamHelper = createVercelStreamHelper(writer);
9733
10285
  try {
10286
+ const emitOperationsHeader = c.req.header("x-emit-operations");
10287
+ const emitOperations = emitOperationsHeader === "true";
9734
10288
  const executionHandler = new ExecutionHandler();
9735
10289
  const result = await executionHandler.execute({
9736
10290
  executionContext,
@@ -9738,13 +10292,14 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9738
10292
  userMessage: userText,
9739
10293
  initialAgentId: agentId,
9740
10294
  requestId: `chatds-${Date.now()}`,
9741
- sseHelper: streamHelper
10295
+ sseHelper: streamHelper,
10296
+ emitOperations
9742
10297
  });
9743
10298
  if (!result.success) {
9744
10299
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
9745
10300
  }
9746
10301
  } catch (err) {
9747
- logger22.error({ err }, "Streaming error");
10302
+ logger23.error({ err }, "Streaming error");
9748
10303
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
9749
10304
  } finally {
9750
10305
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -9765,7 +10320,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9765
10320
  )
9766
10321
  );
9767
10322
  } catch (error) {
9768
- logger22.error({ error }, "chatDataStream error");
10323
+ logger23.error({ error }, "chatDataStream error");
9769
10324
  throw createApiError({
9770
10325
  code: "internal_server_error",
9771
10326
  message: "Failed to process chat completion"
@@ -9776,7 +10331,7 @@ var chatDataStream_default = app3;
9776
10331
  function createMCPSchema(schema) {
9777
10332
  return schema;
9778
10333
  }
9779
- var logger23 = getLogger("mcp");
10334
+ var logger24 = getLogger("mcp");
9780
10335
  var _MockResponseSingleton = class _MockResponseSingleton {
9781
10336
  constructor() {
9782
10337
  __publicField(this, "mockRes");
@@ -9831,21 +10386,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
9831
10386
  id: 0
9832
10387
  });
9833
10388
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
9834
- logger23.info({ sessionId }, "Spoofing initialization message to set transport state");
10389
+ logger24.info({ sessionId }, "Spoofing initialization message to set transport state");
9835
10390
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
9836
10391
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
9837
10392
  try {
9838
10393
  await transport.handleRequest(req, mockRes, spoofInitMessage);
9839
- logger23.info({ sessionId }, "Successfully spoofed initialization");
10394
+ logger24.info({ sessionId }, "Successfully spoofed initialization");
9840
10395
  } catch (spoofError) {
9841
- logger23.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
10396
+ logger24.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
9842
10397
  }
9843
10398
  };
9844
10399
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9845
10400
  const sessionId = req.headers["mcp-session-id"];
9846
- logger23.info({ sessionId }, "Received MCP session ID");
10401
+ logger24.info({ sessionId }, "Received MCP session ID");
9847
10402
  if (!sessionId) {
9848
- logger23.info({ body }, "Missing session ID");
10403
+ logger24.info({ body }, "Missing session ID");
9849
10404
  res.writeHead(400).end(
9850
10405
  JSON.stringify({
9851
10406
  jsonrpc: "2.0",
@@ -9871,7 +10426,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9871
10426
  scopes: { tenantId, projectId },
9872
10427
  conversationId: sessionId
9873
10428
  });
9874
- logger23.info(
10429
+ logger24.info(
9875
10430
  {
9876
10431
  sessionId,
9877
10432
  conversationFound: !!conversation,
@@ -9882,7 +10437,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9882
10437
  "Conversation lookup result"
9883
10438
  );
9884
10439
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
9885
- logger23.info(
10440
+ logger24.info(
9886
10441
  { sessionId, conversationId: conversation?.id },
9887
10442
  "MCP session not found or invalid"
9888
10443
  );
@@ -9943,7 +10498,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
9943
10498
  requestId: requestId2,
9944
10499
  sseHelper: mcpStreamHelper
9945
10500
  });
9946
- logger23.info(
10501
+ logger24.info(
9947
10502
  { result },
9948
10503
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
9949
10504
  );
@@ -9967,7 +10522,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
9967
10522
  ]
9968
10523
  };
9969
10524
  };
9970
- var getServer = async (requestContext, executionContext, conversationId, credentialStores) => {
10525
+ var getServer = async (headers, executionContext, conversationId, credentialStores) => {
9971
10526
  const { tenantId, projectId, graphId } = executionContext;
9972
10527
  setupTracing(conversationId, tenantId, graphId);
9973
10528
  const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
@@ -10023,18 +10578,18 @@ var getServer = async (requestContext, executionContext, conversationId, credent
10023
10578
  projectId,
10024
10579
  graphId,
10025
10580
  conversationId,
10026
- requestContext,
10581
+ headers,
10027
10582
  dbClient: dbClient_default,
10028
10583
  credentialStores
10029
10584
  });
10030
- logger23.info(
10585
+ logger24.info(
10031
10586
  {
10032
10587
  tenantId,
10033
10588
  projectId,
10034
10589
  graphId,
10035
10590
  conversationId,
10036
10591
  hasContextConfig: !!agentGraph.contextConfigId,
10037
- hasRequestContext: !!requestContext,
10592
+ hasHeaders: !!headers,
10038
10593
  hasValidatedContext: !!resolvedContext
10039
10594
  },
10040
10595
  "parameters"
@@ -10089,7 +10644,7 @@ var validateRequestParameters = (c) => {
10089
10644
  };
10090
10645
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
10091
10646
  const { tenantId, projectId, graphId } = executionContext;
10092
- logger23.info({ body }, "Received initialization request");
10647
+ logger24.info({ body }, "Received initialization request");
10093
10648
  const sessionId = getConversationId();
10094
10649
  const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
10095
10650
  scopes: { tenantId, projectId, graphId }
@@ -10129,7 +10684,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10129
10684
  }
10130
10685
  }
10131
10686
  });
10132
- logger23.info(
10687
+ logger24.info(
10133
10688
  { sessionId, conversationId: conversation.id },
10134
10689
  "Created MCP session as conversation"
10135
10690
  );
@@ -10138,9 +10693,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10138
10693
  });
10139
10694
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
10140
10695
  await server.connect(transport);
10141
- logger23.info({ sessionId }, "Server connected for initialization");
10696
+ logger24.info({ sessionId }, "Server connected for initialization");
10142
10697
  res.setHeader("Mcp-Session-Id", sessionId);
10143
- logger23.info(
10698
+ logger24.info(
10144
10699
  {
10145
10700
  sessionId,
10146
10701
  bodyMethod: body?.method,
@@ -10149,7 +10704,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10149
10704
  "About to handle initialization request"
10150
10705
  );
10151
10706
  await transport.handleRequest(req, res, body);
10152
- logger23.info({ sessionId }, "Successfully handled initialization request");
10707
+ logger24.info({ sessionId }, "Successfully handled initialization request");
10153
10708
  return toFetchResponse(res);
10154
10709
  };
10155
10710
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -10177,8 +10732,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10177
10732
  sessionId,
10178
10733
  conversation.metadata?.session_data?.mcpProtocolVersion
10179
10734
  );
10180
- logger23.info({ sessionId }, "Server connected and transport initialized");
10181
- logger23.info(
10735
+ logger24.info({ sessionId }, "Server connected and transport initialized");
10736
+ logger24.info(
10182
10737
  {
10183
10738
  sessionId,
10184
10739
  bodyKeys: Object.keys(body || {}),
@@ -10192,9 +10747,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10192
10747
  );
10193
10748
  try {
10194
10749
  await transport.handleRequest(req, res, body);
10195
- logger23.info({ sessionId }, "Successfully handled MCP request");
10750
+ logger24.info({ sessionId }, "Successfully handled MCP request");
10196
10751
  } catch (transportError) {
10197
- logger23.error(
10752
+ logger24.error(
10198
10753
  {
10199
10754
  sessionId,
10200
10755
  error: transportError,
@@ -10245,13 +10800,13 @@ app4.openapi(
10245
10800
  }
10246
10801
  const { executionContext } = paramValidation;
10247
10802
  const body = c.get("requestBody") || {};
10248
- logger23.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10803
+ logger24.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10249
10804
  const isInitRequest = body.method === "initialize";
10250
10805
  const { req, res } = toReqRes(c.req.raw);
10251
10806
  const validatedContext = c.get("validatedContext") || {};
10252
10807
  const credentialStores = c.get("credentialStores");
10253
- logger23.info({ validatedContext }, "Validated context");
10254
- logger23.info({ req }, "request");
10808
+ logger24.info({ validatedContext }, "Validated context");
10809
+ logger24.info({ req }, "request");
10255
10810
  if (isInitRequest) {
10256
10811
  return await handleInitializationRequest(
10257
10812
  body,
@@ -10273,7 +10828,7 @@ app4.openapi(
10273
10828
  );
10274
10829
  }
10275
10830
  } catch (e) {
10276
- logger23.error(
10831
+ logger24.error(
10277
10832
  {
10278
10833
  error: e instanceof Error ? e.message : e,
10279
10834
  stack: e instanceof Error ? e.stack : void 0
@@ -10285,7 +10840,7 @@ app4.openapi(
10285
10840
  }
10286
10841
  );
10287
10842
  app4.get("/", async (c) => {
10288
- logger23.info({}, "Received GET MCP request");
10843
+ logger24.info({}, "Received GET MCP request");
10289
10844
  return c.json(
10290
10845
  {
10291
10846
  jsonrpc: "2.0",
@@ -10299,7 +10854,7 @@ app4.get("/", async (c) => {
10299
10854
  );
10300
10855
  });
10301
10856
  app4.delete("/", async (c) => {
10302
- logger23.info({}, "Received DELETE MCP request");
10857
+ logger24.info({}, "Received DELETE MCP request");
10303
10858
  return c.json(
10304
10859
  {
10305
10860
  jsonrpc: "2.0",
@@ -10312,7 +10867,7 @@ app4.delete("/", async (c) => {
10312
10867
  var mcp_default = app4;
10313
10868
 
10314
10869
  // src/app.ts
10315
- var logger24 = getLogger("agents-run-api");
10870
+ var logger25 = getLogger("agents-run-api");
10316
10871
  function createExecutionHono(serverConfig, credentialStores) {
10317
10872
  const app6 = new OpenAPIHono();
10318
10873
  app6.use("*", otel());
@@ -10328,7 +10883,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10328
10883
  const body = await c.req.json();
10329
10884
  c.set("requestBody", body);
10330
10885
  } catch (error) {
10331
- 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");
10332
10887
  }
10333
10888
  }
10334
10889
  return next();
@@ -10379,8 +10934,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10379
10934
  if (!isExpectedError) {
10380
10935
  const errorMessage = err instanceof Error ? err.message : String(err);
10381
10936
  const errorStack = err instanceof Error ? err.stack : void 0;
10382
- if (logger24) {
10383
- logger24.error(
10937
+ if (logger25) {
10938
+ logger25.error(
10384
10939
  {
10385
10940
  error: err,
10386
10941
  message: errorMessage,
@@ -10392,8 +10947,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10392
10947
  );
10393
10948
  }
10394
10949
  } else {
10395
- if (logger24) {
10396
- logger24.error(
10950
+ if (logger25) {
10951
+ logger25.error(
10397
10952
  {
10398
10953
  error: err,
10399
10954
  path: c.req.path,
@@ -10410,8 +10965,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10410
10965
  const response = err.getResponse();
10411
10966
  return response;
10412
10967
  } catch (responseError) {
10413
- if (logger24) {
10414
- logger24.error({ error: responseError }, "Error while handling HTTPException response");
10968
+ if (logger25) {
10969
+ logger25.error({ error: responseError }, "Error while handling HTTPException response");
10415
10970
  }
10416
10971
  }
10417
10972
  }
@@ -10445,7 +11000,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10445
11000
  app6.use("*", async (c, next) => {
10446
11001
  const executionContext = c.get("executionContext");
10447
11002
  if (!executionContext) {
10448
- logger24.debug({}, "Empty execution context");
11003
+ logger25.debug({}, "Empty execution context");
10449
11004
  return next();
10450
11005
  }
10451
11006
  const { tenantId, projectId, graphId } = executionContext;
@@ -10454,7 +11009,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10454
11009
  if (requestBody) {
10455
11010
  conversationId = requestBody.conversationId;
10456
11011
  if (!conversationId) {
10457
- logger24.debug({ requestBody }, "No conversation ID found in request body");
11012
+ logger25.debug({ requestBody }, "No conversation ID found in request body");
10458
11013
  }
10459
11014
  }
10460
11015
  const entries = Object.fromEntries(
@@ -10469,7 +11024,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10469
11024
  })
10470
11025
  );
10471
11026
  if (!Object.keys(entries).length) {
10472
- logger24.debug({}, "Empty entries for baggage");
11027
+ logger25.debug({}, "Empty entries for baggage");
10473
11028
  return next();
10474
11029
  }
10475
11030
  const bag = Object.entries(entries).reduce(