@axiom-lattice/core 2.1.24 → 2.1.25

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
@@ -39,6 +39,7 @@ __export(index_exports, {
39
39
  ChunkBufferLatticeManager: () => ChunkBufferLatticeManager,
40
40
  CompositeBackend: () => CompositeBackend,
41
41
  ConsoleLoggerClient: () => ConsoleLoggerClient,
42
+ CustomMetricsClient: () => CustomMetricsClient,
42
43
  DefaultScheduleClient: () => DefaultScheduleClient,
43
44
  EMPTY_CONTENT_WARNING: () => EMPTY_CONTENT_WARNING,
44
45
  EmbeddingsLatticeManager: () => EmbeddingsLatticeManager,
@@ -50,7 +51,10 @@ __export(index_exports, {
50
51
  InMemoryDatabaseConfigStore: () => InMemoryDatabaseConfigStore,
51
52
  InMemoryMailboxStore: () => InMemoryMailboxStore,
52
53
  InMemoryTaskListStore: () => InMemoryTaskListStore,
54
+ InMemoryTenantStore: () => InMemoryTenantStore,
53
55
  InMemoryThreadStore: () => InMemoryThreadStore,
56
+ InMemoryUserStore: () => InMemoryUserStore,
57
+ InMemoryUserTenantLinkStore: () => InMemoryUserTenantLinkStore,
54
58
  LINE_NUMBER_WIDTH: () => LINE_NUMBER_WIDTH,
55
59
  LoggerLatticeManager: () => LoggerLatticeManager,
56
60
  MAX_LINE_LENGTH: () => MAX_LINE_LENGTH,
@@ -61,14 +65,17 @@ __export(index_exports, {
61
65
  MemoryScheduleStorage: () => MemoryScheduleStorage,
62
66
  MemoryType: () => import_protocols2.MemoryType,
63
67
  MessageType: () => MessageType,
68
+ MetricsServerManager: () => MetricsServerManager,
64
69
  ModelLatticeManager: () => ModelLatticeManager,
65
70
  PinoLoggerClient: () => PinoLoggerClient,
66
71
  PostgresDatabase: () => PostgresDatabase,
72
+ PrometheusClient: () => PrometheusClient,
67
73
  Protocols: () => Protocols,
68
74
  QueueLatticeManager: () => QueueLatticeManager,
69
75
  SandboxFilesystem: () => SandboxFilesystem,
70
76
  SandboxLatticeManager: () => SandboxLatticeManager,
71
77
  ScheduleLatticeManager: () => ScheduleLatticeManager,
78
+ SemanticMetricsClient: () => SemanticMetricsClient,
72
79
  SkillLatticeManager: () => SkillLatticeManager,
73
80
  SqlDatabaseManager: () => SqlDatabaseManager,
74
81
  StateBackend: () => StateBackend,
@@ -88,9 +95,16 @@ __export(index_exports, {
88
95
  createAgentTeam: () => createAgentTeam,
89
96
  createFileData: () => createFileData,
90
97
  createInfoSqlTool: () => createInfoSqlTool,
98
+ createListMetricsDataSourcesTool: () => createListMetricsDataSourcesTool,
99
+ createListMetricsServersTool: () => createListMetricsServersTool,
91
100
  createListTablesSqlTool: () => createListTablesSqlTool,
92
101
  createQueryCheckerSqlTool: () => createQueryCheckerSqlTool,
102
+ createQueryMetricDefinitionTool: () => createQueryMetricDefinitionTool,
103
+ createQueryMetricsListTool: () => createQueryMetricsListTool,
104
+ createQuerySemanticMetricDataTool: () => createQuerySemanticMetricDataTool,
93
105
  createQuerySqlTool: () => createQuerySqlTool,
106
+ createQueryTableDefinitionTool: () => createQueryTableDefinitionTool,
107
+ createQueryTablesListTool: () => createQueryTablesListTool,
94
108
  createTeamMiddleware: () => createTeamMiddleware,
95
109
  createTeammateTools: () => createTeammateTools,
96
110
  decrypt: () => decrypt,
@@ -136,6 +150,7 @@ __export(index_exports, {
136
150
  isValidSkillName: () => isValidSkillName,
137
151
  loggerLatticeManager: () => loggerLatticeManager,
138
152
  mcpManager: () => mcpManager,
153
+ metricsServerManager: () => metricsServerManager,
139
154
  modelLatticeManager: () => modelLatticeManager,
140
155
  normalizeSandboxName: () => normalizeSandboxName,
141
156
  parseCronExpression: () => parseCronExpression,
@@ -680,11 +695,11 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
680
695
  * @param key Lattice键名
681
696
  * @param tool 已有的StructuredTool实例
682
697
  */
683
- registerExistingTool(key, tool38) {
698
+ registerExistingTool(key, tool46) {
684
699
  const config = {
685
- name: tool38.name,
686
- description: tool38.description,
687
- schema: tool38.schema,
700
+ name: tool46.name,
701
+ description: tool46.description,
702
+ schema: tool46.schema,
688
703
  // StructuredTool的schema已经是Zod兼容的
689
704
  needUserApprove: false
690
705
  // MCP工具默认不需要用户批准
@@ -692,7 +707,7 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
692
707
  const toolLattice = {
693
708
  key,
694
709
  config,
695
- client: tool38
710
+ client: tool46
696
711
  };
697
712
  this.register(key, toolLattice);
698
713
  }
@@ -718,7 +733,7 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
718
733
  };
719
734
  var toolLatticeManager = ToolLatticeManager.getInstance();
720
735
  var registerToolLattice = (key, config, executor) => toolLatticeManager.registerLattice(key, config, executor);
721
- var registerExistingTool = (key, tool38) => toolLatticeManager.registerExistingTool(key, tool38);
736
+ var registerExistingTool = (key, tool46) => toolLatticeManager.registerExistingTool(key, tool46);
722
737
  var getToolLattice = (key) => toolLatticeManager.getToolLattice(key);
723
738
  var getToolDefinition = (key) => toolLatticeManager.getToolDefinition(key);
724
739
  var getToolClient = (key) => toolLatticeManager.getToolClient(key);
@@ -1389,8 +1404,1595 @@ ${databaseKeys.map(
1389
1404
  );
1390
1405
  };
1391
1406
 
1407
+ // src/tool_lattice/metrics/SemanticMetricsClient.ts
1408
+ var SemanticMetricsClient = class {
1409
+ constructor(config) {
1410
+ this.config = config;
1411
+ this.baseUrl = config.serverUrl.replace(/\/$/, "");
1412
+ }
1413
+ /**
1414
+ * Test connection to the semantic metrics server
1415
+ * Attempts to fetch data sources as a connectivity test
1416
+ */
1417
+ async testConnection() {
1418
+ const startTime = Date.now();
1419
+ try {
1420
+ const response = await fetch(`${this.baseUrl}/datasources`, {
1421
+ method: "GET",
1422
+ headers: this.getHeaders()
1423
+ });
1424
+ if (!response.ok) {
1425
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1426
+ }
1427
+ const data = await response.json();
1428
+ if (data.code !== 200) {
1429
+ throw new Error(`API error: ${data.message}`);
1430
+ }
1431
+ const latency = Date.now() - startTime;
1432
+ return { connected: true, latency };
1433
+ } catch (error) {
1434
+ return {
1435
+ connected: false,
1436
+ error: error instanceof Error ? error.message : String(error)
1437
+ };
1438
+ }
1439
+ }
1440
+ /**
1441
+ * Get list of available metrics from all selected data sources
1442
+ * Aggregates metrics across selected datasources
1443
+ */
1444
+ async listMetrics() {
1445
+ const selectedIds = this.config.selectedDataSources || [];
1446
+ if (selectedIds.length === 0) {
1447
+ return [];
1448
+ }
1449
+ const allMetrics = [];
1450
+ const seenMetrics = /* @__PURE__ */ new Set();
1451
+ for (const datasourceId of selectedIds) {
1452
+ try {
1453
+ const metaData = await this.getDatasourceMetrics(datasourceId);
1454
+ for (const item of metaData.index.metrics) {
1455
+ if (!seenMetrics.has(item.metricName)) {
1456
+ seenMetrics.add(item.metricName);
1457
+ const detail = metaData.metricsDetails.find((d) => d.metricName === item.metricName);
1458
+ allMetrics.push({
1459
+ name: item.metricName,
1460
+ type: detail?.dataType || "number",
1461
+ description: item.shortDesc || detail?.description,
1462
+ labels: [],
1463
+ unit: void 0
1464
+ });
1465
+ }
1466
+ }
1467
+ } catch (error) {
1468
+ console.warn(`Failed to get metrics for datasource ${datasourceId}:`, error);
1469
+ }
1470
+ }
1471
+ return allMetrics;
1472
+ }
1473
+ /**
1474
+ * Get metadata for a specific metric
1475
+ * Searches across selected datasources for the metric
1476
+ */
1477
+ async getMetricMeta(metricName) {
1478
+ const selectedIds = this.config.selectedDataSources || [];
1479
+ for (const datasourceId of selectedIds) {
1480
+ try {
1481
+ const metaData = await this.getDatasourceMetrics(datasourceId);
1482
+ const item = metaData.index.metrics.find((m) => m.metricName === metricName);
1483
+ if (item) {
1484
+ const detail = metaData.metricsDetails.find((d) => d.metricName === metricName);
1485
+ return {
1486
+ name: item.metricName,
1487
+ type: detail?.dataType || "number",
1488
+ description: item.shortDesc || detail?.description,
1489
+ labels: [],
1490
+ unit: void 0
1491
+ };
1492
+ }
1493
+ } catch (error) {
1494
+ console.warn(`Failed to get metric meta from datasource ${datasourceId}:`, error);
1495
+ }
1496
+ }
1497
+ return null;
1498
+ }
1499
+ /**
1500
+ * Query metric data - delegates to semanticQuery
1501
+ * Note: For semantic server, use semanticQuery() directly for full functionality
1502
+ */
1503
+ async queryMetricData(metricName, options) {
1504
+ const selectedIds = this.config.selectedDataSources || [];
1505
+ if (selectedIds.length === 0) {
1506
+ throw new Error("No data sources selected for this semantic metrics server");
1507
+ }
1508
+ const datasourceId = selectedIds[0];
1509
+ const filters = [];
1510
+ if (options.startTime && options.endTime) {
1511
+ filters.push({
1512
+ dimension: "timestamp",
1513
+ operator: "BETWEEN",
1514
+ values: [
1515
+ new Date(options.startTime * 1e3).toISOString(),
1516
+ new Date(options.endTime * 1e3).toISOString()
1517
+ ]
1518
+ });
1519
+ }
1520
+ if (options.labels) {
1521
+ for (const [key, value] of Object.entries(options.labels)) {
1522
+ filters.push({
1523
+ dimension: key,
1524
+ operator: "=",
1525
+ values: [value]
1526
+ });
1527
+ }
1528
+ }
1529
+ const request = {
1530
+ datasourceId,
1531
+ metrics: [metricName],
1532
+ filters,
1533
+ limit: 1e3
1534
+ };
1535
+ const result = await this.semanticQuery(request);
1536
+ const metricResult = result.results.find((r) => r.metricName === metricName);
1537
+ const dataPoints = metricResult?.rows.map((row, index) => ({
1538
+ timestamp: index * 1e3,
1539
+ // Use index as timestamp if not provided
1540
+ value: typeof row.value === "number" ? row.value : 0,
1541
+ labels: Object.fromEntries(
1542
+ Object.entries(row).map(([k, v]) => [k, String(v)])
1543
+ )
1544
+ })) || [];
1545
+ return {
1546
+ metricName,
1547
+ dataPoints,
1548
+ metadata: {
1549
+ startTime: options.startTime ? options.startTime * 1e3 : void 0,
1550
+ endTime: options.endTime ? options.endTime * 1e3 : void 0
1551
+ }
1552
+ };
1553
+ }
1554
+ /**
1555
+ * Get the server type
1556
+ */
1557
+ getServerType() {
1558
+ return "semantic";
1559
+ }
1560
+ /**
1561
+ * Get all available data sources from the semantic server
1562
+ * GET /datasources
1563
+ */
1564
+ async getDataSources() {
1565
+ const response = await fetch(`${this.baseUrl}/datasources`, {
1566
+ method: "GET",
1567
+ headers: this.getHeaders()
1568
+ });
1569
+ if (!response.ok) {
1570
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1571
+ }
1572
+ const data = await response.json();
1573
+ if (data.code !== 200) {
1574
+ throw new Error(`API error: ${data.message}`);
1575
+ }
1576
+ return data.data || [];
1577
+ }
1578
+ /**
1579
+ * Get metrics meta for a specific data source
1580
+ * GET /datasources/{id}/meta
1581
+ */
1582
+ async getDatasourceMetrics(datasourceId) {
1583
+ const response = await fetch(
1584
+ `${this.baseUrl}/datasources/${encodeURIComponent(datasourceId)}/meta`,
1585
+ {
1586
+ method: "GET",
1587
+ headers: this.getHeaders()
1588
+ }
1589
+ );
1590
+ if (!response.ok) {
1591
+ if (response.status === 404) {
1592
+ return { index: { datasourceId: 0, datasourceName: "", catalogVersion: "", domainCategories: [], metrics: [], tables: [] }, metricsDetails: [] };
1593
+ }
1594
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1595
+ }
1596
+ const data = await response.json();
1597
+ if (data.code !== 200) {
1598
+ throw new Error(`API error: ${data.message}`);
1599
+ }
1600
+ return data.data;
1601
+ }
1602
+ /**
1603
+ * Execute a semantic metrics query
1604
+ * POST /metrics/query
1605
+ */
1606
+ async semanticQuery(request) {
1607
+ const response = await fetch(`${this.baseUrl}/metrics/query`, {
1608
+ method: "POST",
1609
+ headers: {
1610
+ ...this.getHeaders(),
1611
+ "Content-Type": "application/json"
1612
+ },
1613
+ body: JSON.stringify(request)
1614
+ });
1615
+ if (!response.ok) {
1616
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1617
+ }
1618
+ const data = await response.json();
1619
+ if (data.code !== 200) {
1620
+ throw new Error(`API error: ${data.message}`);
1621
+ }
1622
+ return data.data;
1623
+ }
1624
+ /**
1625
+ * Get selected data sources for this configuration
1626
+ */
1627
+ getSelectedDataSources() {
1628
+ return this.config.selectedDataSources || [];
1629
+ }
1630
+ /**
1631
+ * Build request headers with authentication
1632
+ */
1633
+ getHeaders() {
1634
+ const headers = {
1635
+ Accept: "application/json",
1636
+ ...this.config.headers
1637
+ };
1638
+ if (this.config.apiKey) {
1639
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1640
+ } else if (this.config.username && this.config.password) {
1641
+ const auth = Buffer.from(`${this.config.username}:${this.config.password}`).toString("base64");
1642
+ headers["Authorization"] = `Basic ${auth}`;
1643
+ }
1644
+ return headers;
1645
+ }
1646
+ };
1647
+
1648
+ // src/tool_lattice/metrics/MetricsServerManager.ts
1649
+ var PrometheusClient = class {
1650
+ constructor(config) {
1651
+ this.config = config;
1652
+ }
1653
+ async testConnection() {
1654
+ const startTime = Date.now();
1655
+ try {
1656
+ const response = await fetch(`${this.config.serverUrl}/api/v1/status/buildinfo`, {
1657
+ method: "GET",
1658
+ headers: this.getHeaders()
1659
+ });
1660
+ if (!response.ok) {
1661
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1662
+ }
1663
+ const latency = Date.now() - startTime;
1664
+ return { connected: true, latency };
1665
+ } catch (error) {
1666
+ return {
1667
+ connected: false,
1668
+ error: error instanceof Error ? error.message : String(error)
1669
+ };
1670
+ }
1671
+ }
1672
+ async listMetrics() {
1673
+ try {
1674
+ const response = await fetch(`${this.config.serverUrl}/api/v1/label/__name__/values`, {
1675
+ method: "GET",
1676
+ headers: this.getHeaders()
1677
+ });
1678
+ if (!response.ok) {
1679
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1680
+ }
1681
+ const data = await response.json();
1682
+ if (data.status !== "success") {
1683
+ throw new Error(`Prometheus error: ${data.error || "Unknown error"}`);
1684
+ }
1685
+ const metrics = [];
1686
+ for (const name of data.data || []) {
1687
+ const meta = await this.getMetricMeta(name);
1688
+ if (meta) {
1689
+ metrics.push(meta);
1690
+ } else {
1691
+ metrics.push({ name });
1692
+ }
1693
+ }
1694
+ return metrics;
1695
+ } catch (error) {
1696
+ throw new Error(`Failed to list metrics: ${error instanceof Error ? error.message : String(error)}`);
1697
+ }
1698
+ }
1699
+ async getMetricMeta(metricName) {
1700
+ try {
1701
+ const response = await fetch(
1702
+ `${this.config.serverUrl}/api/v1/metadata?metric=${encodeURIComponent(metricName)}`,
1703
+ {
1704
+ method: "GET",
1705
+ headers: this.getHeaders()
1706
+ }
1707
+ );
1708
+ if (!response.ok) {
1709
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1710
+ }
1711
+ const data = await response.json();
1712
+ if (data.status !== "success" || !data.data[metricName]) {
1713
+ return { name: metricName };
1714
+ }
1715
+ const metadata = data.data[metricName][0];
1716
+ return {
1717
+ name: metricName,
1718
+ type: metadata.type,
1719
+ description: metadata.help,
1720
+ unit: metadata.unit
1721
+ };
1722
+ } catch (error) {
1723
+ console.warn(`Failed to get metric metadata for ${metricName}:`, error);
1724
+ return { name: metricName };
1725
+ }
1726
+ }
1727
+ async queryMetricData(metricName, options) {
1728
+ const endTime = options.endTime || Math.floor(Date.now() / 1e3);
1729
+ const startTime = options.startTime || endTime - 3600;
1730
+ const step = options.step || 60;
1731
+ let query = metricName;
1732
+ if (options.labels && Object.keys(options.labels).length > 0) {
1733
+ const labelSelectors = Object.entries(options.labels).map(([key, value]) => `${key}="${value}"`).join(",");
1734
+ query = `${metricName}{${labelSelectors}}`;
1735
+ }
1736
+ try {
1737
+ const response = await fetch(
1738
+ `${this.config.serverUrl}/api/v1/query_range?query=${encodeURIComponent(query)}&start=${startTime}&end=${endTime}&step=${step}`,
1739
+ {
1740
+ method: "GET",
1741
+ headers: this.getHeaders()
1742
+ }
1743
+ );
1744
+ if (!response.ok) {
1745
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1746
+ }
1747
+ const data = await response.json();
1748
+ if (data.status !== "success") {
1749
+ throw new Error(`Prometheus error: ${data.error || "Unknown error"}`);
1750
+ }
1751
+ const dataPoints = [];
1752
+ const result = data.data?.result || [];
1753
+ for (const series of result) {
1754
+ const labels = series.metric || {};
1755
+ for (const [timestamp, value] of series.values || []) {
1756
+ dataPoints.push({
1757
+ timestamp: parseFloat(timestamp) * 1e3,
1758
+ // Convert to milliseconds
1759
+ value: parseFloat(value),
1760
+ labels
1761
+ });
1762
+ }
1763
+ }
1764
+ return {
1765
+ metricName,
1766
+ dataPoints,
1767
+ metadata: {
1768
+ startTime: startTime * 1e3,
1769
+ endTime: endTime * 1e3,
1770
+ step: step * 1e3
1771
+ }
1772
+ };
1773
+ } catch (error) {
1774
+ throw new Error(`Failed to query metric data: ${error instanceof Error ? error.message : String(error)}`);
1775
+ }
1776
+ }
1777
+ getServerType() {
1778
+ return "prometheus";
1779
+ }
1780
+ getHeaders() {
1781
+ const headers = {
1782
+ Accept: "application/json",
1783
+ ...this.config.headers
1784
+ };
1785
+ if (this.config.apiKey) {
1786
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1787
+ } else if (this.config.username && this.config.password) {
1788
+ const auth = Buffer.from(`${this.config.username}:${this.config.password}`).toString("base64");
1789
+ headers["Authorization"] = `Basic ${auth}`;
1790
+ }
1791
+ return headers;
1792
+ }
1793
+ };
1794
+ var CustomMetricsClient = class {
1795
+ constructor(config) {
1796
+ this.config = config;
1797
+ }
1798
+ async testConnection() {
1799
+ const startTime = Date.now();
1800
+ try {
1801
+ const response = await fetch(`${this.config.serverUrl}/health`, {
1802
+ method: "GET",
1803
+ headers: this.getHeaders()
1804
+ });
1805
+ if (!response.ok) {
1806
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1807
+ }
1808
+ const latency = Date.now() - startTime;
1809
+ return { connected: true, latency };
1810
+ } catch (error) {
1811
+ return {
1812
+ connected: false,
1813
+ error: error instanceof Error ? error.message : String(error)
1814
+ };
1815
+ }
1816
+ }
1817
+ async listMetrics() {
1818
+ try {
1819
+ const response = await fetch(`${this.config.serverUrl}/api/metrics`, {
1820
+ method: "GET",
1821
+ headers: this.getHeaders()
1822
+ });
1823
+ if (!response.ok) {
1824
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1825
+ }
1826
+ const data = await response.json();
1827
+ return data.metrics || [];
1828
+ } catch (error) {
1829
+ throw new Error(`Failed to list metrics: ${error instanceof Error ? error.message : String(error)}`);
1830
+ }
1831
+ }
1832
+ async getMetricMeta(metricName) {
1833
+ try {
1834
+ const response = await fetch(
1835
+ `${this.config.serverUrl}/api/metrics/${encodeURIComponent(metricName)}/meta`,
1836
+ {
1837
+ method: "GET",
1838
+ headers: this.getHeaders()
1839
+ }
1840
+ );
1841
+ if (!response.ok) {
1842
+ if (response.status === 404) {
1843
+ return null;
1844
+ }
1845
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1846
+ }
1847
+ return await response.json();
1848
+ } catch (error) {
1849
+ throw new Error(`Failed to get metric metadata: ${error instanceof Error ? error.message : String(error)}`);
1850
+ }
1851
+ }
1852
+ async queryMetricData(metricName, options) {
1853
+ try {
1854
+ const queryParams = new URLSearchParams();
1855
+ if (options.startTime) queryParams.append("start", options.startTime.toString());
1856
+ if (options.endTime) queryParams.append("end", options.endTime.toString());
1857
+ if (options.step) queryParams.append("step", options.step.toString());
1858
+ if (options.labels) {
1859
+ queryParams.append("labels", JSON.stringify(options.labels));
1860
+ }
1861
+ const response = await fetch(
1862
+ `${this.config.serverUrl}/api/metrics/${encodeURIComponent(metricName)}/data?${queryParams}`,
1863
+ {
1864
+ method: "GET",
1865
+ headers: this.getHeaders()
1866
+ }
1867
+ );
1868
+ if (!response.ok) {
1869
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1870
+ }
1871
+ return await response.json();
1872
+ } catch (error) {
1873
+ throw new Error(`Failed to query metric data: ${error instanceof Error ? error.message : String(error)}`);
1874
+ }
1875
+ }
1876
+ getServerType() {
1877
+ return "custom";
1878
+ }
1879
+ getHeaders() {
1880
+ const headers = {
1881
+ Accept: "application/json",
1882
+ ...this.config.headers
1883
+ };
1884
+ if (this.config.apiKey) {
1885
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1886
+ } else if (this.config.username && this.config.password) {
1887
+ const auth = Buffer.from(`${this.config.username}:${this.config.password}`).toString("base64");
1888
+ headers["Authorization"] = `Basic ${auth}`;
1889
+ }
1890
+ return headers;
1891
+ }
1892
+ };
1893
+ var MetricsServerManager = class _MetricsServerManager {
1894
+ constructor() {
1895
+ this.clients = /* @__PURE__ */ new Map();
1896
+ this.configs = /* @__PURE__ */ new Map();
1897
+ this.defaultServerKey = null;
1898
+ }
1899
+ /**
1900
+ * Get the singleton instance
1901
+ */
1902
+ static getInstance() {
1903
+ if (!_MetricsServerManager.instance) {
1904
+ _MetricsServerManager.instance = new _MetricsServerManager();
1905
+ }
1906
+ return _MetricsServerManager.instance;
1907
+ }
1908
+ /**
1909
+ * Register a metrics server
1910
+ * @param key - Unique identifier for the server
1911
+ * @param config - Metrics server configuration
1912
+ */
1913
+ registerServer(key, config) {
1914
+ let client;
1915
+ switch (config.type) {
1916
+ case "prometheus":
1917
+ client = new PrometheusClient(config);
1918
+ break;
1919
+ case "custom":
1920
+ client = new CustomMetricsClient(config);
1921
+ break;
1922
+ case "semantic":
1923
+ client = new SemanticMetricsClient(config);
1924
+ break;
1925
+ default:
1926
+ throw new Error(`Unsupported metrics server type: ${config.type}`);
1927
+ }
1928
+ this.clients.set(key, client);
1929
+ this.configs.set(key, config);
1930
+ if (this.defaultServerKey === null) {
1931
+ this.defaultServerKey = key;
1932
+ }
1933
+ }
1934
+ /**
1935
+ * Set the default metrics server
1936
+ * @param key - Server key to set as default
1937
+ */
1938
+ setDefaultServer(key) {
1939
+ if (!this.clients.has(key)) {
1940
+ throw new Error(`Metrics server '${key}' not found`);
1941
+ }
1942
+ this.defaultServerKey = key;
1943
+ }
1944
+ /**
1945
+ * Get a metrics server client by key
1946
+ * @param key - Server key (optional, uses default if not provided)
1947
+ */
1948
+ getClient(key) {
1949
+ const serverKey = key || this.defaultServerKey;
1950
+ if (!serverKey) {
1951
+ throw new Error("No metrics server registered");
1952
+ }
1953
+ const client = this.clients.get(serverKey);
1954
+ if (!client) {
1955
+ throw new Error(`Metrics server '${serverKey}' not found`);
1956
+ }
1957
+ return client;
1958
+ }
1959
+ /**
1960
+ * Get metrics server configuration by key
1961
+ * @param key - Server key (optional, uses default if not provided)
1962
+ */
1963
+ getConfig(key) {
1964
+ const serverKey = key || this.defaultServerKey;
1965
+ if (!serverKey) {
1966
+ throw new Error("No metrics server registered");
1967
+ }
1968
+ const config = this.configs.get(serverKey);
1969
+ if (!config) {
1970
+ throw new Error(`Metrics server '${serverKey}' not found`);
1971
+ }
1972
+ return config;
1973
+ }
1974
+ /**
1975
+ * Check if a metrics server is registered
1976
+ * @param key - Server key
1977
+ */
1978
+ hasServer(key) {
1979
+ return this.clients.has(key);
1980
+ }
1981
+ /**
1982
+ * Get all registered metrics server keys with their types
1983
+ */
1984
+ getServerKeys() {
1985
+ return Array.from(this.configs.entries()).map(([key, config]) => ({
1986
+ key,
1987
+ type: config.type
1988
+ }));
1989
+ }
1990
+ /**
1991
+ * Remove a metrics server
1992
+ * @param key - Server key
1993
+ */
1994
+ removeServer(key) {
1995
+ this.clients.delete(key);
1996
+ this.configs.delete(key);
1997
+ if (this.defaultServerKey === key) {
1998
+ this.defaultServerKey = this.clients.size > 0 ? this.clients.keys().next().value || null : null;
1999
+ }
2000
+ }
2001
+ /**
2002
+ * Load metrics server configurations from a store
2003
+ * and register them with this manager
2004
+ *
2005
+ * @param store - The metrics server configuration store
2006
+ * @param tenantId - Tenant identifier
2007
+ */
2008
+ async loadConfigsFromStore(store, tenantId) {
2009
+ const configs = await store.getAllConfigs(tenantId);
2010
+ for (const entry of configs) {
2011
+ this.registerServer(entry.key, entry.config);
2012
+ }
2013
+ }
2014
+ /**
2015
+ * Load all metrics server configurations from a store
2016
+ * across all tenants and register them with this manager
2017
+ *
2018
+ * @param store - The metrics server configuration store
2019
+ */
2020
+ async loadAllConfigsFromStore(store) {
2021
+ const configs = await store.getAllConfigsWithoutTenant();
2022
+ for (const entry of configs) {
2023
+ this.registerServer(entry.key, entry.config);
2024
+ }
2025
+ }
2026
+ };
2027
+ var metricsServerManager = MetricsServerManager.getInstance();
2028
+
2029
+ // src/tool_lattice/metrics/list_metrics_servers.ts
2030
+ var import_zod7 = __toESM(require("zod"));
2031
+ var import_langchain5 = require("langchain");
2032
+ var LIST_METRICS_SERVERS_DESCRIPTION = `List all registered metrics servers. Returns a list of available metrics servers with their keys and types. Use this tool first to understand what metrics servers are available.`;
2033
+ var createListMetricsServersTool = ({ serverKeys, serverDescriptions }) => {
2034
+ const availableServersText = serverKeys.length > 0 ? `
2035
+
2036
+ Available metrics servers:
2037
+ ${serverKeys.map(
2038
+ (key) => `- ${key}${serverDescriptions?.[key] ? `: ${serverDescriptions[key]}` : ""}`
2039
+ ).join("\n")}` : "";
2040
+ return (0, import_langchain5.tool)(
2041
+ async (_input, _exeConfig) => {
2042
+ try {
2043
+ const servers = metricsServerManager.getServerKeys();
2044
+ if (servers.length === 0) {
2045
+ return "No metrics servers registered.";
2046
+ }
2047
+ const lines = servers.map(({ key, type }) => {
2048
+ const desc = serverDescriptions?.[key] ? ` - ${serverDescriptions[key]}` : "";
2049
+ return `- ${key} (${type})${desc}`;
2050
+ });
2051
+ return `Available metrics servers:
2052
+ ${lines.join("\n")}`;
2053
+ } catch (error) {
2054
+ return `Error listing metrics servers: ${error instanceof Error ? error.message : String(error)}`;
2055
+ }
2056
+ },
2057
+ {
2058
+ name: "list_metrics_servers",
2059
+ description: `${LIST_METRICS_SERVERS_DESCRIPTION}${availableServersText}`,
2060
+ schema: import_zod7.default.object({})
2061
+ }
2062
+ );
2063
+ };
2064
+
2065
+ // src/tool_lattice/metrics/list_metrics_datasources.ts
2066
+ var import_zod8 = __toESM(require("zod"));
2067
+ var import_langchain6 = require("langchain");
2068
+ var LIST_METRICS_DATASOURCES_DESCRIPTION = `List all available datasources from all configured metrics servers. Returns a table with Server Key, DataSource ID, and DataSource Name. Use this tool first to discover what datasources are available before querying metrics.`;
2069
+ var createListMetricsDataSourcesTool = ({ serverKeys, serverDescriptions }) => {
2070
+ const availableServersText = serverKeys.length > 0 ? `
2071
+
2072
+ Configured metrics servers:
2073
+ ${serverKeys.map(
2074
+ (key) => `- ${key}${serverDescriptions?.[key] ? `: ${serverDescriptions[key]}` : ""}`
2075
+ ).join("\n")}` : "";
2076
+ return (0, import_langchain6.tool)(
2077
+ async (_input, _exeConfig) => {
2078
+ try {
2079
+ if (serverKeys.length === 0) {
2080
+ return "No metrics servers configured.";
2081
+ }
2082
+ const allDataSources = [];
2083
+ for (const serverKey of serverKeys) {
2084
+ try {
2085
+ const config = metricsServerManager.getConfig(serverKey);
2086
+ if (config.type !== "semantic") {
2087
+ console.warn(`Server "${serverKey}" is not a semantic metrics server, skipping.`);
2088
+ continue;
2089
+ }
2090
+ const client = metricsServerManager.getClient(serverKey);
2091
+ const dataSources = await client.getDataSources();
2092
+ for (const ds of dataSources) {
2093
+ allDataSources.push({
2094
+ serverKey,
2095
+ datasourceId: String(ds.id),
2096
+ datasourceName: ds.name || String(ds.id)
2097
+ });
2098
+ }
2099
+ } catch (error) {
2100
+ console.warn(`Failed to get datasources from server "${serverKey}":`, error);
2101
+ }
2102
+ }
2103
+ if (allDataSources.length === 0) {
2104
+ return `No datasources found in any configured metrics servers.`;
2105
+ }
2106
+ const lines = [];
2107
+ lines.push(`Found ${allDataSources.length} datasource(s) from ${serverKeys.length} server(s):
2108
+ `);
2109
+ lines.push("| Server Key | DataSource ID | Name |");
2110
+ lines.push("|------------|---------------|------|");
2111
+ for (const ds of allDataSources) {
2112
+ lines.push(`| ${ds.serverKey} | ${ds.datasourceId} | ${ds.datasourceName} |`);
2113
+ }
2114
+ lines.push("\nUse the Server Key and DataSource ID when calling other metrics tools.");
2115
+ return lines.join("\n");
2116
+ } catch (error) {
2117
+ return `Error listing datasources: ${error instanceof Error ? error.message : String(error)}`;
2118
+ }
2119
+ },
2120
+ {
2121
+ name: "list_metrics_datasources",
2122
+ description: `${LIST_METRICS_DATASOURCES_DESCRIPTION}${availableServersText}`,
2123
+ schema: import_zod8.default.object({})
2124
+ }
2125
+ );
2126
+ };
2127
+
2128
+ // src/tool_lattice/metrics/query_metrics_list.ts
2129
+ var import_zod9 = __toESM(require("zod"));
2130
+ var import_langchain7 = require("langchain");
2131
+ var QUERY_METRICS_LIST_DESCRIPTION = `Query Available Metrics - Step 1 of the Metrics Workflow
2132
+
2133
+ Discover what metrics exist in the semantic metrics server. This tool returns a list of available metrics with their domains and descriptions.
2134
+
2135
+ When to Use This Tool
2136
+ Use this tool proactively in these scenarios:
2137
+ - When the user asks about business metrics but does not specify exact metric names
2138
+ - When you need to find metrics matching a specific domain (e.g., "sales performance", "pricing")
2139
+ - At the start of ANY metrics-related conversation to understand available data
2140
+ - When the user asks "what metrics do we have?" or "show me available KPIs"
2141
+
2142
+ When NOT to Use This Tool
2143
+ Skip using this tool when:
2144
+ - The user has already provided exact metric names (proceed directly to query_metric_definition)
2145
+ - You have cached metric metadata from a recent call (within the same conversation)
2146
+ - The query is purely about retrieving data, not discovering what's available
2147
+
2148
+ The Three-Step Metrics Workflow
2149
+ 1. query_metrics_list (THIS TOOL) \u2192 discover available metrics
2150
+ 2. query_metric_definition \u2192 read metric metadata before querying
2151
+ 3. query_semantic_metric_data \u2192 execute the query with correct parameters
2152
+
2153
+ Response Fields Reference
2154
+ | Field | How to Use It |
2155
+ |-------|---------------|
2156
+ | metricName | The identifier passed to query_metric_definition and query_semantic_metric_data |
2157
+ | domain | Groups related metrics (e.g., sales_performance, pricing_and_margin) |
2158
+ | shortDesc | One-line description to present to the user |
2159
+ | displayName | Human-readable name of the metric |
2160
+
2161
+ Next Step
2162
+ After finding relevant metrics, call query_metric_definition with the metricName to get detailed metadata including time dimensions and supported filters.`;
2163
+ var createQueryMetricsListTool = ({ serverKeys, serverDescriptions }) => {
2164
+ const availableServersText = serverKeys.length > 0 ? `
2165
+
2166
+ Available metrics servers:
2167
+ ${serverKeys.map(
2168
+ (key) => `- ${key}${serverDescriptions?.[key] ? `: ${serverDescriptions[key]}` : ""}`
2169
+ ).join("\n")}` : "";
2170
+ return (0, import_langchain7.tool)(
2171
+ async ({
2172
+ serverKey,
2173
+ datasourceIds
2174
+ }, _exeConfig) => {
2175
+ try {
2176
+ if (!serverKey) {
2177
+ return "Error: serverKey parameter is required. Available servers: " + serverKeys.join(", ");
2178
+ }
2179
+ if (!serverKeys.includes(serverKey)) {
2180
+ return `Error: serverKey "${serverKey}" is not in the allowed list: [${serverKeys.join(", ")}]`;
2181
+ }
2182
+ const config = metricsServerManager.getConfig(serverKey);
2183
+ if (config.type !== "semantic") {
2184
+ return `Error: Server "${serverKey}" is not a semantic metrics server. This tool only works with semantic servers.`;
2185
+ }
2186
+ const client = metricsServerManager.getClient(serverKey);
2187
+ const targetDatasourceIds = datasourceIds && datasourceIds.length > 0 ? datasourceIds : client.getSelectedDataSources();
2188
+ if (targetDatasourceIds.length === 0) {
2189
+ return `Error: No data sources specified and no default data sources configured for server "${serverKey}".`;
2190
+ }
2191
+ const allMetrics = /* @__PURE__ */ new Map();
2192
+ for (const datasourceId of targetDatasourceIds) {
2193
+ try {
2194
+ const metaData = await client.getDatasourceMetrics(datasourceId);
2195
+ const index = metaData.index;
2196
+ for (const item of index.metrics) {
2197
+ if (allMetrics.has(item.metricName)) {
2198
+ const existing = allMetrics.get(item.metricName);
2199
+ if (!existing.datasources.includes(datasourceId)) {
2200
+ existing.datasources.push(datasourceId);
2201
+ }
2202
+ } else {
2203
+ allMetrics.set(item.metricName, {
2204
+ metricName: item.metricName,
2205
+ displayName: item.displayName,
2206
+ domain: item.domain,
2207
+ shortDesc: item.shortDesc,
2208
+ datasources: [datasourceId]
2209
+ });
2210
+ }
2211
+ }
2212
+ } catch (error) {
2213
+ console.warn(`Failed to get metrics for datasource ${datasourceId}:`, error);
2214
+ }
2215
+ }
2216
+ const metricsByDatasource = /* @__PURE__ */ new Map();
2217
+ for (const metric of allMetrics.values()) {
2218
+ for (const dsId of metric.datasources) {
2219
+ if (!metricsByDatasource.has(dsId)) {
2220
+ metricsByDatasource.set(dsId, []);
2221
+ }
2222
+ metricsByDatasource.get(dsId).push(metric);
2223
+ }
2224
+ }
2225
+ if (metricsByDatasource.size === 0) {
2226
+ return `\u672A\u5728\u6307\u5B9A\u7684\u6570\u636E\u6E90\u4E2D\u627E\u5230\u6307\u6807\u3002`;
2227
+ }
2228
+ const lines = [];
2229
+ lines.push(`## \u4E1A\u52A1\u6307\u6807\u5217\u8868\uFF08serverKey: ${serverKey}\uFF09
2230
+ `);
2231
+ const sortedDatasourceIds = Array.from(metricsByDatasource.keys()).sort();
2232
+ for (const dsId of sortedDatasourceIds) {
2233
+ const metrics = metricsByDatasource.get(dsId);
2234
+ const sortedMetrics = metrics.sort((a, b) => {
2235
+ if (a.domain !== b.domain) {
2236
+ return a.domain.localeCompare(b.domain);
2237
+ }
2238
+ return a.metricName.localeCompare(b.metricName);
2239
+ });
2240
+ lines.push(`### datasourceId: ${dsId}\uFF08${metrics.length} \u4E2A\u6307\u6807\uFF09
2241
+ `);
2242
+ lines.push("| metricName | displayName | domain | shortDesc |");
2243
+ lines.push("|------------|-------------|--------|-----------|");
2244
+ for (const metric of sortedMetrics) {
2245
+ const shortDesc = metric.shortDesc || "";
2246
+ lines.push(`| ${metric.metricName} | ${metric.displayName} | ${metric.domain} | ${shortDesc} |`);
2247
+ }
2248
+ lines.push("");
2249
+ }
2250
+ lines.push("---");
2251
+ lines.push("");
2252
+ lines.push("\u5982\u9700\u67E5\u770B\u6307\u6807\u7684\u8BE6\u7EC6\u5B9A\u4E49\uFF0C\u8BF7\u4F7F\u7528 **query_metric_definition** \u5DE5\u5177\uFF0C\u4F20\u5165\u53C2\u6570\uFF1A`serverKey`\u3001`metricName`\u3001`datasourceId`");
2253
+ return lines.join("\n");
2254
+ } catch (error) {
2255
+ return `Error querying metrics list: ${error instanceof Error ? error.message : String(error)}`;
2256
+ }
2257
+ },
2258
+ {
2259
+ name: "query_metrics_list",
2260
+ description: `${QUERY_METRICS_LIST_DESCRIPTION}${availableServersText}`,
2261
+ schema: import_zod9.default.object({
2262
+ serverKey: import_zod9.default.string().describe(`Target semantic metrics server. Choose from: ${serverKeys.join(", ")}`),
2263
+ datasourceIds: import_zod9.default.array(import_zod9.default.string()).optional().describe("Optional array of datasource IDs to query. If not provided, uses all selected datasources.")
2264
+ })
2265
+ }
2266
+ );
2267
+ };
2268
+
2269
+ // src/tool_lattice/metrics/query_metric_definition.ts
2270
+ var import_zod10 = __toESM(require("zod"));
2271
+ var import_langchain8 = require("langchain");
2272
+ var QUERY_METRIC_DEFINITION_DESCRIPTION = `Get Metric Definition - Step 2 of the Metrics Workflow
2273
+
2274
+ Read detailed metadata for a specific metric before querying it.
2275
+
2276
+ When to Use This Tool
2277
+ - BEFORE calling query_semantic_metric_data for any metric
2278
+ - When you need to understand time dimensions and supported grains
2279
+ - When you need to know which dimensions are available for GROUP BY and filtering
2280
+
2281
+ When NOT to Use This Tool
2282
+ - You have already retrieved the metric definition in this conversation
2283
+ - You are only listing available metrics (use query_metrics_list instead)
2284
+
2285
+ Key Response Sections
2286
+
2287
+ 1. defaultTimeContext - Time Configuration
2288
+ - timeDimension: Primary date field (e.g., "DocDate")
2289
+ - supportedGrains: Available grains ["day", "week", "month", "year"]
2290
+ - Format: Use "{timeDimension}__{grain}" for time grouping
2291
+
2292
+ 2. supportedDimensions - Available Axes
2293
+ Each dimension has: dim_id, field_name, type (categorical/datetime)
2294
+
2295
+ Filter Patterns by Type:
2296
+ - categorical \u2192 {"dimension": "dim_id", "operator": "IN", "values": ["v1", "v2"]}
2297
+ - datetime \u2192 {"dimension": "dim_id", "operator": "BETWEEN", "values": ["2025-01-01", "2025-12-31"]}
2298
+
2299
+ GroupBy Patterns:
2300
+ - categorical \u2192 Use dim_id directly (e.g., "org_region")
2301
+ - datetime \u2192 Use "{dim_id}__{grain}" (e.g., "DocDate__month")
2302
+
2303
+ Rules
2304
+ - Use dim_id (never field_name) in filters and groupBy
2305
+ - Time grain format: lowercase (day/week/month/year)
2306
+ - Categorical: IN for multiple, EQ for single
2307
+ - Datetime: BETWEEN for ranges, GT/LT for open-ended
2308
+
2309
+ Next Step
2310
+ Call query_semantic_metric_data with parameters derived from this definition.`;
2311
+ var createQueryMetricDefinitionTool = ({ serverKeys, serverDescriptions }) => {
2312
+ const availableServersText = serverKeys.length > 0 ? `
2313
+
2314
+ Available metrics servers:
2315
+ ${serverKeys.map(
2316
+ (key) => `- ${key}${serverDescriptions?.[key] ? `: ${serverDescriptions[key]}` : ""}`
2317
+ ).join("\n")}` : "";
2318
+ return (0, import_langchain8.tool)(
2319
+ async ({
2320
+ serverKey,
2321
+ metricName,
2322
+ datasourceId
2323
+ }, _exeConfig) => {
2324
+ try {
2325
+ if (!serverKey) {
2326
+ return "Error: serverKey parameter is required. Available servers: " + serverKeys.join(", ");
2327
+ }
2328
+ if (!serverKeys.includes(serverKey)) {
2329
+ return `Error: serverKey "${serverKey}" is not in the allowed list: [${serverKeys.join(", ")}]`;
2330
+ }
2331
+ if (!metricName) {
2332
+ return "Error: metricName parameter is required.";
2333
+ }
2334
+ const config = metricsServerManager.getConfig(serverKey);
2335
+ if (config.type !== "semantic") {
2336
+ return `Error: Server "${serverKey}" is not a semantic metrics server. This tool only works with semantic servers.`;
2337
+ }
2338
+ const client = metricsServerManager.getClient(serverKey);
2339
+ const targetDatasourceIds = datasourceId ? [datasourceId] : client.getSelectedDataSources();
2340
+ if (targetDatasourceIds.length === 0) {
2341
+ return `Error: No datasourceId specified and no default data sources configured for server "${serverKey}".`;
2342
+ }
2343
+ let foundDetail = null;
2344
+ let foundDatasourceId = null;
2345
+ for (const dsId of targetDatasourceIds) {
2346
+ try {
2347
+ const metaData = await client.getDatasourceMetrics(dsId);
2348
+ const item = metaData.index.metrics.find((m) => m.metricName === metricName);
2349
+ if (item) {
2350
+ const detail = metaData.metricsDetails.find((d) => d.metricName === metricName);
2351
+ if (detail) {
2352
+ foundDetail = detail;
2353
+ foundDatasourceId = dsId;
2354
+ }
2355
+ break;
2356
+ }
2357
+ } catch (error) {
2358
+ console.warn(`Failed to get metrics for datasource ${dsId}:`, error);
2359
+ }
2360
+ }
2361
+ if (!foundDetail) {
2362
+ return `Metric "${metricName}" not found in the specified data sources.`;
2363
+ }
2364
+ const lines = [];
2365
+ lines.push(`# ${foundDetail.displayName} (${foundDetail.metricName})`);
2366
+ lines.push("");
2367
+ lines.push(`## \u57FA\u672C\u4FE1\u606F`);
2368
+ lines.push("");
2369
+ lines.push(`- **\u6307\u6807\u540D\u79F0**: ${foundDetail.metricName}`);
2370
+ lines.push(`- **\u663E\u793A\u540D\u79F0**: ${foundDetail.displayName}`);
2371
+ lines.push(`- **\u6240\u5C5E\u9886\u57DF**: ${foundDetail.domain}`);
2372
+ lines.push(`- **\u6570\u636E\u7C7B\u578B**: ${foundDetail.dataType}`);
2373
+ lines.push(`- **\u663E\u793A\u683C\u5F0F**: ${foundDetail.format}`);
2374
+ if (foundDatasourceId) {
2375
+ lines.push(`- **\u6570\u636E\u6E90ID**: ${foundDatasourceId}`);
2376
+ }
2377
+ lines.push("");
2378
+ lines.push(`## \u6307\u6807\u63CF\u8FF0`);
2379
+ lines.push("");
2380
+ lines.push(foundDetail.description);
2381
+ lines.push("");
2382
+ if (foundDetail.defaultTimeContext) {
2383
+ lines.push(`## \u65F6\u95F4\u4E0A\u4E0B\u6587`);
2384
+ lines.push("");
2385
+ lines.push(`- **\u65F6\u95F4\u7EF4\u5EA6**: ${foundDetail.defaultTimeContext.timeDimension} (${foundDetail.defaultTimeContext.label})`);
2386
+ lines.push(`- **\u9ED8\u8BA4\u7C92\u5EA6**: ${foundDetail.defaultTimeContext.granularity}`);
2387
+ lines.push(`- **\u9ED8\u8BA4\u7A97\u53E3**: ${foundDetail.defaultTimeContext.window}`);
2388
+ lines.push(`- **\u652F\u6301\u7684\u7C92\u5EA6**: ${foundDetail.defaultTimeContext.supportedGrains.join("\u3001")}`);
2389
+ lines.push("");
2390
+ }
2391
+ if (foundDetail.supportedDimensions && foundDetail.supportedDimensions.length > 0) {
2392
+ const categoricalDims = foundDetail.supportedDimensions.filter((d) => d.type === "categorical");
2393
+ const datetimeDims = foundDetail.supportedDimensions.filter((d) => d.type === "datetime");
2394
+ const timeDimension = foundDetail.defaultTimeContext?.timeDimension;
2395
+ lines.push(`## \u652F\u6301\u7684\u7EF4\u5EA6`);
2396
+ lines.push("");
2397
+ if (categoricalDims.length > 0) {
2398
+ lines.push(`### \u5206\u7C7B\u7EF4\u5EA6 (categorical) - ${categoricalDims.length} \u4E2A`);
2399
+ lines.push("\u652F\u6301 IN\uFF08\u591A\u9009\uFF09\u3001EQ\uFF08\u5355\u9009\uFF09\u64CD\u4F5C\u7B26");
2400
+ lines.push("");
2401
+ const examples = categoricalDims.slice(0, 2);
2402
+ for (const dim of examples) {
2403
+ lines.push(`**${dim.dim_id}** (${dim.field_name})`);
2404
+ lines.push("```json");
2405
+ lines.push(`// \u5206\u7EC4\u793A\u4F8B`);
2406
+ lines.push(`"groupBy": ["${dim.dim_id}"]`);
2407
+ lines.push("");
2408
+ lines.push(`// \u8FC7\u6EE4\u793A\u4F8B`);
2409
+ lines.push(`{"dimension": "${dim.dim_id}", "operator": "IN", "values": ["value1", "value2"]}`);
2410
+ lines.push("```");
2411
+ lines.push("");
2412
+ }
2413
+ if (categoricalDims.length > 2) {
2414
+ const others = categoricalDims.slice(2).map((d) => d.dim_id).join("\u3001");
2415
+ lines.push(`**\u5176\u4ED6 ${categoricalDims.length - 2} \u4E2A\u7EF4\u5EA6**: ${others}`);
2416
+ lines.push("");
2417
+ }
2418
+ }
2419
+ if (datetimeDims.length > 0) {
2420
+ lines.push(`### \u65F6\u95F4\u7EF4\u5EA6 (datetime) - ${datetimeDims.length} \u4E2A`);
2421
+ lines.push("\u652F\u6301 BETWEEN\uFF08\u8303\u56F4\uFF09\u3001GT/GTE/LT/LTE\uFF08\u6BD4\u8F83\uFF09\u64CD\u4F5C\u7B26");
2422
+ lines.push("");
2423
+ const primaryDim = datetimeDims.find((d) => d.dim_id === timeDimension) || datetimeDims[0];
2424
+ lines.push(`**${primaryDim.dim_id}** (${primaryDim.field_name})`);
2425
+ lines.push("```json");
2426
+ lines.push(`// \u6309\u65F6\u95F4\u7C92\u5EA6\u5206\u7EC4`);
2427
+ lines.push(`"groupBy": ["${primaryDim.dim_id}__month"] // \u53EF\u9009: day, week, month, year`);
2428
+ lines.push("");
2429
+ lines.push(`// \u65F6\u95F4\u8303\u56F4\u8FC7\u6EE4`);
2430
+ lines.push(`{"dimension": "${primaryDim.dim_id}", "operator": "BETWEEN", "values": ["2025-01-01", "2025-12-31"]}`);
2431
+ lines.push("```");
2432
+ lines.push("");
2433
+ if (datetimeDims.length > 1) {
2434
+ const others = datetimeDims.filter((d) => d.dim_id !== primaryDim.dim_id).map((d) => d.dim_id).join("\u3001");
2435
+ lines.push(`**\u5176\u4ED6\u65F6\u95F4\u7EF4\u5EA6**: ${others}`);
2436
+ lines.push("");
2437
+ }
2438
+ }
2439
+ lines.push("### \u5FEB\u901F\u53C2\u8003");
2440
+ lines.push("");
2441
+ lines.push("**\u65F6\u95F4\u5206\u7EC4\u683C\u5F0F**: `{timeDimension}__{grain}`");
2442
+ lines.push("- \u6309\u5929: `DocDate__day`");
2443
+ lines.push("- \u6309\u5468: `DocDate__week`");
2444
+ lines.push("- \u6309\u6708: `DocDate__month`");
2445
+ lines.push("- \u6309\u5E74: `DocDate__year`");
2446
+ lines.push("");
2447
+ }
2448
+ if (foundDetail.aiAgentContext) {
2449
+ const aiContext = foundDetail.aiAgentContext;
2450
+ lines.push(`## AI \u5206\u6790\u4E0A\u4E0B\u6587`);
2451
+ lines.push("");
2452
+ lines.push(`### \u6307\u6807\u6781\u6027`);
2453
+ lines.push("");
2454
+ lines.push(aiContext.polarity === "positive" ? "\u6B63\u5411\u6307\u6807\uFF08\u8D8A\u9AD8\u8D8A\u597D\uFF09" : "\u8D1F\u5411\u6307\u6807\uFF08\u8D8A\u4F4E\u8D8A\u597D\uFF09");
2455
+ lines.push("");
2456
+ if (aiContext.synonyms && aiContext.synonyms.length > 0) {
2457
+ lines.push(`### \u540C\u4E49\u8BCD/\u522B\u540D`);
2458
+ lines.push("");
2459
+ lines.push(aiContext.synonyms.join("\u3001"));
2460
+ lines.push("");
2461
+ }
2462
+ if (aiContext.thresholds && aiContext.thresholds.length > 0) {
2463
+ lines.push(`### \u9884\u8B66\u9608\u503C`);
2464
+ lines.push("");
2465
+ lines.push("| \u6307\u6807 | \u8FD0\u7B97\u7B26 | \u9608\u503C | \u7EA7\u522B |");
2466
+ lines.push("|------|--------|------|------|");
2467
+ for (const t of aiContext.thresholds) {
2468
+ lines.push(`| ${t.metric} | ${t.operator} | ${t.value} | ${t.level} |`);
2469
+ }
2470
+ lines.push("");
2471
+ }
2472
+ if (aiContext.diagnosticWorkflow) {
2473
+ lines.push(`### \u8BCA\u65AD\u5DE5\u4F5C\u6D41`);
2474
+ lines.push("");
2475
+ if (aiContext.diagnosticWorkflow.trigger && aiContext.diagnosticWorkflow.trigger.any_of) {
2476
+ lines.push(`**\u89E6\u53D1\u6761\u4EF6** (\u6EE1\u8DB3\u4EFB\u4E00):`);
2477
+ for (const trigger of aiContext.diagnosticWorkflow.trigger.any_of) {
2478
+ lines.push(`- ${trigger.metric} ${trigger.operator} ${trigger.value}`);
2479
+ }
2480
+ lines.push("");
2481
+ }
2482
+ if (aiContext.diagnosticWorkflow.actions && aiContext.diagnosticWorkflow.actions.length > 0) {
2483
+ lines.push(`**\u5206\u6790\u52A8\u4F5C**:`);
2484
+ for (let i = 0; i < aiContext.diagnosticWorkflow.actions.length; i++) {
2485
+ const action = aiContext.diagnosticWorkflow.actions[i];
2486
+ lines.push(`${i + 1}. **${action.type}**`);
2487
+ if (action.metric) {
2488
+ lines.push(` - \u5BF9\u6BD4\u6307\u6807: ${action.metric}`);
2489
+ }
2490
+ if (action.dimensions && action.dimensions.length > 0) {
2491
+ lines.push(` - \u4E0B\u94BB\u7EF4\u5EA6: ${action.dimensions.join("\u3001")}`);
2492
+ }
2493
+ lines.push(` - \u76EE\u7684: ${action.intent}`);
2494
+ }
2495
+ lines.push("");
2496
+ }
2497
+ if (aiContext.diagnosticWorkflow.analysis_logic) {
2498
+ lines.push(`**\u5206\u6790\u903B\u8F91**: ${aiContext.diagnosticWorkflow.analysis_logic}`);
2499
+ lines.push("");
2500
+ }
2501
+ }
2502
+ if (aiContext.humanReadableExplanation) {
2503
+ lines.push(`### \u7CFB\u7EDF\u5EFA\u8BAE`);
2504
+ lines.push("");
2505
+ lines.push(aiContext.humanReadableExplanation);
2506
+ lines.push("");
2507
+ }
2508
+ }
2509
+ lines.push(`---`);
2510
+ lines.push("");
2511
+ lines.push(`## \u4F7F\u7528\u793A\u4F8B`);
2512
+ lines.push("");
2513
+ lines.push(`\u67E5\u8BE2\u6B64\u6307\u6807\u65F6\uFF0C\u4F7F\u7528 query_semantic_metric_data \u5DE5\u5177\uFF0C\u53C2\u6570:`);
2514
+ lines.push(`- **metricName**: "${foundDetail.metricName}"`);
2515
+ if (foundDatasourceId) {
2516
+ lines.push(`- **datasourceId**: "${foundDatasourceId}"`);
2517
+ }
2518
+ return lines.join("\n");
2519
+ } catch (error) {
2520
+ return `Error querying metric definition: ${error instanceof Error ? error.message : String(error)}`;
2521
+ }
2522
+ },
2523
+ {
2524
+ name: "query_metric_definition",
2525
+ description: `${QUERY_METRIC_DEFINITION_DESCRIPTION}${availableServersText}`,
2526
+ schema: import_zod10.default.object({
2527
+ serverKey: import_zod10.default.string().describe(`Target semantic metrics server. Choose from: ${serverKeys.join(", ")}`),
2528
+ metricName: import_zod10.default.string().describe("The name of the metric to get definition for."),
2529
+ datasourceId: import_zod10.default.string().optional().describe("Optional specific datasource ID to search in. If not provided, searches all selected datasources.")
2530
+ })
2531
+ }
2532
+ );
2533
+ };
2534
+
2535
+ // src/tool_lattice/metrics/query_semantic_metric_data.ts
2536
+ var import_zod11 = __toESM(require("zod"));
2537
+ var import_langchain9 = require("langchain");
2538
+ var QUERY_SEMANTIC_METRIC_DATA_DESCRIPTION = `Query Metric Data - Step 3 of the Metrics Workflow
2539
+
2540
+ Execute queries with the correct parameters derived from metric definitions. This tool requires you to have already discovered and understood the metric metadata.
2541
+
2542
+ When to Use This Tool
2543
+ Use this tool proactively in these scenarios:
2544
+ - When you have the metricName and have read its definition via query_metric_definition
2545
+ - When executing time trend analysis, dimension breakdowns, or drill-downs
2546
+ - When comparing multiple metrics side-by-side
2547
+
2548
+ When NOT to Use This Tool
2549
+ Skip using this tool when:
2550
+ - You haven't retrieved the metric definition yet (call query_metric_definition first)
2551
+ - You're unsure about supported dimensions or time grains for this metric
2552
+
2553
+ Prerequisites - MUST Complete First
2554
+ 1. Call query_metrics_list to discover available metrics
2555
+ 2. Call query_metric_definition(metricName) to get:
2556
+ - defaultTimeContext.timeDimension (e.g., "DocDate")
2557
+ - defaultTimeContext.supportedGrains (e.g., ["day", "week", "month", "year"])
2558
+ - supportedDimensions[].dim_id (use these for groupBy and filters)
2559
+ - supportedDimensions[].filter_operators (allowed operators per dimension)
2560
+
2561
+ The Five Query Patterns
2562
+
2563
+ Pattern A - Time Trend (most common first query)
2564
+ Goal: Show how a metric changes over time within a period
2565
+ {
2566
+ "metrics": ["order_amt_tax_inc"],
2567
+ "groupBy": ["DocDate__month"],
2568
+ "filters": [{ "dimension": "DocDate", "operator": "BETWEEN", "values": ["2025-01-01", "2025-12-31"] }],
2569
+ "orderBy": [{ "field": "DocDate__month", "direction": "ASC" }]
2570
+ }
2571
+
2572
+ Pattern B - Dimension Breakdown (who/what is top or bottom)
2573
+ Goal: Rank performance across a categorical dimension in a fixed period
2574
+ {
2575
+ "metrics": ["order_amt_tax_inc"],
2576
+ "groupBy": ["org_region"],
2577
+ "filters": [{ "dimension": "DocDate", "operator": "BETWEEN", "values": ["2025-01-01", "2025-03-31"] }],
2578
+ "orderBy": [{ "field": "value", "direction": "DESC" }],
2579
+ "limit": 10
2580
+ }
2581
+
2582
+ Pattern C - Drill Down (zoom into an anomaly)
2583
+ Goal: After Pattern A reveals a bad month, find which segment caused it
2584
+ Step 1 - Monthly trend to find anomaly (Pattern A)
2585
+ Step 2 - Drill into that month by adding categorical dimension:
2586
+ {
2587
+ "groupBy": ["sales_person"],
2588
+ "filters": [
2589
+ { "dimension": "DocDate", "operator": "BETWEEN", "values": ["2025-06-01", "2025-06-30"] },
2590
+ { "dimension": "org_region", "operator": "EQ", "values": ["\u534E\u4E1C"] }
2591
+ ],
2592
+ "orderBy": [{ "field": "value", "direction": "ASC" }]
2593
+ }
2594
+
2595
+ Pattern D - Multi-Metric Comparison
2596
+ Goal: Query two or more metrics in one call to compare side-by-side
2597
+ {
2598
+ "metrics": ["order_amt_tax_inc", "net_sales_amt"],
2599
+ "groupBy": ["DocDate__month"],
2600
+ "filters": [{ "dimension": "DocDate", "operator": "BETWEEN", "values": ["2025-01-01", "2025-12-31"] }],
2601
+ "orderBy": [{ "field": "DocDate__month", "direction": "ASC" }]
2602
+ }
2603
+
2604
+ Pattern E - Time x Dimension Cross-Analysis
2605
+ Goal: See how a dimension behaves across time (e.g., monthly sales by region)
2606
+ {
2607
+ "metrics": ["order_amt_tax_inc"],
2608
+ "groupBy": ["DocDate__month", "org_region"],
2609
+ "filters": [{ "dimension": "DocDate", "operator": "BETWEEN", "values": ["2025-01-01", "2025-06-30"] }],
2610
+ "orderBy": [
2611
+ { "field": "DocDate__month", "direction": "ASC" },
2612
+ { "field": "org_region", "direction": "ASC" }
2613
+ ]
2614
+ }
2615
+
2616
+ Filter Operator Reference
2617
+ | Operator | Applies To | Values Array |
2618
+ |----------|------------|--------------|
2619
+ | BETWEEN | datetime, number | [min, max] (inclusive) |
2620
+ | IN | categorical | ["v1", "v2", ...] |
2621
+ | EQ | any | ["v"] |
2622
+ | NEQ | any | ["v"] |
2623
+ | GT / GTE | datetime, number | ["v"] |
2624
+ | LT / LTE | datetime, number | ["v"] |
2625
+ | LIKE | string | ["%pattern%"] |
2626
+ | NOT_NULL | any | [] |
2627
+
2628
+ Common Mistakes to Avoid
2629
+ - Using field_name (e.g., "SlpName") instead of dim_id (e.g., "sales_person")
2630
+ - Writing "DocDate__Month" (capital M) - always lowercase: "DocDate__month"
2631
+ - Omitting date filter entirely - ALWAYS include at least one DocDate filter
2632
+ - Querying a metric by an unsupported dimension - only use dim_id from supportedDimensions
2633
+ - Putting display name in orderBy.field - must match exactly what's in groupBy
2634
+
2635
+ Recommended Analysis Flow
2636
+ User question
2637
+ |
2638
+ \u25BC
2639
+ Step 1: query_metrics_list - find matching metric(s)
2640
+ |
2641
+ \u25BC
2642
+ Step 2: query_metric_definition - read defaultTimeContext + supportedDimensions
2643
+ |
2644
+ \u25BC
2645
+ Step 3a: Pattern A (time trend) - get the big picture
2646
+ |
2647
+ \u251C\u2500 anomaly found? \u2500\u2500\u25BA Step 3c: Pattern C (drill down)
2648
+ \u251C\u2500 user asks "who"? \u2500\u2500\u25BA Step 3b: Pattern B (dimension breakdown)
2649
+ \u2514\u2500 user asks "compare X and Y"? \u2500\u2500\u25BA Step 3d: Pattern D (multi-metric)
2650
+
2651
+ Debug Mode
2652
+ Set "debug": true to receive executedSqls in the response to verify generated SQL.`;
2653
+ function formatSemanticQueryResult(datasourceId, datasourceName, results) {
2654
+ if (results.length === 0) {
2655
+ return `No data found for the specified query.
2656
+ Data Source: ${datasourceId}${datasourceName ? ` (${datasourceName})` : ""}`;
2657
+ }
2658
+ const lines = [];
2659
+ lines.push(`# \u6307\u6807\u67E5\u8BE2\u7ED3\u679C`);
2660
+ lines.push(`
2661
+ **\u6570\u636E\u6E90**: ${datasourceId}${datasourceName ? ` (${datasourceName})` : ""}`);
2662
+ lines.push(`**\u6307\u6807\u6570**: ${results.length}`);
2663
+ lines.push(`
2664
+ ---
2665
+ `);
2666
+ for (const metric of results) {
2667
+ lines.push(`## ${metric.displayName} (${metric.metricName})`);
2668
+ lines.push(`
2669
+ - **\u6570\u636E\u7C7B\u578B**: ${metric.dataType}`);
2670
+ lines.push(`- **\u683C\u5F0F**: ${metric.format}`);
2671
+ lines.push(`- **\u6781\u6027**: ${metric.polarity}`);
2672
+ lines.push(`- **\u6267\u884C\u8017\u65F6**: ${metric.executionTimeMs}ms`);
2673
+ lines.push(`- **\u8FD4\u56DE\u884C\u6570**: ${metric.rowCount}`);
2674
+ if (metric.columns.length > 0 && metric.rows.length > 0) {
2675
+ lines.push(`
2676
+ ### \u6570\u636E
2677
+ `);
2678
+ lines.push(`| ${metric.columns.join(" | ")} |`);
2679
+ lines.push(`|${metric.columns.map(() => "---").join("|")}|`);
2680
+ for (const row of metric.rows) {
2681
+ const rowValues = metric.columns.map((col) => {
2682
+ const val = row[col];
2683
+ return val !== void 0 ? String(val) : "";
2684
+ });
2685
+ lines.push(`| ${rowValues.join(" | ")} |`);
2686
+ }
2687
+ }
2688
+ if (metric.aiHints) {
2689
+ lines.push(`
2690
+ ### AI \u5206\u6790\u5EFA\u8BAE
2691
+ `);
2692
+ lines.push(`- **\u6307\u6807\u89E3\u91CA**: ${metric.aiHints.valueInterpretation}`);
2693
+ if (metric.aiHints.thresholds && metric.aiHints.thresholds.length > 0) {
2694
+ lines.push(`- **\u9884\u8B66\u9608\u503C**:`);
2695
+ for (const t of metric.aiHints.thresholds) {
2696
+ lines.push(` - ${t.metric} ${t.operator} ${t.value} (${t.level})`);
2697
+ }
2698
+ }
2699
+ if (metric.aiHints.suggestedFollowup && metric.aiHints.suggestedFollowup.length > 0) {
2700
+ lines.push(`- **\u5EFA\u8BAE\u540E\u7EED\u5206\u6790**:`);
2701
+ for (const suggestion of metric.aiHints.suggestedFollowup) {
2702
+ lines.push(` - ${suggestion}`);
2703
+ }
2704
+ }
2705
+ }
2706
+ lines.push(`
2707
+ ---
2708
+ `);
2709
+ }
2710
+ return lines.join("\n");
2711
+ }
2712
+ var createQuerySemanticMetricDataTool = ({ serverKeys, serverDescriptions }) => {
2713
+ const availableServersText = serverKeys.length > 0 ? `
2714
+
2715
+ Available metrics servers:
2716
+ ${serverKeys.map(
2717
+ (key) => `- ${key}${serverDescriptions?.[key] ? `: ${serverDescriptions[key]}` : ""}`
2718
+ ).join("\n")}` : "";
2719
+ return (0, import_langchain9.tool)(
2720
+ async ({
2721
+ serverKey,
2722
+ datasourceId,
2723
+ metrics,
2724
+ groupBy,
2725
+ filters,
2726
+ limit
2727
+ }, _exeConfig) => {
2728
+ try {
2729
+ if (!serverKey) {
2730
+ return "Error: serverKey parameter is required. Available servers: " + serverKeys.join(", ");
2731
+ }
2732
+ if (!serverKeys.includes(serverKey)) {
2733
+ return `Error: serverKey "${serverKey}" is not in the allowed list: [${serverKeys.join(", ")}]`;
2734
+ }
2735
+ if (!datasourceId) {
2736
+ return "Error: datasourceId parameter is required.";
2737
+ }
2738
+ if (!metrics || metrics.length === 0) {
2739
+ return "Error: metrics parameter is required (at least one metric name).";
2740
+ }
2741
+ const config = metricsServerManager.getConfig(serverKey);
2742
+ if (config.type !== "semantic") {
2743
+ return `Error: Server "${serverKey}" is not a semantic metrics server. This tool only works with semantic servers.`;
2744
+ }
2745
+ const client = metricsServerManager.getClient(serverKey);
2746
+ const semanticFilters = (filters || []).map((f) => ({
2747
+ dimension: f.dimension,
2748
+ operator: f.operator,
2749
+ values: f.values
2750
+ }));
2751
+ const result = await client.semanticQuery({
2752
+ datasourceId,
2753
+ metrics,
2754
+ groupBy,
2755
+ filters: semanticFilters,
2756
+ limit: limit || 1e3
2757
+ });
2758
+ return formatSemanticQueryResult(
2759
+ result.datasourceId,
2760
+ result.datasourceName,
2761
+ result.results
2762
+ );
2763
+ } catch (error) {
2764
+ return `Error querying semantic metric data: ${error instanceof Error ? error.message : String(error)}`;
2765
+ }
2766
+ },
2767
+ {
2768
+ name: "query_semantic_metric_data",
2769
+ description: `${QUERY_SEMANTIC_METRIC_DATA_DESCRIPTION}${availableServersText}`,
2770
+ schema: import_zod11.default.object({
2771
+ serverKey: import_zod11.default.string().describe(`Target semantic metrics server. Choose from: ${serverKeys.join(", ")}`),
2772
+ datasourceId: import_zod11.default.string().describe("The data source ID to query metrics from."),
2773
+ metrics: import_zod11.default.array(import_zod11.default.string()).describe("Array of metric names to query (e.g., ['net_sales_amt', 'gross_profit'])."),
2774
+ groupBy: import_zod11.default.array(import_zod11.default.string()).optional().describe("Optional array of dimensions to group by (e.g., ['DocDate__month', 'CustomerCode'])."),
2775
+ filters: import_zod11.default.array(import_zod11.default.object({
2776
+ dimension: import_zod11.default.string().describe("Dimension/column name to filter on"),
2777
+ operator: import_zod11.default.string().describe("Operator (e.g., 'BETWEEN', '=', '>', '<')"),
2778
+ values: import_zod11.default.array(import_zod11.default.union([import_zod11.default.string(), import_zod11.default.number(), import_zod11.default.boolean()])).describe("Filter values")
2779
+ })).optional().describe("Optional array of filters to apply to the query."),
2780
+ limit: import_zod11.default.number().optional().describe("Maximum number of results to return (default: 1000).")
2781
+ })
2782
+ }
2783
+ );
2784
+ };
2785
+
2786
+ // src/tool_lattice/metrics/query_tables_list.ts
2787
+ var import_zod12 = __toESM(require("zod"));
2788
+ var import_langchain10 = require("langchain");
2789
+ var QUERY_TABLES_LIST_DESCRIPTION = `Query available tables from a semantic metrics server. Returns a list of data tables with their schemas and descriptions. Use this tool to discover what tables are available in the data source.`;
2790
+ var createQueryTablesListTool = ({ serverKeys, serverDescriptions }) => {
2791
+ const availableServersText = serverKeys.length > 0 ? `
2792
+
2793
+ Available metrics servers:
2794
+ ${serverKeys.map(
2795
+ (key) => `- ${key}${serverDescriptions?.[key] ? `: ${serverDescriptions[key]}` : ""}`
2796
+ ).join("\n")}` : "";
2797
+ return (0, import_langchain10.tool)(
2798
+ async ({
2799
+ serverKey,
2800
+ datasourceIds
2801
+ }, _exeConfig) => {
2802
+ try {
2803
+ if (!serverKey) {
2804
+ return "Error: serverKey parameter is required. Available servers: " + serverKeys.join(", ");
2805
+ }
2806
+ if (!serverKeys.includes(serverKey)) {
2807
+ return `Error: serverKey "${serverKey}" is not in the allowed list: [${serverKeys.join(", ")}]`;
2808
+ }
2809
+ const config = metricsServerManager.getConfig(serverKey);
2810
+ if (config.type !== "semantic") {
2811
+ return `Error: Server "${serverKey}" is not a semantic metrics server. This tool only works with semantic servers.`;
2812
+ }
2813
+ const client = metricsServerManager.getClient(serverKey);
2814
+ const targetDatasourceIds = datasourceIds && datasourceIds.length > 0 ? datasourceIds : client.getSelectedDataSources();
2815
+ if (targetDatasourceIds.length === 0) {
2816
+ return `Error: No data sources specified and no default data sources configured for server "${serverKey}".`;
2817
+ }
2818
+ const allTables = /* @__PURE__ */ new Map();
2819
+ for (const datasourceId of targetDatasourceIds) {
2820
+ try {
2821
+ const metaData = await client.getDatasourceMetrics(datasourceId);
2822
+ const index = metaData.index;
2823
+ for (const item of index.tables) {
2824
+ const tableKey = item.tableName;
2825
+ if (allTables.has(tableKey)) {
2826
+ const existing = allTables.get(tableKey);
2827
+ if (!existing.datasources.includes(datasourceId)) {
2828
+ existing.datasources.push(datasourceId);
2829
+ }
2830
+ } else {
2831
+ allTables.set(tableKey, {
2832
+ tableName: item.tableName,
2833
+ displayName: item.displayName,
2834
+ docType: item.docType,
2835
+ docTypeEn: item.docTypeEn,
2836
+ mainTable: item.mainTable,
2837
+ lineTable: item.lineTable,
2838
+ columnCount: item.columnCount,
2839
+ shortDesc: item.shortDesc,
2840
+ datasources: [datasourceId]
2841
+ });
2842
+ }
2843
+ }
2844
+ } catch (error) {
2845
+ console.warn(`Failed to get tables for datasource ${datasourceId}:`, error);
2846
+ }
2847
+ }
2848
+ if (allTables.size === 0) {
2849
+ return `\u672A\u5728\u6307\u5B9A\u7684\u6570\u636E\u6E90\u4E2D\u627E\u5230\u6570\u636E\u8868\u3002`;
2850
+ }
2851
+ const lines = [];
2852
+ lines.push(`## \u6570\u636E\u8868\u5217\u8868\uFF08\u5171 ${allTables.size} \u4E2A\uFF09
2853
+ `);
2854
+ const sortedTables = Array.from(allTables.values()).sort(
2855
+ (a, b) => a.tableName.localeCompare(b.tableName)
2856
+ );
2857
+ lines.push("| \u8868\u540D | \u663E\u793A\u540D\u79F0 | \u5355\u636E\u7C7B\u578B | \u5217\u6570 | \u63CF\u8FF0 |");
2858
+ lines.push("|------|---------|---------|------|------|");
2859
+ for (const table of sortedTables) {
2860
+ const mainTableInfo = table.mainTable ? ` (\u4E3B\u8868: ${table.mainTable})` : "";
2861
+ const lineTableInfo = table.lineTable ? ` (\u884C\u8868: ${table.lineTable})` : "";
2862
+ const tableRelation = mainTableInfo + lineTableInfo;
2863
+ lines.push(`| ${table.tableName} | ${table.displayName} | ${table.docType}${tableRelation} | ${table.columnCount} | ${table.shortDesc} |`);
2864
+ }
2865
+ return lines.join("\n");
2866
+ } catch (error) {
2867
+ return `Error querying tables list: ${error instanceof Error ? error.message : String(error)}`;
2868
+ }
2869
+ },
2870
+ {
2871
+ name: "query_tables_list",
2872
+ description: `${QUERY_TABLES_LIST_DESCRIPTION}${availableServersText}`,
2873
+ schema: import_zod12.default.object({
2874
+ serverKey: import_zod12.default.string().describe(`Target semantic metrics server. Choose from: ${serverKeys.join(", ")}`),
2875
+ datasourceIds: import_zod12.default.array(import_zod12.default.string()).optional().describe("Optional array of datasource IDs to query. If not provided, uses all selected datasources.")
2876
+ })
2877
+ }
2878
+ );
2879
+ };
2880
+
2881
+ // src/tool_lattice/metrics/query_table_definition.ts
2882
+ var import_zod13 = __toESM(require("zod"));
2883
+ var import_langchain11 = require("langchain");
2884
+ var QUERY_TABLE_DEFINITION_DESCRIPTION = `Get detailed definition and schema for a specific table from a semantic metrics server. Returns comprehensive information including column definitions, SQL query, and table relationships.`;
2885
+ var createQueryTableDefinitionTool = ({ serverKeys, serverDescriptions }) => {
2886
+ const availableServersText = serverKeys.length > 0 ? `
2887
+
2888
+ Available metrics servers:
2889
+ ${serverKeys.map(
2890
+ (key) => `- ${key}${serverDescriptions?.[key] ? `: ${serverDescriptions[key]}` : ""}`
2891
+ ).join("\n")}` : "";
2892
+ return (0, import_langchain11.tool)(
2893
+ async ({
2894
+ serverKey,
2895
+ tableName,
2896
+ datasourceId
2897
+ }, _exeConfig) => {
2898
+ try {
2899
+ if (!serverKey) {
2900
+ return "Error: serverKey parameter is required. Available servers: " + serverKeys.join(", ");
2901
+ }
2902
+ if (!serverKeys.includes(serverKey)) {
2903
+ return `Error: serverKey "${serverKey}" is not in the allowed list: [${serverKeys.join(", ")}]`;
2904
+ }
2905
+ if (!tableName) {
2906
+ return "Error: tableName parameter is required.";
2907
+ }
2908
+ const config = metricsServerManager.getConfig(serverKey);
2909
+ if (config.type !== "semantic") {
2910
+ return `Error: Server "${serverKey}" is not a semantic metrics server. This tool only works with semantic servers.`;
2911
+ }
2912
+ const client = metricsServerManager.getClient(serverKey);
2913
+ const targetDatasourceIds = datasourceId ? [datasourceId] : client.getSelectedDataSources();
2914
+ if (targetDatasourceIds.length === 0) {
2915
+ return `Error: No datasourceId specified and no default data sources configured for server "${serverKey}".`;
2916
+ }
2917
+ let foundTable = null;
2918
+ let foundDatasourceId = null;
2919
+ for (const dsId of targetDatasourceIds) {
2920
+ try {
2921
+ const metaData = await client.getDatasourceMetrics(dsId);
2922
+ const tableDetail = metaData.tablesDetails?.find((t) => t.tableName === tableName);
2923
+ if (tableDetail) {
2924
+ foundTable = tableDetail;
2925
+ foundDatasourceId = dsId;
2926
+ break;
2927
+ }
2928
+ } catch (error) {
2929
+ console.warn(`Failed to get table definition for datasource ${dsId}:`, error);
2930
+ }
2931
+ }
2932
+ if (!foundTable) {
2933
+ return `Table "${tableName}" not found in the specified data sources.`;
2934
+ }
2935
+ const lines = [];
2936
+ lines.push(`# ${foundTable.tableName}`);
2937
+ lines.push("");
2938
+ lines.push(`## \u57FA\u672C\u4FE1\u606F`);
2939
+ lines.push("");
2940
+ lines.push(`- **\u8868\u540D**: ${foundTable.tableName}`);
2941
+ lines.push(`- **\u5355\u636E\u7C7B\u578B**: ${foundTable.docType}`);
2942
+ lines.push(`- **\u5355\u636E\u7C7B\u578B(\u82F1\u6587)**: ${foundTable.docTypeEn}`);
2943
+ if (foundTable.objTypeCode) {
2944
+ lines.push(`- **\u5BF9\u8C61\u7C7B\u578B\u4EE3\u7801**: ${foundTable.objTypeCode}`);
2945
+ }
2946
+ if (foundTable.mainTable) {
2947
+ lines.push(`- **\u4E3B\u8868**: ${foundTable.mainTable}`);
2948
+ }
2949
+ if (foundTable.lineTable) {
2950
+ lines.push(`- **\u884C\u8868**: ${foundTable.lineTable}`);
2951
+ }
2952
+ if (foundDatasourceId) {
2953
+ lines.push(`- **\u6570\u636E\u6E90ID**: ${foundDatasourceId}`);
2954
+ }
2955
+ lines.push("");
2956
+ if (foundTable.columns && foundTable.columns.length > 0) {
2957
+ const validColumns = foundTable.columns.filter((col) => col !== null);
2958
+ lines.push(`## \u5217\u5B9A\u4E49 (${validColumns.length} \u5217)`);
2959
+ lines.push("");
2960
+ lines.push("| \u5217\u540D | \u6807\u7B7E | \u7C7B\u578B | \u793A\u4F8B\u503C |");
2961
+ lines.push("|------|------|------|--------|");
2962
+ for (const col of validColumns) {
2963
+ const type = col.type || "-";
2964
+ const example = col.example || "-";
2965
+ lines.push(`| ${col.name} | ${col.label} | ${type} | ${example} |`);
2966
+ }
2967
+ lines.push("");
2968
+ }
2969
+ if (foundTable.selectSql) {
2970
+ lines.push(`## SQL \u67E5\u8BE2`);
2971
+ lines.push("");
2972
+ lines.push("```sql");
2973
+ lines.push(foundTable.selectSql);
2974
+ lines.push("```");
2975
+ lines.push("");
2976
+ }
2977
+ return lines.join("\n");
2978
+ } catch (error) {
2979
+ return `Error querying table definition: ${error instanceof Error ? error.message : String(error)}`;
2980
+ }
2981
+ },
2982
+ {
2983
+ name: "query_table_definition",
2984
+ description: `${QUERY_TABLE_DEFINITION_DESCRIPTION}${availableServersText}`,
2985
+ schema: import_zod13.default.object({
2986
+ serverKey: import_zod13.default.string().describe(`Target semantic metrics server. Choose from: ${serverKeys.join(", ")}`),
2987
+ tableName: import_zod13.default.string().describe("The name of the table to get definition for."),
2988
+ datasourceId: import_zod13.default.string().optional().describe("Optional specific datasource ID to search in. If not provided, searches all selected datasources.")
2989
+ })
2990
+ }
2991
+ );
2992
+ };
2993
+
1392
2994
  // src/tool_lattice/code_eval/index.ts
1393
- var import_zod7 = __toESM(require("zod"));
2995
+ var import_zod14 = __toESM(require("zod"));
1394
2996
 
1395
2997
  // src/sandbox_lattice/SandboxLatticeManager.ts
1396
2998
  var import_sandbox = require("@agent-infra/sandbox");
@@ -1629,7 +3231,7 @@ var getSandBoxManager = (key = "default") => {
1629
3231
  };
1630
3232
 
1631
3233
  // src/tool_lattice/code_eval/index.ts
1632
- var import_langchain5 = require("langchain");
3234
+ var import_langchain12 = require("langchain");
1633
3235
  var CODE_EVAL_DESCRIPTION = `Execute code in Python or JavaScript runtime.
1634
3236
 
1635
3237
  Args:
@@ -1639,7 +3241,7 @@ Args:
1639
3241
  Returns:
1640
3242
  Dict containing output, errors, and execution details`;
1641
3243
  var createCodeEvalTool = ({ isolatedLevel }) => {
1642
- return (0, import_langchain5.tool)(async (input, exe_config) => {
3244
+ return (0, import_langchain12.tool)(async (input, exe_config) => {
1643
3245
  try {
1644
3246
  const runConfig = exe_config.configurable?.runConfig;
1645
3247
  const sandboxManager = getSandBoxManager();
@@ -1680,16 +3282,16 @@ ${traceback.join("\n")}`);
1680
3282
  }, {
1681
3283
  name: "execute_code",
1682
3284
  description: CODE_EVAL_DESCRIPTION,
1683
- schema: import_zod7.default.object({
1684
- language: import_zod7.default.enum(["python", "javascript"]).describe("Programming language: 'python' or 'javascript'"),
1685
- code: import_zod7.default.string().describe("Code to execute")
3285
+ schema: import_zod14.default.object({
3286
+ language: import_zod14.default.enum(["python", "javascript"]).describe("Programming language: 'python' or 'javascript'"),
3287
+ code: import_zod14.default.string().describe("Code to execute")
1686
3288
  })
1687
3289
  });
1688
3290
  };
1689
3291
 
1690
3292
  // src/tool_lattice/code_execute_file/index.ts
1691
- var import_zod8 = __toESM(require("zod"));
1692
- var import_langchain6 = require("langchain");
3293
+ var import_zod15 = __toESM(require("zod"));
3294
+ var import_langchain13 = require("langchain");
1693
3295
  var path = __toESM(require("path"));
1694
3296
  var CODE_EXECUTE_FILE_DESCRIPTION = `Execute a code file from the sandbox filesystem. Only supports Python (.py) and JavaScript (.js, .mjs) files. Other file types are not supported. The tool reads the file content and executes it in an isolated sandbox environment. Language is automatically inferred from the file extension. Output is returned via stdout; errors appear in stderr and traceback.`;
1695
3297
  function inferLanguageFromPath(filePath) {
@@ -1702,7 +3304,7 @@ function inferLanguageFromPath(filePath) {
1702
3304
  return null;
1703
3305
  }
1704
3306
  var createCodeExecuteFileTool = ({ isolatedLevel }) => {
1705
- return (0, import_langchain6.tool)(
3307
+ return (0, import_langchain13.tool)(
1706
3308
  async (input, exe_config) => {
1707
3309
  try {
1708
3310
  const runConfig = exe_config.configurable?.runConfig;
@@ -1765,15 +3367,15 @@ ${traceback.join("\n")}`);
1765
3367
  {
1766
3368
  name: "execute_code_file",
1767
3369
  description: CODE_EXECUTE_FILE_DESCRIPTION,
1768
- schema: import_zod8.default.object({
1769
- file_path: import_zod8.default.string().describe("Path to the code file to execute (absolute path in sandbox filesystem). Only supports .py (Python) and .js/.mjs (JavaScript) files.")
3370
+ schema: import_zod15.default.object({
3371
+ file_path: import_zod15.default.string().describe("Path to the code file to execute (absolute path in sandbox filesystem). Only supports .py (Python) and .js/.mjs (JavaScript) files.")
1770
3372
  })
1771
3373
  }
1772
3374
  );
1773
3375
  };
1774
3376
 
1775
3377
  // src/tool_lattice/convert_to_markdown/index.ts
1776
- var import_zod9 = __toESM(require("zod"));
3378
+ var import_zod16 = __toESM(require("zod"));
1777
3379
  var CONVERT_TO_MARKDOWN_DESCRIPTION = `Convert a resource described by an http:, https:, file: or data: URI to markdown.
1778
3380
 
1779
3381
  Args:
@@ -1790,8 +3392,8 @@ registerToolLattice(
1790
3392
  name: "convert_to_markdown",
1791
3393
  description: CONVERT_TO_MARKDOWN_DESCRIPTION,
1792
3394
  needUserApprove: false,
1793
- schema: import_zod9.default.object({
1794
- uri: import_zod9.default.string().describe("The URI to convert.")
3395
+ schema: import_zod16.default.object({
3396
+ uri: import_zod16.default.string().describe("The URI to convert.")
1795
3397
  })
1796
3398
  },
1797
3399
  async (input, exe_config) => {
@@ -1814,15 +3416,15 @@ registerToolLattice(
1814
3416
  );
1815
3417
 
1816
3418
  // src/tool_lattice/browser/browser_navigate.ts
1817
- var import_zod10 = __toESM(require("zod"));
1818
- var import_langchain7 = require("langchain");
3419
+ var import_zod17 = __toESM(require("zod"));
3420
+ var import_langchain14 = require("langchain");
1819
3421
  var BROWSER_NAVIGATE_DESCRIPTION = `Navigate to a URL.
1820
3422
 
1821
3423
  Args:
1822
3424
  url (str): The URL to navigate to.
1823
3425
  `;
1824
3426
  var createBrowserNavigateTool = ({ isolatedLevel }) => {
1825
- return (0, import_langchain7.tool)(
3427
+ return (0, import_langchain14.tool)(
1826
3428
  async (input, exe_config) => {
1827
3429
  try {
1828
3430
  const runConfig = exe_config.configurable?.runConfig;
@@ -1842,23 +3444,23 @@ var createBrowserNavigateTool = ({ isolatedLevel }) => {
1842
3444
  {
1843
3445
  name: "browser_navigate",
1844
3446
  description: BROWSER_NAVIGATE_DESCRIPTION,
1845
- schema: import_zod10.default.object({
1846
- url: import_zod10.default.string().describe("The URL to navigate to.")
3447
+ schema: import_zod17.default.object({
3448
+ url: import_zod17.default.string().describe("The URL to navigate to.")
1847
3449
  })
1848
3450
  }
1849
3451
  );
1850
3452
  };
1851
3453
 
1852
3454
  // src/tool_lattice/browser/browser_click.ts
1853
- var import_zod11 = __toESM(require("zod"));
1854
- var import_langchain8 = require("langchain");
3455
+ var import_zod18 = __toESM(require("zod"));
3456
+ var import_langchain15 = require("langchain");
1855
3457
  var BROWSER_CLICK_DESCRIPTION = `Click an element on the page, before using the tool, use \`browser_get_clickable_elements\` to get the index of the element, but not call \`browser_get_clickable_elements\` multiple times.
1856
3458
 
1857
3459
  Args:
1858
3460
  index (int): Index of the element to click
1859
3461
  `;
1860
3462
  var createBrowserClickTool = ({ isolatedLevel }) => {
1861
- return (0, import_langchain8.tool)(
3463
+ return (0, import_langchain15.tool)(
1862
3464
  async (input, exe_config) => {
1863
3465
  try {
1864
3466
  const runConfig = exe_config.configurable?.runConfig;
@@ -1878,23 +3480,23 @@ var createBrowserClickTool = ({ isolatedLevel }) => {
1878
3480
  {
1879
3481
  name: "browser_click",
1880
3482
  description: BROWSER_CLICK_DESCRIPTION,
1881
- schema: import_zod11.default.object({
1882
- index: import_zod11.default.number().describe("Index of the element to click")
3483
+ schema: import_zod18.default.object({
3484
+ index: import_zod18.default.number().describe("Index of the element to click")
1883
3485
  })
1884
3486
  }
1885
3487
  );
1886
3488
  };
1887
3489
 
1888
3490
  // src/tool_lattice/browser/browser_get_text.ts
1889
- var import_zod12 = __toESM(require("zod"));
1890
- var import_langchain9 = require("langchain");
3491
+ var import_zod19 = __toESM(require("zod"));
3492
+ var import_langchain16 = require("langchain");
1891
3493
  var BROWSER_GET_TEXT_DESCRIPTION = `Get the text content of the current page.
1892
3494
 
1893
3495
  Args:
1894
3496
  None
1895
3497
  `;
1896
3498
  var createBrowserGetTextTool = ({ isolatedLevel }) => {
1897
- return (0, import_langchain9.tool)(
3499
+ return (0, import_langchain16.tool)(
1898
3500
  async (input, exe_config) => {
1899
3501
  try {
1900
3502
  const runConfig = exe_config.configurable?.runConfig;
@@ -1912,21 +3514,21 @@ var createBrowserGetTextTool = ({ isolatedLevel }) => {
1912
3514
  {
1913
3515
  name: "browser_get_text",
1914
3516
  description: BROWSER_GET_TEXT_DESCRIPTION,
1915
- schema: import_zod12.default.object({})
3517
+ schema: import_zod19.default.object({})
1916
3518
  }
1917
3519
  );
1918
3520
  };
1919
3521
 
1920
3522
  // src/tool_lattice/browser/browser_get_markdown.ts
1921
- var import_zod13 = __toESM(require("zod"));
1922
- var import_langchain10 = require("langchain");
3523
+ var import_zod20 = __toESM(require("zod"));
3524
+ var import_langchain17 = require("langchain");
1923
3525
  var BROWSER_GET_MARKDOWN_DESCRIPTION = `Get the markdown content of the current page.
1924
3526
 
1925
3527
  Args:
1926
3528
  None
1927
3529
  `;
1928
3530
  var createBrowserGetMarkdownTool = ({ isolatedLevel }) => {
1929
- return (0, import_langchain10.tool)(
3531
+ return (0, import_langchain17.tool)(
1930
3532
  async (input, exe_config) => {
1931
3533
  try {
1932
3534
  const runConfig = exe_config.configurable?.runConfig;
@@ -1944,21 +3546,21 @@ var createBrowserGetMarkdownTool = ({ isolatedLevel }) => {
1944
3546
  {
1945
3547
  name: "browser_get_markdown",
1946
3548
  description: BROWSER_GET_MARKDOWN_DESCRIPTION,
1947
- schema: import_zod13.default.object({})
3549
+ schema: import_zod20.default.object({})
1948
3550
  }
1949
3551
  );
1950
3552
  };
1951
3553
 
1952
3554
  // src/tool_lattice/browser/browser_evaluate.ts
1953
- var import_zod14 = __toESM(require("zod"));
1954
- var import_langchain11 = require("langchain");
3555
+ var import_zod21 = __toESM(require("zod"));
3556
+ var import_langchain18 = require("langchain");
1955
3557
  var BROWSER_EVALUATE_DESCRIPTION = `Execute JavaScript in the browser console.
1956
3558
 
1957
3559
  Args:
1958
3560
  script (str): JavaScript code to execute, () => { /* code */ }
1959
3561
  `;
1960
3562
  var createBrowserEvaluateTool = ({ isolatedLevel }) => {
1961
- return (0, import_langchain11.tool)(
3563
+ return (0, import_langchain18.tool)(
1962
3564
  async (input, exe_config) => {
1963
3565
  try {
1964
3566
  const runConfig = exe_config.configurable?.runConfig;
@@ -1978,16 +3580,16 @@ var createBrowserEvaluateTool = ({ isolatedLevel }) => {
1978
3580
  {
1979
3581
  name: "browser_evaluate",
1980
3582
  description: BROWSER_EVALUATE_DESCRIPTION,
1981
- schema: import_zod14.default.object({
1982
- script: import_zod14.default.string().describe("JavaScript code to execute, () => { /* code */ }")
3583
+ schema: import_zod21.default.object({
3584
+ script: import_zod21.default.string().describe("JavaScript code to execute, () => { /* code */ }")
1983
3585
  })
1984
3586
  }
1985
3587
  );
1986
3588
  };
1987
3589
 
1988
3590
  // src/tool_lattice/browser/browser_screenshot.ts
1989
- var import_zod15 = __toESM(require("zod"));
1990
- var import_langchain12 = require("langchain");
3591
+ var import_zod22 = __toESM(require("zod"));
3592
+ var import_langchain19 = require("langchain");
1991
3593
  var BROWSER_SCREENSHOT_DESCRIPTION = `Take a screenshot of the current page or a specific element.
1992
3594
 
1993
3595
  Args:
@@ -2000,7 +3602,7 @@ Args:
2000
3602
  highlight (bool): Highlight the element
2001
3603
  `;
2002
3604
  var createBrowserScreenshotTool = ({ isolatedLevel }) => {
2003
- return (0, import_langchain12.tool)(
3605
+ return (0, import_langchain19.tool)(
2004
3606
  async (input, exe_config) => {
2005
3607
  try {
2006
3608
  const runConfig = exe_config.configurable?.runConfig;
@@ -2052,29 +3654,29 @@ var createBrowserScreenshotTool = ({ isolatedLevel }) => {
2052
3654
  {
2053
3655
  name: "browser_screenshot",
2054
3656
  description: BROWSER_SCREENSHOT_DESCRIPTION,
2055
- schema: import_zod15.default.object({
2056
- name: import_zod15.default.string().optional().describe("Name for the screenshot"),
2057
- selector: import_zod15.default.string().optional().describe("CSS selector for element to screenshot"),
2058
- index: import_zod15.default.number().optional().describe("index of the element to screenshot"),
2059
- width: import_zod15.default.number().optional().describe("Width in pixels (default: viewport width)"),
2060
- height: import_zod15.default.number().optional().describe("Height in pixels (default: viewport height)"),
2061
- fullPage: import_zod15.default.boolean().optional().describe("Full page screenshot (default: false)"),
2062
- highlight: import_zod15.default.boolean().default(false).describe("Highlight the element")
3657
+ schema: import_zod22.default.object({
3658
+ name: import_zod22.default.string().optional().describe("Name for the screenshot"),
3659
+ selector: import_zod22.default.string().optional().describe("CSS selector for element to screenshot"),
3660
+ index: import_zod22.default.number().optional().describe("index of the element to screenshot"),
3661
+ width: import_zod22.default.number().optional().describe("Width in pixels (default: viewport width)"),
3662
+ height: import_zod22.default.number().optional().describe("Height in pixels (default: viewport height)"),
3663
+ fullPage: import_zod22.default.boolean().optional().describe("Full page screenshot (default: false)"),
3664
+ highlight: import_zod22.default.boolean().default(false).describe("Highlight the element")
2063
3665
  })
2064
3666
  }
2065
3667
  );
2066
3668
  };
2067
3669
 
2068
3670
  // src/tool_lattice/browser/browser_scroll.ts
2069
- var import_zod16 = __toESM(require("zod"));
2070
- var import_langchain13 = require("langchain");
3671
+ var import_zod23 = __toESM(require("zod"));
3672
+ var import_langchain20 = require("langchain");
2071
3673
  var BROWSER_SCROLL_DESCRIPTION = `Scroll the page.
2072
3674
 
2073
3675
  Args:
2074
3676
  amount (int): Pixels to scroll (positive for down, negative for up), if the amount is not provided, scroll to the bottom of the page
2075
3677
  `;
2076
3678
  var createBrowserScrollTool = ({ isolatedLevel }) => {
2077
- return (0, import_langchain13.tool)(
3679
+ return (0, import_langchain20.tool)(
2078
3680
  async (input, exe_config) => {
2079
3681
  try {
2080
3682
  const runConfig = exe_config.configurable?.runConfig;
@@ -2094,16 +3696,16 @@ var createBrowserScrollTool = ({ isolatedLevel }) => {
2094
3696
  {
2095
3697
  name: "browser_scroll",
2096
3698
  description: BROWSER_SCROLL_DESCRIPTION,
2097
- schema: import_zod16.default.object({
2098
- amount: import_zod16.default.number().optional().describe("Pixels to scroll (positive for down, negative for up)")
3699
+ schema: import_zod23.default.object({
3700
+ amount: import_zod23.default.number().optional().describe("Pixels to scroll (positive for down, negative for up)")
2099
3701
  })
2100
3702
  }
2101
3703
  );
2102
3704
  };
2103
3705
 
2104
3706
  // src/tool_lattice/browser/browser_form_input_fill.ts
2105
- var import_zod17 = __toESM(require("zod"));
2106
- var import_langchain14 = require("langchain");
3707
+ var import_zod24 = __toESM(require("zod"));
3708
+ var import_langchain21 = require("langchain");
2107
3709
  var BROWSER_FORM_INPUT_FILL_DESCRIPTION = `Fill out an input field, before using the tool, Either 'index' or 'selector' must be provided.
2108
3710
 
2109
3711
  Args:
@@ -2113,7 +3715,7 @@ Args:
2113
3715
  clear (bool): Whether to clear existing text before filling
2114
3716
  `;
2115
3717
  var createBrowserFormInputFillTool = ({ isolatedLevel }) => {
2116
- return (0, import_langchain14.tool)(
3718
+ return (0, import_langchain21.tool)(
2117
3719
  async (input, exe_config) => {
2118
3720
  try {
2119
3721
  const runConfig = exe_config.configurable?.runConfig;
@@ -2136,19 +3738,19 @@ var createBrowserFormInputFillTool = ({ isolatedLevel }) => {
2136
3738
  {
2137
3739
  name: "browser_form_input_fill",
2138
3740
  description: BROWSER_FORM_INPUT_FILL_DESCRIPTION,
2139
- schema: import_zod17.default.object({
2140
- selector: import_zod17.default.string().optional().describe("CSS selector for input field"),
2141
- index: import_zod17.default.number().optional().describe("Index of the element to fill"),
2142
- value: import_zod17.default.string().describe("Value to fill"),
2143
- clear: import_zod17.default.boolean().default(false).describe("Whether to clear existing text before filling")
3741
+ schema: import_zod24.default.object({
3742
+ selector: import_zod24.default.string().optional().describe("CSS selector for input field"),
3743
+ index: import_zod24.default.number().optional().describe("Index of the element to fill"),
3744
+ value: import_zod24.default.string().describe("Value to fill"),
3745
+ clear: import_zod24.default.boolean().default(false).describe("Whether to clear existing text before filling")
2144
3746
  })
2145
3747
  }
2146
3748
  );
2147
3749
  };
2148
3750
 
2149
3751
  // src/tool_lattice/browser/browser_select.ts
2150
- var import_zod18 = __toESM(require("zod"));
2151
- var import_langchain15 = require("langchain");
3752
+ var import_zod25 = __toESM(require("zod"));
3753
+ var import_langchain22 = require("langchain");
2152
3754
  var BROWSER_SELECT_DESCRIPTION = `Select an element on the page with index, Either 'index' or 'selector' must be provided.
2153
3755
 
2154
3756
  Args:
@@ -2157,7 +3759,7 @@ Args:
2157
3759
  value (str): Value to select
2158
3760
  `;
2159
3761
  var createBrowserSelectTool = ({ isolatedLevel }) => {
2160
- return (0, import_langchain15.tool)(
3762
+ return (0, import_langchain22.tool)(
2161
3763
  async (input, exe_config) => {
2162
3764
  try {
2163
3765
  const runConfig = exe_config.configurable?.runConfig;
@@ -2179,18 +3781,18 @@ var createBrowserSelectTool = ({ isolatedLevel }) => {
2179
3781
  {
2180
3782
  name: "browser_select",
2181
3783
  description: BROWSER_SELECT_DESCRIPTION,
2182
- schema: import_zod18.default.object({
2183
- index: import_zod18.default.number().optional().describe("Index of the element to select"),
2184
- selector: import_zod18.default.string().optional().describe("CSS selector for element to select"),
2185
- value: import_zod18.default.string().describe("Value to select")
3784
+ schema: import_zod25.default.object({
3785
+ index: import_zod25.default.number().optional().describe("Index of the element to select"),
3786
+ selector: import_zod25.default.string().optional().describe("CSS selector for element to select"),
3787
+ value: import_zod25.default.string().describe("Value to select")
2186
3788
  })
2187
3789
  }
2188
3790
  );
2189
3791
  };
2190
3792
 
2191
3793
  // src/tool_lattice/browser/browser_hover.ts
2192
- var import_zod19 = __toESM(require("zod"));
2193
- var import_langchain16 = require("langchain");
3794
+ var import_zod26 = __toESM(require("zod"));
3795
+ var import_langchain23 = require("langchain");
2194
3796
  var BROWSER_HOVER_DESCRIPTION = `Hover an element on the page, Either 'index' or 'selector' must be provided.
2195
3797
 
2196
3798
  Args:
@@ -2198,7 +3800,7 @@ Args:
2198
3800
  selector (str): CSS selector for element to hover
2199
3801
  `;
2200
3802
  var createBrowserHoverTool = ({ isolatedLevel }) => {
2201
- return (0, import_langchain16.tool)(
3803
+ return (0, import_langchain23.tool)(
2202
3804
  async (input, exe_config) => {
2203
3805
  try {
2204
3806
  const runConfig = exe_config.configurable?.runConfig;
@@ -2219,24 +3821,24 @@ var createBrowserHoverTool = ({ isolatedLevel }) => {
2219
3821
  {
2220
3822
  name: "browser_hover",
2221
3823
  description: BROWSER_HOVER_DESCRIPTION,
2222
- schema: import_zod19.default.object({
2223
- index: import_zod19.default.number().optional().describe("Index of the element to hover"),
2224
- selector: import_zod19.default.string().optional().describe("CSS selector for element to hover")
3824
+ schema: import_zod26.default.object({
3825
+ index: import_zod26.default.number().optional().describe("Index of the element to hover"),
3826
+ selector: import_zod26.default.string().optional().describe("CSS selector for element to hover")
2225
3827
  })
2226
3828
  }
2227
3829
  );
2228
3830
  };
2229
3831
 
2230
3832
  // src/tool_lattice/browser/browser_go_back.ts
2231
- var import_zod20 = __toESM(require("zod"));
2232
- var import_langchain17 = require("langchain");
3833
+ var import_zod27 = __toESM(require("zod"));
3834
+ var import_langchain24 = require("langchain");
2233
3835
  var BROWSER_GO_BACK_DESCRIPTION = `Go back to the previous page.
2234
3836
 
2235
3837
  Args:
2236
3838
  None
2237
3839
  `;
2238
3840
  var createBrowserGoBackTool = ({ isolatedLevel }) => {
2239
- return (0, import_langchain17.tool)(
3841
+ return (0, import_langchain24.tool)(
2240
3842
  async (input, exe_config) => {
2241
3843
  try {
2242
3844
  const runConfig = exe_config.configurable?.runConfig;
@@ -2254,21 +3856,21 @@ var createBrowserGoBackTool = ({ isolatedLevel }) => {
2254
3856
  {
2255
3857
  name: "browser_go_back",
2256
3858
  description: BROWSER_GO_BACK_DESCRIPTION,
2257
- schema: import_zod20.default.object({})
3859
+ schema: import_zod27.default.object({})
2258
3860
  }
2259
3861
  );
2260
3862
  };
2261
3863
 
2262
3864
  // src/tool_lattice/browser/browser_go_forward.ts
2263
- var import_zod21 = __toESM(require("zod"));
2264
- var import_langchain18 = require("langchain");
3865
+ var import_zod28 = __toESM(require("zod"));
3866
+ var import_langchain25 = require("langchain");
2265
3867
  var BROWSER_GO_FORWARD_DESCRIPTION = `Go forward to the next page.
2266
3868
 
2267
3869
  Args:
2268
3870
  None
2269
3871
  `;
2270
3872
  var createBrowserGoForwardTool = ({ isolatedLevel }) => {
2271
- return (0, import_langchain18.tool)(
3873
+ return (0, import_langchain25.tool)(
2272
3874
  async (input, exe_config) => {
2273
3875
  try {
2274
3876
  const runConfig = exe_config.configurable?.runConfig;
@@ -2286,21 +3888,21 @@ var createBrowserGoForwardTool = ({ isolatedLevel }) => {
2286
3888
  {
2287
3889
  name: "browser_go_forward",
2288
3890
  description: BROWSER_GO_FORWARD_DESCRIPTION,
2289
- schema: import_zod21.default.object({})
3891
+ schema: import_zod28.default.object({})
2290
3892
  }
2291
3893
  );
2292
3894
  };
2293
3895
 
2294
3896
  // src/tool_lattice/browser/browser_new_tab.ts
2295
- var import_zod22 = __toESM(require("zod"));
2296
- var import_langchain19 = require("langchain");
3897
+ var import_zod29 = __toESM(require("zod"));
3898
+ var import_langchain26 = require("langchain");
2297
3899
  var BROWSER_NEW_TAB_DESCRIPTION = `Open a new tab.
2298
3900
 
2299
3901
  Args:
2300
3902
  url (str): URL to open in the new tab
2301
3903
  `;
2302
3904
  var createBrowserNewTabTool = ({ isolatedLevel }) => {
2303
- return (0, import_langchain19.tool)(
3905
+ return (0, import_langchain26.tool)(
2304
3906
  async (input, exe_config) => {
2305
3907
  try {
2306
3908
  const runConfig = exe_config.configurable?.runConfig;
@@ -2320,23 +3922,23 @@ var createBrowserNewTabTool = ({ isolatedLevel }) => {
2320
3922
  {
2321
3923
  name: "browser_new_tab",
2322
3924
  description: BROWSER_NEW_TAB_DESCRIPTION,
2323
- schema: import_zod22.default.object({
2324
- url: import_zod22.default.string().describe("URL to open in the new tab")
3925
+ schema: import_zod29.default.object({
3926
+ url: import_zod29.default.string().describe("URL to open in the new tab")
2325
3927
  })
2326
3928
  }
2327
3929
  );
2328
3930
  };
2329
3931
 
2330
3932
  // src/tool_lattice/browser/browser_tab_list.ts
2331
- var import_zod23 = __toESM(require("zod"));
2332
- var import_langchain20 = require("langchain");
3933
+ var import_zod30 = __toESM(require("zod"));
3934
+ var import_langchain27 = require("langchain");
2333
3935
  var BROWSER_TAB_LIST_DESCRIPTION = `Get the list of tabs.
2334
3936
 
2335
3937
  Args:
2336
3938
  None
2337
3939
  `;
2338
3940
  var createBrowserTabListTool = ({ isolatedLevel }) => {
2339
- return (0, import_langchain20.tool)(
3941
+ return (0, import_langchain27.tool)(
2340
3942
  async (input, exe_config) => {
2341
3943
  try {
2342
3944
  const runConfig = exe_config.configurable?.runConfig;
@@ -2354,21 +3956,21 @@ var createBrowserTabListTool = ({ isolatedLevel }) => {
2354
3956
  {
2355
3957
  name: "browser_tab_list",
2356
3958
  description: BROWSER_TAB_LIST_DESCRIPTION,
2357
- schema: import_zod23.default.object({})
3959
+ schema: import_zod30.default.object({})
2358
3960
  }
2359
3961
  );
2360
3962
  };
2361
3963
 
2362
3964
  // src/tool_lattice/browser/browser_switch_tab.ts
2363
- var import_zod24 = __toESM(require("zod"));
2364
- var import_langchain21 = require("langchain");
3965
+ var import_zod31 = __toESM(require("zod"));
3966
+ var import_langchain28 = require("langchain");
2365
3967
  var BROWSER_SWITCH_TAB_DESCRIPTION = `Switch to a specific tab.
2366
3968
 
2367
3969
  Args:
2368
3970
  index (int): Tab index to switch to
2369
3971
  `;
2370
3972
  var createBrowserSwitchTabTool = ({ isolatedLevel }) => {
2371
- return (0, import_langchain21.tool)(
3973
+ return (0, import_langchain28.tool)(
2372
3974
  async (input, exe_config) => {
2373
3975
  try {
2374
3976
  const runConfig = exe_config.configurable?.runConfig;
@@ -2388,23 +3990,23 @@ var createBrowserSwitchTabTool = ({ isolatedLevel }) => {
2388
3990
  {
2389
3991
  name: "browser_switch_tab",
2390
3992
  description: BROWSER_SWITCH_TAB_DESCRIPTION,
2391
- schema: import_zod24.default.object({
2392
- index: import_zod24.default.number().describe("Tab index to switch to")
3993
+ schema: import_zod31.default.object({
3994
+ index: import_zod31.default.number().describe("Tab index to switch to")
2393
3995
  })
2394
3996
  }
2395
3997
  );
2396
3998
  };
2397
3999
 
2398
4000
  // src/tool_lattice/browser/browser_close_tab.ts
2399
- var import_zod25 = __toESM(require("zod"));
2400
- var import_langchain22 = require("langchain");
4001
+ var import_zod32 = __toESM(require("zod"));
4002
+ var import_langchain29 = require("langchain");
2401
4003
  var BROWSER_CLOSE_TAB_DESCRIPTION = `Close the current tab.
2402
4004
 
2403
4005
  Args:
2404
4006
  None
2405
4007
  `;
2406
4008
  var createBrowserCloseTabTool = ({ isolatedLevel }) => {
2407
- return (0, import_langchain22.tool)(
4009
+ return (0, import_langchain29.tool)(
2408
4010
  async (input, exe_config) => {
2409
4011
  try {
2410
4012
  const runConfig = exe_config.configurable?.runConfig;
@@ -2422,21 +4024,21 @@ var createBrowserCloseTabTool = ({ isolatedLevel }) => {
2422
4024
  {
2423
4025
  name: "browser_close_tab",
2424
4026
  description: BROWSER_CLOSE_TAB_DESCRIPTION,
2425
- schema: import_zod25.default.object({})
4027
+ schema: import_zod32.default.object({})
2426
4028
  }
2427
4029
  );
2428
4030
  };
2429
4031
 
2430
4032
  // src/tool_lattice/browser/browser_close.ts
2431
- var import_zod26 = __toESM(require("zod"));
2432
- var import_langchain23 = require("langchain");
4033
+ var import_zod33 = __toESM(require("zod"));
4034
+ var import_langchain30 = require("langchain");
2433
4035
  var BROWSER_CLOSE_DESCRIPTION = `Close the browser when the task is done and the browser is not needed anymore.
2434
4036
 
2435
4037
  Args:
2436
4038
  None
2437
4039
  `;
2438
4040
  var createBrowserCloseTool = ({ isolatedLevel }) => {
2439
- return (0, import_langchain23.tool)(
4041
+ return (0, import_langchain30.tool)(
2440
4042
  async (input, exe_config) => {
2441
4043
  try {
2442
4044
  const runConfig = exe_config.configurable?.runConfig;
@@ -2454,21 +4056,21 @@ var createBrowserCloseTool = ({ isolatedLevel }) => {
2454
4056
  {
2455
4057
  name: "browser_close",
2456
4058
  description: BROWSER_CLOSE_DESCRIPTION,
2457
- schema: import_zod26.default.object({})
4059
+ schema: import_zod33.default.object({})
2458
4060
  }
2459
4061
  );
2460
4062
  };
2461
4063
 
2462
4064
  // src/tool_lattice/browser/browser_press_key.ts
2463
- var import_zod27 = __toESM(require("zod"));
2464
- var import_langchain24 = require("langchain");
4065
+ var import_zod34 = __toESM(require("zod"));
4066
+ var import_langchain31 = require("langchain");
2465
4067
  var BROWSER_PRESS_KEY_DESCRIPTION = `Press a key on the keyboard.
2466
4068
 
2467
4069
  Args:
2468
4070
  key (str): Name of the key to press or a character to generate, such as Enter, Tab, Escape, Backspace, Delete, Insert, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, PageUp, PageDown, Home, End, ShiftLeft, ShiftRight, ControlLeft, ControlRight, AltLeft, AltRight, MetaLeft, MetaRight, CapsLock, PrintScreen, ScrollLock, Pause, ContextMenu
2469
4071
  `;
2470
4072
  var createBrowserPressKeyTool = ({ isolatedLevel }) => {
2471
- return (0, import_langchain24.tool)(
4073
+ return (0, import_langchain31.tool)(
2472
4074
  async (input, exe_config) => {
2473
4075
  try {
2474
4076
  const runConfig = exe_config.configurable?.runConfig;
@@ -2488,8 +4090,8 @@ var createBrowserPressKeyTool = ({ isolatedLevel }) => {
2488
4090
  {
2489
4091
  name: "browser_press_key",
2490
4092
  description: BROWSER_PRESS_KEY_DESCRIPTION,
2491
- schema: import_zod27.default.object({
2492
- key: import_zod27.default.enum([
4093
+ schema: import_zod34.default.object({
4094
+ key: import_zod34.default.enum([
2493
4095
  "Enter",
2494
4096
  "Tab",
2495
4097
  "Escape",
@@ -2536,15 +4138,15 @@ var createBrowserPressKeyTool = ({ isolatedLevel }) => {
2536
4138
  };
2537
4139
 
2538
4140
  // src/tool_lattice/browser/browser_read_links.ts
2539
- var import_zod28 = __toESM(require("zod"));
2540
- var import_langchain25 = require("langchain");
4141
+ var import_zod35 = __toESM(require("zod"));
4142
+ var import_langchain32 = require("langchain");
2541
4143
  var BROWSER_READ_LINKS_DESCRIPTION = `Get all links on the current page.
2542
4144
 
2543
4145
  Args:
2544
4146
  None
2545
4147
  `;
2546
4148
  var createBrowserReadLinksTool = ({ isolatedLevel }) => {
2547
- return (0, import_langchain25.tool)(
4149
+ return (0, import_langchain32.tool)(
2548
4150
  async (input, exe_config) => {
2549
4151
  try {
2550
4152
  const runConfig = exe_config.configurable?.runConfig;
@@ -2562,21 +4164,21 @@ var createBrowserReadLinksTool = ({ isolatedLevel }) => {
2562
4164
  {
2563
4165
  name: "browser_read_links",
2564
4166
  description: BROWSER_READ_LINKS_DESCRIPTION,
2565
- schema: import_zod28.default.object({})
4167
+ schema: import_zod35.default.object({})
2566
4168
  }
2567
4169
  );
2568
4170
  };
2569
4171
 
2570
4172
  // src/tool_lattice/browser/browser_get_clickable_elements.ts
2571
- var import_zod29 = __toESM(require("zod"));
2572
- var import_langchain26 = require("langchain");
4173
+ var import_zod36 = __toESM(require("zod"));
4174
+ var import_langchain33 = require("langchain");
2573
4175
  var BROWSER_GET_CLICKABLE_ELEMENTS_DESCRIPTION = `Get the clickable or hoverable or selectable elements on the current page, don't call this tool multiple times.
2574
4176
 
2575
4177
  Args:
2576
4178
  None
2577
4179
  `;
2578
4180
  var createBrowserGetClickableElementsTool = ({ isolatedLevel }) => {
2579
- return (0, import_langchain26.tool)(
4181
+ return (0, import_langchain33.tool)(
2580
4182
  async (input, exe_config) => {
2581
4183
  try {
2582
4184
  const runConfig = exe_config.configurable?.runConfig;
@@ -2594,21 +4196,21 @@ var createBrowserGetClickableElementsTool = ({ isolatedLevel }) => {
2594
4196
  {
2595
4197
  name: "browser_get_clickable_elements",
2596
4198
  description: BROWSER_GET_CLICKABLE_ELEMENTS_DESCRIPTION,
2597
- schema: import_zod29.default.object({})
4199
+ schema: import_zod36.default.object({})
2598
4200
  }
2599
4201
  );
2600
4202
  };
2601
4203
 
2602
4204
  // src/tool_lattice/browser/browser_get_download_list.ts
2603
- var import_zod30 = __toESM(require("zod"));
2604
- var import_langchain27 = require("langchain");
4205
+ var import_zod37 = __toESM(require("zod"));
4206
+ var import_langchain34 = require("langchain");
2605
4207
  var BROWSER_GET_DOWNLOAD_LIST_DESCRIPTION = `Get the list of downloaded files.
2606
4208
 
2607
4209
  Args:
2608
4210
  None
2609
4211
  `;
2610
4212
  var createBrowserGetDownloadListTool = ({ isolatedLevel }) => {
2611
- return (0, import_langchain27.tool)(
4213
+ return (0, import_langchain34.tool)(
2612
4214
  async (input, exe_config) => {
2613
4215
  try {
2614
4216
  const runConfig = exe_config.configurable?.runConfig;
@@ -2626,14 +4228,14 @@ var createBrowserGetDownloadListTool = ({ isolatedLevel }) => {
2626
4228
  {
2627
4229
  name: "browser_get_download_list",
2628
4230
  description: BROWSER_GET_DOWNLOAD_LIST_DESCRIPTION,
2629
- schema: import_zod30.default.object({})
4231
+ schema: import_zod37.default.object({})
2630
4232
  }
2631
4233
  );
2632
4234
  };
2633
4235
 
2634
4236
  // src/tool_lattice/browser/get_info.ts
2635
- var import_zod31 = __toESM(require("zod"));
2636
- var import_langchain28 = require("langchain");
4237
+ var import_zod38 = __toESM(require("zod"));
4238
+ var import_langchain35 = require("langchain");
2637
4239
  var BROWSER_GET_INFO_DESCRIPTION = `Get information about browser, like CDP URL, viewport size, etc.
2638
4240
 
2639
4241
  Args:
@@ -2642,7 +4244,7 @@ Args:
2642
4244
  Returns:
2643
4245
  Dict containing browser information including CDP URL, viewport dimensions, and other browser metadata.`;
2644
4246
  var createBrowserGetInfoTool = ({ isolatedLevel }) => {
2645
- return (0, import_langchain28.tool)(
4247
+ return (0, import_langchain35.tool)(
2646
4248
  async (input, exe_config) => {
2647
4249
  try {
2648
4250
  const runConfig = exe_config.configurable?.runConfig;
@@ -2660,7 +4262,7 @@ var createBrowserGetInfoTool = ({ isolatedLevel }) => {
2660
4262
  {
2661
4263
  name: "browser_get_info",
2662
4264
  description: BROWSER_GET_INFO_DESCRIPTION,
2663
- schema: import_zod31.default.object({})
4265
+ schema: import_zod38.default.object({})
2664
4266
  }
2665
4267
  );
2666
4268
  };
@@ -2749,14 +4351,14 @@ var memory = new import_langgraph2.MemorySaver();
2749
4351
  registerCheckpointSaver("default", memory);
2750
4352
 
2751
4353
  // src/agent_lattice/builders/state.ts
2752
- var import_zod32 = require("@langchain/langgraph/zod");
4354
+ var import_zod39 = require("@langchain/langgraph/zod");
2753
4355
  var import_langgraph3 = require("@langchain/langgraph");
2754
4356
  var createReactAgentSchema = (schema) => {
2755
4357
  return schema ? import_langgraph3.MessagesZodState.extend(schema.shape) : void 0;
2756
4358
  };
2757
4359
 
2758
4360
  // src/agent_lattice/builders/ReActAgentGraphBuilder.ts
2759
- var import_langchain36 = require("langchain");
4361
+ var import_langchain45 = require("langchain");
2760
4362
 
2761
4363
  // src/deep_agent_new/backends/sandboxFiles.ts
2762
4364
  var import_sandbox2 = require("@agent-infra/sandbox");
@@ -2799,8 +4401,8 @@ var SandboxFilesystem = class {
2799
4401
  */
2800
4402
  toVirtualPath(realPath) {
2801
4403
  const rootPath = path2.join(this.homeDir, this.workingDirectory);
2802
- const relative3 = path2.relative(rootPath, realPath);
2803
- const normalized = relative3.split(path2.sep).join("/");
4404
+ const relative4 = path2.relative(rootPath, realPath);
4405
+ const normalized = relative4.split(path2.sep).join("/");
2804
4406
  return "/" + normalized;
2805
4407
  }
2806
4408
  /**
@@ -3035,18 +4637,18 @@ var SandboxFilesystem = class {
3035
4637
  };
3036
4638
 
3037
4639
  // src/middlewares/codeEvalMiddleware.ts
3038
- var import_langchain29 = require("langchain");
4640
+ var import_langchain36 = require("langchain");
3039
4641
  function createCodeEvalMiddleware(params = { isolatedLevel: "global" }) {
3040
4642
  const codeEvalTool = createCodeEvalTool({ isolatedLevel: params.isolatedLevel });
3041
4643
  const codeExecuteFileTool = createCodeExecuteFileTool({ isolatedLevel: params.isolatedLevel });
3042
- return (0, import_langchain29.createMiddleware)({
4644
+ return (0, import_langchain36.createMiddleware)({
3043
4645
  name: "codeEvalMiddleware",
3044
4646
  tools: [codeEvalTool, codeExecuteFileTool, getToolClient("convert_to_markdown")]
3045
4647
  });
3046
4648
  }
3047
4649
 
3048
4650
  // src/middlewares/browserMiddleware.ts
3049
- var import_langchain30 = require("langchain");
4651
+ var import_langchain37 = require("langchain");
3050
4652
  function createBrowserMiddleware(params = { isolatedLevel: "global" }) {
3051
4653
  const isolatedLevel = params.isolatedLevel || "global";
3052
4654
  const tools = [
@@ -3073,18 +4675,18 @@ function createBrowserMiddleware(params = { isolatedLevel: "global" }) {
3073
4675
  createBrowserGetDownloadListTool({ isolatedLevel }),
3074
4676
  createBrowserGetInfoTool({ isolatedLevel })
3075
4677
  ];
3076
- return (0, import_langchain30.createMiddleware)({
4678
+ return (0, import_langchain37.createMiddleware)({
3077
4679
  name: "browserMiddleware",
3078
4680
  tools
3079
4681
  });
3080
4682
  }
3081
4683
 
3082
4684
  // src/middlewares/sqlMiddleware.ts
3083
- var import_langchain31 = require("langchain");
4685
+ var import_langchain38 = require("langchain");
3084
4686
  function createSqlMiddleware(params) {
3085
4687
  const { databaseKeys, databaseDescriptions } = params;
3086
4688
  if (!databaseKeys || databaseKeys.length === 0) {
3087
- return (0, import_langchain31.createMiddleware)({
4689
+ return (0, import_langchain38.createMiddleware)({
3088
4690
  name: "sqlMiddleware",
3089
4691
  tools: []
3090
4692
  });
@@ -3093,7 +4695,7 @@ function createSqlMiddleware(params) {
3093
4695
  databaseKeys,
3094
4696
  databaseDescriptions
3095
4697
  };
3096
- return (0, import_langchain31.createMiddleware)({
4698
+ return (0, import_langchain38.createMiddleware)({
3097
4699
  name: "sqlMiddleware",
3098
4700
  tools: [
3099
4701
  createListTablesSqlTool(toolParams),
@@ -3105,7 +4707,7 @@ function createSqlMiddleware(params) {
3105
4707
  }
3106
4708
 
3107
4709
  // src/middlewares/skillMiddleware.ts
3108
- var import_langchain34 = require("langchain");
4710
+ var import_langchain42 = require("langchain");
3109
4711
 
3110
4712
  // src/store_lattice/InMemoryThreadStore.ts
3111
4713
  var InMemoryThreadStore = class {
@@ -3753,7 +5355,58 @@ ${body}` : `${frontmatter}
3753
5355
  subSkills.push(subSkill);
3754
5356
  }
3755
5357
  }
3756
- return subSkills;
5358
+ return subSkills;
5359
+ }
5360
+ /**
5361
+ * List all resources in a skill's resources directory
5362
+ * @param skillName The skill name
5363
+ * @returns Array of resource paths relative to resources/ directory
5364
+ */
5365
+ async listSkillResources(skillName) {
5366
+ const skillDir = this.getSkillDirectoryPath(skillName);
5367
+ const resourcesDir = path3.join(skillDir, "resources");
5368
+ try {
5369
+ const entries = await fs.readdir(resourcesDir, { withFileTypes: true, recursive: true });
5370
+ const resources = [];
5371
+ for (const entry of entries) {
5372
+ if (!entry.isDirectory()) {
5373
+ const fullPath = path3.join(entry.path, entry.name);
5374
+ const relativePath = path3.relative(resourcesDir, fullPath);
5375
+ resources.push(relativePath.replace(/\\/g, "/"));
5376
+ }
5377
+ }
5378
+ return resources.sort();
5379
+ } catch (error) {
5380
+ if (error.code === "ENOENT") {
5381
+ return [];
5382
+ }
5383
+ throw error;
5384
+ }
5385
+ }
5386
+ /**
5387
+ * Load a specific resource from a skill's resources directory
5388
+ * @param skillName The skill name
5389
+ * @param resourcePath Path to the resource relative to resources/ directory
5390
+ * @returns The resource content as string
5391
+ */
5392
+ async loadSkillResource(skillName, resourcePath) {
5393
+ const skillDir = this.getSkillDirectoryPath(skillName);
5394
+ const resourcesDir = path3.join(skillDir, "resources");
5395
+ const fullPath = path3.join(resourcesDir, resourcePath);
5396
+ const resolvedPath = path3.resolve(fullPath);
5397
+ const resolvedResourcesDir = path3.resolve(resourcesDir);
5398
+ if (!resolvedPath.startsWith(resolvedResourcesDir)) {
5399
+ throw new Error(`Invalid resource path: ${resourcePath}`);
5400
+ }
5401
+ try {
5402
+ const content = await fs.readFile(fullPath, "utf-8");
5403
+ return content;
5404
+ } catch (error) {
5405
+ if (error.code === "ENOENT") {
5406
+ return null;
5407
+ }
5408
+ throw error;
5409
+ }
3757
5410
  }
3758
5411
  };
3759
5412
 
@@ -4009,6 +5662,291 @@ var InMemoryDatabaseConfigStore = class {
4009
5662
  }
4010
5663
  };
4011
5664
 
5665
+ // src/store_lattice/InMemoryMetricsServerConfigStore.ts
5666
+ var InMemoryMetricsServerConfigStore = class {
5667
+ constructor() {
5668
+ this.configs = /* @__PURE__ */ new Map();
5669
+ }
5670
+ /**
5671
+ * Get composite key for storage
5672
+ */
5673
+ getKey(tenantId, id) {
5674
+ return `${tenantId}:${id}`;
5675
+ }
5676
+ /**
5677
+ * Get all metrics server configurations for a tenant
5678
+ */
5679
+ async getAllConfigs(tenantId) {
5680
+ return Array.from(this.configs.values()).filter(
5681
+ (config) => config.tenantId === tenantId
5682
+ );
5683
+ }
5684
+ /**
5685
+ * Get all metrics server configurations across all tenants
5686
+ */
5687
+ async getAllConfigsWithoutTenant() {
5688
+ return Array.from(this.configs.values());
5689
+ }
5690
+ /**
5691
+ * Get metrics server configuration by ID
5692
+ */
5693
+ async getConfigById(tenantId, id) {
5694
+ const key = this.getKey(tenantId, id);
5695
+ return this.configs.get(key) || null;
5696
+ }
5697
+ /**
5698
+ * Get metrics server configuration by business key
5699
+ */
5700
+ async getConfigByKey(tenantId, key) {
5701
+ const configs = await this.getAllConfigs(tenantId);
5702
+ return configs.find((config) => config.key === key) || null;
5703
+ }
5704
+ /**
5705
+ * Create a new metrics server configuration
5706
+ */
5707
+ async createConfig(tenantId, id, data) {
5708
+ const now = /* @__PURE__ */ new Date();
5709
+ const entry = {
5710
+ id,
5711
+ tenantId,
5712
+ key: data.key,
5713
+ config: data.config,
5714
+ name: data.name,
5715
+ description: data.description,
5716
+ createdAt: now,
5717
+ updatedAt: now
5718
+ };
5719
+ const storageKey = this.getKey(tenantId, id);
5720
+ this.configs.set(storageKey, entry);
5721
+ return entry;
5722
+ }
5723
+ /**
5724
+ * Update an existing metrics server configuration
5725
+ */
5726
+ async updateConfig(tenantId, id, updates) {
5727
+ const key = this.getKey(tenantId, id);
5728
+ const existing = this.configs.get(key);
5729
+ if (!existing) {
5730
+ return null;
5731
+ }
5732
+ const updated = {
5733
+ ...existing,
5734
+ ...updates,
5735
+ config: updates.config ? { ...existing.config, ...updates.config } : existing.config,
5736
+ key: updates.key || existing.key,
5737
+ name: updates.name !== void 0 ? updates.name : existing.name,
5738
+ description: updates.description !== void 0 ? updates.description : existing.description,
5739
+ updatedAt: /* @__PURE__ */ new Date()
5740
+ };
5741
+ this.configs.set(key, updated);
5742
+ return updated;
5743
+ }
5744
+ /**
5745
+ * Delete a metrics server configuration by ID
5746
+ */
5747
+ async deleteConfig(tenantId, id) {
5748
+ const key = this.getKey(tenantId, id);
5749
+ return this.configs.delete(key);
5750
+ }
5751
+ /**
5752
+ * Check if configuration exists
5753
+ */
5754
+ async hasConfig(tenantId, id) {
5755
+ const key = this.getKey(tenantId, id);
5756
+ return this.configs.has(key);
5757
+ }
5758
+ /**
5759
+ * Clear all configurations (useful for testing)
5760
+ */
5761
+ clear() {
5762
+ this.configs.clear();
5763
+ }
5764
+ /**
5765
+ * Clear configurations for a specific tenant
5766
+ */
5767
+ clearByTenant(tenantId) {
5768
+ for (const key of this.configs.keys()) {
5769
+ if (key.startsWith(`${tenantId}:`)) {
5770
+ this.configs.delete(key);
5771
+ }
5772
+ }
5773
+ }
5774
+ };
5775
+
5776
+ // src/store_lattice/InMemoryUserStore.ts
5777
+ var InMemoryUserStore = class {
5778
+ constructor() {
5779
+ this.users = /* @__PURE__ */ new Map();
5780
+ }
5781
+ async getAllUsers() {
5782
+ return Array.from(this.users.values());
5783
+ }
5784
+ async getUserById(id) {
5785
+ return this.users.get(id) || null;
5786
+ }
5787
+ async getUserByEmail(email) {
5788
+ for (const user of this.users.values()) {
5789
+ if (user.email === email) {
5790
+ return user;
5791
+ }
5792
+ }
5793
+ return null;
5794
+ }
5795
+ async createUser(id, data) {
5796
+ const now = /* @__PURE__ */ new Date();
5797
+ const user = {
5798
+ id,
5799
+ email: data.email,
5800
+ name: data.name,
5801
+ status: data.status || "pending",
5802
+ metadata: data.metadata ?? {},
5803
+ createdAt: now,
5804
+ updatedAt: now
5805
+ };
5806
+ this.users.set(id, user);
5807
+ return user;
5808
+ }
5809
+ async updateUser(id, updates) {
5810
+ const existing = this.users.get(id);
5811
+ if (!existing) {
5812
+ return null;
5813
+ }
5814
+ const updated = {
5815
+ ...existing,
5816
+ ...updates,
5817
+ metadata: updates.metadata ?? existing.metadata,
5818
+ updatedAt: /* @__PURE__ */ new Date()
5819
+ };
5820
+ this.users.set(id, updated);
5821
+ return updated;
5822
+ }
5823
+ async deleteUser(id) {
5824
+ return this.users.delete(id);
5825
+ }
5826
+ clear() {
5827
+ this.users.clear();
5828
+ }
5829
+ };
5830
+
5831
+ // src/store_lattice/InMemoryTenantStore.ts
5832
+ var InMemoryTenantStore = class {
5833
+ constructor() {
5834
+ this.tenants = /* @__PURE__ */ new Map();
5835
+ this.initDefaultData();
5836
+ }
5837
+ initDefaultData() {
5838
+ const defaultTenant = {
5839
+ id: "default",
5840
+ name: "Default Tenant",
5841
+ description: "Default tenant for single-tenant setups",
5842
+ status: "active",
5843
+ metadata: {},
5844
+ createdAt: /* @__PURE__ */ new Date(),
5845
+ updatedAt: /* @__PURE__ */ new Date()
5846
+ };
5847
+ this.tenants.set("default", defaultTenant);
5848
+ }
5849
+ async getAllTenants() {
5850
+ return Array.from(this.tenants.values());
5851
+ }
5852
+ async getTenantById(id) {
5853
+ return this.tenants.get(id) || null;
5854
+ }
5855
+ async createTenant(id, data) {
5856
+ const now = /* @__PURE__ */ new Date();
5857
+ const tenant = {
5858
+ id,
5859
+ name: data.name,
5860
+ description: data.description,
5861
+ status: data.status || "active",
5862
+ metadata: data.metadata || {},
5863
+ createdAt: now,
5864
+ updatedAt: now
5865
+ };
5866
+ this.tenants.set(id, tenant);
5867
+ return tenant;
5868
+ }
5869
+ async updateTenant(id, updates) {
5870
+ const existing = this.tenants.get(id);
5871
+ if (!existing) {
5872
+ return null;
5873
+ }
5874
+ const updated = {
5875
+ ...existing,
5876
+ ...updates,
5877
+ updatedAt: /* @__PURE__ */ new Date()
5878
+ };
5879
+ this.tenants.set(id, updated);
5880
+ return updated;
5881
+ }
5882
+ async deleteTenant(id) {
5883
+ return this.tenants.delete(id);
5884
+ }
5885
+ clear() {
5886
+ this.tenants.clear();
5887
+ this.initDefaultData();
5888
+ }
5889
+ };
5890
+
5891
+ // src/store_lattice/InMemoryUserTenantLinkStore.ts
5892
+ var InMemoryUserTenantLinkStore = class {
5893
+ constructor() {
5894
+ this.links = /* @__PURE__ */ new Map();
5895
+ }
5896
+ getKey(userId, tenantId) {
5897
+ return `${userId}:${tenantId}`;
5898
+ }
5899
+ async getTenantsByUser(userId) {
5900
+ return Array.from(this.links.values()).filter(
5901
+ (link) => link.userId === userId
5902
+ );
5903
+ }
5904
+ async getUsersByTenant(tenantId) {
5905
+ return Array.from(this.links.values()).filter(
5906
+ (link) => link.tenantId === tenantId
5907
+ );
5908
+ }
5909
+ async getLink(userId, tenantId) {
5910
+ const key = this.getKey(userId, tenantId);
5911
+ return this.links.get(key) || null;
5912
+ }
5913
+ async createLink(data) {
5914
+ const link = {
5915
+ userId: data.userId,
5916
+ tenantId: data.tenantId,
5917
+ role: data.role || "member",
5918
+ joinedAt: /* @__PURE__ */ new Date(),
5919
+ metadata: data.metadata ?? {}
5920
+ };
5921
+ const key = this.getKey(data.userId, data.tenantId);
5922
+ this.links.set(key, link);
5923
+ return link;
5924
+ }
5925
+ async updateLink(userId, tenantId, updates) {
5926
+ const key = this.getKey(userId, tenantId);
5927
+ const existing = this.links.get(key);
5928
+ if (!existing) return null;
5929
+ const updated = {
5930
+ ...existing,
5931
+ ...updates,
5932
+ metadata: updates.metadata ?? existing.metadata
5933
+ };
5934
+ this.links.set(key, updated);
5935
+ return updated;
5936
+ }
5937
+ async deleteLink(userId, tenantId) {
5938
+ const key = this.getKey(userId, tenantId);
5939
+ return this.links.delete(key);
5940
+ }
5941
+ async hasLink(userId, tenantId) {
5942
+ const key = this.getKey(userId, tenantId);
5943
+ return this.links.has(key);
5944
+ }
5945
+ clear() {
5946
+ this.links.clear();
5947
+ }
5948
+ };
5949
+
4012
5950
  // src/store_lattice/StoreLatticeManager.ts
4013
5951
  var StoreLatticeManager = class _StoreLatticeManager extends BaseLatticeManager {
4014
5952
  /**
@@ -4139,6 +6077,7 @@ var defaultSkillStore = new FileSystemSkillStore();
4139
6077
  var defaultWorkspaceStore = new InMemoryWorkspaceStore();
4140
6078
  var defaultProjectStore = new InMemoryProjectStore();
4141
6079
  var defaultDatabaseConfigStore = new InMemoryDatabaseConfigStore();
6080
+ var defaultMetricsServerConfigStore = new InMemoryMetricsServerConfigStore();
4142
6081
  storeLatticeManager.registerLattice("default", "thread", defaultThreadStore);
4143
6082
  storeLatticeManager.registerLattice(
4144
6083
  "default",
@@ -4149,13 +6088,20 @@ storeLatticeManager.registerLattice("default", "skill", defaultSkillStore);
4149
6088
  storeLatticeManager.registerLattice("default", "workspace", defaultWorkspaceStore);
4150
6089
  storeLatticeManager.registerLattice("default", "project", defaultProjectStore);
4151
6090
  storeLatticeManager.registerLattice("default", "database", defaultDatabaseConfigStore);
6091
+ storeLatticeManager.registerLattice("default", "metrics", defaultMetricsServerConfigStore);
6092
+ var defaultUserStore = new InMemoryUserStore();
6093
+ var defaultTenantStore = new InMemoryTenantStore();
6094
+ var defaultUserTenantLinkStore = new InMemoryUserTenantLinkStore();
6095
+ storeLatticeManager.registerLattice("default", "user", defaultUserStore);
6096
+ storeLatticeManager.registerLattice("default", "tenant", defaultTenantStore);
6097
+ storeLatticeManager.registerLattice("default", "userTenantLink", defaultUserTenantLinkStore);
4152
6098
 
4153
6099
  // src/tool_lattice/skill/load_skills.ts
4154
- var import_zod33 = __toESM(require("zod"));
4155
- var import_langchain32 = require("langchain");
6100
+ var import_zod40 = __toESM(require("zod"));
6101
+ var import_langchain39 = require("langchain");
4156
6102
  var LOAD_SKILLS_DESCRIPTION = `Load all available skills and return their metadata (name, description, license, compatibility, metadata, and subSkills) without the content. This tool returns skill information including hierarchical relationships (subSkills). Use this to discover what skills are available and their structure.`;
4157
6103
  var createLoadSkillsTool = ({ skills } = {}) => {
4158
- return (0, import_langchain32.tool)(
6104
+ return (0, import_langchain39.tool)(
4159
6105
  async (_input, _exe_config) => {
4160
6106
  try {
4161
6107
  const storeLattice = getStoreLattice("default", "skill");
@@ -4179,17 +6125,17 @@ var createLoadSkillsTool = ({ skills } = {}) => {
4179
6125
  {
4180
6126
  name: "load_skills",
4181
6127
  description: LOAD_SKILLS_DESCRIPTION,
4182
- schema: import_zod33.default.object({})
6128
+ schema: import_zod40.default.object({})
4183
6129
  }
4184
6130
  );
4185
6131
  };
4186
6132
 
4187
6133
  // src/tool_lattice/skill/load_skill_content.ts
4188
- var import_zod34 = __toESM(require("zod"));
4189
- var import_langchain33 = require("langchain");
4190
- var LOAD_SKILL_CONTENT_DESCRIPTION = `Load a specific skill's content by name and return its full content including markdown body. This tool returns the complete skill content including frontmatter and markdown body. Use this tool to get the complete skill content for a skill that you want to use.`;
6134
+ var import_zod41 = __toESM(require("zod"));
6135
+ var import_langchain40 = require("langchain");
6136
+ var LOAD_SKILL_CONTENT_DESCRIPTION = `Load a specific skill's content by name and return its full content including markdown body. This tool returns the complete skill content including frontmatter and markdown body. If the skill has resources, they will be listed at the end of the content with instructions on how to access them. Use this tool to get the complete skill content for a skill that you want to use.`;
4191
6137
  var createLoadSkillContentTool = () => {
4192
- return (0, import_langchain33.tool)(
6138
+ return (0, import_langchain40.tool)(
4193
6139
  async (input, _exe_config) => {
4194
6140
  try {
4195
6141
  const storeLattice = getStoreLattice("default", "skill");
@@ -4223,8 +6169,23 @@ var createLoadSkillContentTool = () => {
4223
6169
  }
4224
6170
  frontmatter.push("---");
4225
6171
  const content = skill.content || "";
4226
- return `${frontmatter.join("\n")}
6172
+ let result = `${frontmatter.join("\n")}
4227
6173
  ${content}`;
6174
+ const fsStore = skillStore;
6175
+ if (fsStore.listSkillResources) {
6176
+ try {
6177
+ const resources = await fsStore.listSkillResources(input.skill_name);
6178
+ if (resources.length > 0) {
6179
+ result += "\n\n---\n\n**Resources** (use `load_skill_resource` tool to access):\n";
6180
+ resources.forEach((resource) => {
6181
+ result += `- ${resource}
6182
+ `;
6183
+ });
6184
+ }
6185
+ } catch {
6186
+ }
6187
+ }
6188
+ return result;
4228
6189
  } catch (error) {
4229
6190
  return `Error loading skill content: ${error instanceof Error ? error.message : String(error)}`;
4230
6191
  }
@@ -4232,16 +6193,55 @@ ${content}`;
4232
6193
  {
4233
6194
  name: "load_skill_content",
4234
6195
  description: LOAD_SKILL_CONTENT_DESCRIPTION,
4235
- schema: import_zod34.default.object({
4236
- skill_name: import_zod34.default.string().describe("The name of the skill to load")
6196
+ schema: import_zod41.default.object({
6197
+ skill_name: import_zod41.default.string().describe("The name of the skill to load")
6198
+ })
6199
+ }
6200
+ );
6201
+ };
6202
+
6203
+ // src/tool_lattice/skill/load_skill_resource.ts
6204
+ var import_zod42 = __toESM(require("zod"));
6205
+ var import_langchain41 = require("langchain");
6206
+ var LOAD_SKILL_RESOURCE_DESCRIPTION = `Load a specific resource file from a skill's resources directory. Use this tool when you need to access template files, example data, or other resources bundled with a skill. The resource paths are listed in the skill content when using the load_skill_content tool.`;
6207
+ var createLoadSkillResourceTool = () => {
6208
+ return (0, import_langchain41.tool)(
6209
+ async (input, _exe_config) => {
6210
+ try {
6211
+ const storeLattice = getStoreLattice("default", "skill");
6212
+ const skillStore = storeLattice.store;
6213
+ const fsStore = skillStore;
6214
+ if (!fsStore.loadSkillResource) {
6215
+ return `Error: This skill store does not support resource loading.`;
6216
+ }
6217
+ const content = await fsStore.loadSkillResource(input.skill_name, input.resource_path);
6218
+ if (!content) {
6219
+ return `Resource "${input.resource_path}" not found for skill "${input.skill_name}".`;
6220
+ }
6221
+ return content;
6222
+ } catch (error) {
6223
+ return `Error loading skill resource: ${error instanceof Error ? error.message : String(error)}`;
6224
+ }
6225
+ },
6226
+ {
6227
+ name: "load_skill_resource",
6228
+ description: LOAD_SKILL_RESOURCE_DESCRIPTION,
6229
+ schema: import_zod42.default.object({
6230
+ skill_name: import_zod42.default.string().describe("The name of the skill containing the resource"),
6231
+ resource_path: import_zod42.default.string().describe("The path to the resource relative to the skill's resources/ directory")
4237
6232
  })
4238
6233
  }
4239
6234
  );
4240
6235
  };
4241
6236
 
4242
6237
  // src/middlewares/skillMiddleware.ts
4243
- var DEFAULT_HEADING = "## Available Skills";
4244
- var DEFAULT_EXTRA_NOTE = "Use the load_skill_content tool when you need detailed information about handling a specific type of request.";
6238
+ var DEFAULT_HEADING = "To better accomplish the user's objective, you can use the following skills to access best practices.";
6239
+ var DEFAULT_EXTRA_NOTE = `
6240
+ you must:
6241
+ 1) systematically evaluate every available skill for relevance,
6242
+ 2) explicitly activate all skills you judge relevant using the \`load_skill_content\` tool to get the best practices *before* working on the task, and
6243
+ 3) implement your solution using the guidance and best practices from those activated skills, explaining trade\u2011offs when they matter.
6244
+ `;
4245
6245
  function createSkillMiddleware(params = {}) {
4246
6246
  const {
4247
6247
  skills = [],
@@ -4250,11 +6250,12 @@ function createSkillMiddleware(params = {}) {
4250
6250
  extraNote = DEFAULT_EXTRA_NOTE
4251
6251
  } = params;
4252
6252
  let latestSkills = [];
4253
- return (0, import_langchain34.createMiddleware)({
6253
+ return (0, import_langchain42.createMiddleware)({
4254
6254
  name: "skillMiddleware",
4255
6255
  tools: [
4256
6256
  createLoadSkillsTool({ skills: readAll ? void 0 : skills }),
4257
- createLoadSkillContentTool()
6257
+ createLoadSkillContentTool(),
6258
+ createLoadSkillResourceTool()
4258
6259
  ],
4259
6260
  beforeAgent: async () => {
4260
6261
  try {
@@ -4274,7 +6275,8 @@ function createSkillMiddleware(params = {}) {
4274
6275
  }
4275
6276
  },
4276
6277
  wrapModelCall: (request, handler) => {
4277
- const skillsPrompt = latestSkills.map((skill) => `- **${skill.name}**: ${skill.description}`).join("\n");
6278
+ const skillsPrompt = latestSkills.map((skill) => `## ${skill.name}
6279
+ ${skill.description}`).join("\n");
4278
6280
  const skillsAddendum = `
4279
6281
 
4280
6282
  ${heading}
@@ -4293,10 +6295,10 @@ ${extraNote}`;
4293
6295
  }
4294
6296
 
4295
6297
  // src/deep_agent_new/middleware/fs.ts
4296
- var import_langchain35 = require("langchain");
6298
+ var import_langchain43 = require("langchain");
4297
6299
  var import_langgraph4 = require("@langchain/langgraph");
4298
6300
  var import_v3 = require("zod/v3");
4299
- var import_zod35 = require("@langchain/langgraph/zod");
6301
+ var import_zod43 = require("@langchain/langgraph/zod");
4300
6302
 
4301
6303
  // src/deep_agent_new/backends/utils.ts
4302
6304
  var import_micromatch = __toESM(require("micromatch"));
@@ -4441,15 +6443,15 @@ function globSearchFiles(files, pattern, path5 = "/") {
4441
6443
  const effectivePattern = pattern;
4442
6444
  const matches = [];
4443
6445
  for (const [filePath, fileData] of Object.entries(filtered)) {
4444
- let relative3 = filePath.substring(normalizedPath.length);
4445
- if (relative3.startsWith("/")) {
4446
- relative3 = relative3.substring(1);
6446
+ let relative4 = filePath.substring(normalizedPath.length);
6447
+ if (relative4.startsWith("/")) {
6448
+ relative4 = relative4.substring(1);
4447
6449
  }
4448
- if (!relative3) {
6450
+ if (!relative4) {
4449
6451
  const parts = filePath.split("/");
4450
- relative3 = parts[parts.length - 1] || "";
6452
+ relative4 = parts[parts.length - 1] || "";
4451
6453
  }
4452
- if (import_micromatch.default.isMatch(relative3, effectivePattern, {
6454
+ if (import_micromatch.default.isMatch(relative4, effectivePattern, {
4453
6455
  dot: true,
4454
6456
  nobrace: false
4455
6457
  })) {
@@ -4603,9 +6605,9 @@ var StateBackend = class {
4603
6605
  if (!k.startsWith(normalizedPath)) {
4604
6606
  continue;
4605
6607
  }
4606
- const relative3 = k.substring(normalizedPath.length);
4607
- if (relative3.includes("/")) {
4608
- const subdirName = relative3.split("/")[0];
6608
+ const relative4 = k.substring(normalizedPath.length);
6609
+ if (relative4.includes("/")) {
6610
+ const subdirName = relative4.split("/")[0];
4609
6611
  subdirs.add(normalizedPath + subdirName + "/");
4610
6612
  continue;
4611
6613
  }
@@ -4760,7 +6762,7 @@ function fileDataReducer(left, right) {
4760
6762
  return result;
4761
6763
  }
4762
6764
  var FilesystemStateSchema = import_v3.z.object({
4763
- files: (0, import_zod35.withLangGraph)(
6765
+ files: (0, import_zod43.withLangGraph)(
4764
6766
  import_v3.z.record(import_v3.z.string(), FileDataSchema).default({}),
4765
6767
  {
4766
6768
  reducer: {
@@ -4792,7 +6794,7 @@ var GLOB_TOOL_DESCRIPTION = "Find files matching a glob pattern (e.g., '**/*.py'
4792
6794
  var GREP_TOOL_DESCRIPTION = "Search for a regex pattern in files. Returns matching files and line numbers";
4793
6795
  function createLsTool(backend, options) {
4794
6796
  const { customDescription } = options;
4795
- return (0, import_langchain35.tool)(
6797
+ return (0, import_langchain43.tool)(
4796
6798
  async (input, config) => {
4797
6799
  const { runConfig } = config.configurable;
4798
6800
  const stateAndStore = {
@@ -4828,7 +6830,7 @@ function createLsTool(backend, options) {
4828
6830
  }
4829
6831
  function createReadFileTool(backend, options) {
4830
6832
  const { customDescription } = options;
4831
- return (0, import_langchain35.tool)(
6833
+ return (0, import_langchain43.tool)(
4832
6834
  async (input, config) => {
4833
6835
  const { runConfig } = config.configurable;
4834
6836
  const stateAndStore = {
@@ -4853,7 +6855,7 @@ function createReadFileTool(backend, options) {
4853
6855
  }
4854
6856
  function createWriteFileTool(backend, options) {
4855
6857
  const { customDescription } = options;
4856
- return (0, import_langchain35.tool)(
6858
+ return (0, import_langchain43.tool)(
4857
6859
  async (input, config) => {
4858
6860
  const { runConfig } = config.configurable;
4859
6861
  const stateAndStore = {
@@ -4867,7 +6869,7 @@ function createWriteFileTool(backend, options) {
4867
6869
  if (result.error) {
4868
6870
  return result.error;
4869
6871
  }
4870
- const message = new import_langchain35.ToolMessage({
6872
+ const message = new import_langchain43.ToolMessage({
4871
6873
  content: `Successfully wrote to '${file_path}'`,
4872
6874
  tool_call_id: config.toolCall?.id,
4873
6875
  name: "write_file",
@@ -4892,7 +6894,7 @@ function createWriteFileTool(backend, options) {
4892
6894
  }
4893
6895
  function createEditFileTool(backend, options) {
4894
6896
  const { customDescription } = options;
4895
- return (0, import_langchain35.tool)(
6897
+ return (0, import_langchain43.tool)(
4896
6898
  async (input, config) => {
4897
6899
  const { runConfig } = config.configurable;
4898
6900
  const stateAndStore = {
@@ -4911,7 +6913,7 @@ function createEditFileTool(backend, options) {
4911
6913
  if (result.error) {
4912
6914
  return result.error;
4913
6915
  }
4914
- const message = new import_langchain35.ToolMessage({
6916
+ const message = new import_langchain43.ToolMessage({
4915
6917
  content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`,
4916
6918
  tool_call_id: config.toolCall?.id,
4917
6919
  name: "edit_file",
@@ -4938,7 +6940,7 @@ function createEditFileTool(backend, options) {
4938
6940
  }
4939
6941
  function createGlobTool(backend, options) {
4940
6942
  const { customDescription } = options;
4941
- return (0, import_langchain35.tool)(
6943
+ return (0, import_langchain43.tool)(
4942
6944
  async (input, config) => {
4943
6945
  const { runConfig } = config.configurable;
4944
6946
  const stateAndStore = {
@@ -4966,7 +6968,7 @@ function createGlobTool(backend, options) {
4966
6968
  }
4967
6969
  function createGrepTool(backend, options) {
4968
6970
  const { customDescription } = options;
4969
- return (0, import_langchain35.tool)(
6971
+ return (0, import_langchain43.tool)(
4970
6972
  async (input, config) => {
4971
6973
  const { runConfig } = config.configurable;
4972
6974
  const stateAndStore = {
@@ -5034,7 +7036,7 @@ function createFilesystemMiddleware(options = {}) {
5034
7036
  customDescription: customToolDescriptions?.grep
5035
7037
  })
5036
7038
  ];
5037
- return (0, import_langchain35.createMiddleware)({
7039
+ return (0, import_langchain43.createMiddleware)({
5038
7040
  name: "FilesystemMiddleware",
5039
7041
  stateSchema: FilesystemStateSchema,
5040
7042
  tools,
@@ -5065,7 +7067,7 @@ ${systemPrompt}` : systemPrompt;
5065
7067
  if (writeResult.error) {
5066
7068
  return { message: msg, filesUpdate: null };
5067
7069
  }
5068
- const truncatedMessage = new import_langchain35.ToolMessage({
7070
+ const truncatedMessage = new import_langchain43.ToolMessage({
5069
7071
  content: `Tool result too large (${Math.round(
5070
7072
  msg.content.length / 4
5071
7073
  )} tokens). Content saved to ${evictPath}`,
@@ -5079,7 +7081,7 @@ ${systemPrompt}` : systemPrompt;
5079
7081
  }
5080
7082
  return { message: msg, filesUpdate: null };
5081
7083
  }
5082
- if (result instanceof import_langchain35.ToolMessage) {
7084
+ if (result instanceof import_langchain43.ToolMessage) {
5083
7085
  const processed = await processToolMessage(result);
5084
7086
  if (processed.filesUpdate) {
5085
7087
  return new import_langgraph4.Command({
@@ -5102,7 +7104,7 @@ ${systemPrompt}` : systemPrompt;
5102
7104
  };
5103
7105
  const processedMessages = [];
5104
7106
  for (const msg of update.messages) {
5105
- if (msg instanceof import_langchain35.ToolMessage) {
7107
+ if (msg instanceof import_langchain43.ToolMessage) {
5106
7108
  const processed = await processToolMessage(msg);
5107
7109
  processedMessages.push(processed.message);
5108
7110
  if (processed.filesUpdate) {
@@ -5128,6 +7130,31 @@ ${systemPrompt}` : systemPrompt;
5128
7130
  });
5129
7131
  }
5130
7132
 
7133
+ // src/middlewares/metricsMiddleware.ts
7134
+ var import_langchain44 = require("langchain");
7135
+ function createMetricsMiddleware(params) {
7136
+ const { serverKeys, serverDescriptions } = params;
7137
+ if (!serverKeys || serverKeys.length === 0) {
7138
+ return (0, import_langchain44.createMiddleware)({
7139
+ name: "metricsMiddleware",
7140
+ tools: []
7141
+ });
7142
+ }
7143
+ const toolParams = {
7144
+ serverKeys,
7145
+ serverDescriptions
7146
+ };
7147
+ return (0, import_langchain44.createMiddleware)({
7148
+ name: "metricsMiddleware",
7149
+ tools: [
7150
+ createListMetricsDataSourcesTool(toolParams),
7151
+ createQueryMetricsListTool(toolParams),
7152
+ createQueryMetricDefinitionTool(toolParams),
7153
+ createQuerySemanticMetricDataTool(toolParams)
7154
+ ]
7155
+ });
7156
+ }
7157
+
5131
7158
  // src/agent_lattice/builders/commonMiddleware.ts
5132
7159
  function createCommonMiddlewares(middlewareConfigs, filesystemBackend) {
5133
7160
  const middlewares = [];
@@ -5166,6 +7193,14 @@ function createCommonMiddlewares(middlewareConfigs, filesystemBackend) {
5166
7193
  case "skill":
5167
7194
  middlewares.push(createSkillMiddleware(config.config));
5168
7195
  break;
7196
+ case "metrics":
7197
+ {
7198
+ const metricsConfig = config.config;
7199
+ if (metricsConfig.serverKeys && metricsConfig.serverKeys.length > 0) {
7200
+ middlewares.push(createMetricsMiddleware(metricsConfig));
7201
+ }
7202
+ }
7203
+ break;
5169
7204
  }
5170
7205
  }
5171
7206
  return middlewares;
@@ -5209,14 +7244,14 @@ var ReActAgentGraphBuilder = class {
5209
7244
  */
5210
7245
  build(agentLattice, params) {
5211
7246
  const tools = params.tools.map((t) => {
5212
- const tool38 = getToolClient(t.key);
5213
- return tool38;
5214
- }).filter((tool38) => tool38 !== void 0);
7247
+ const tool46 = getToolClient(t.key);
7248
+ return tool46;
7249
+ }).filter((tool46) => tool46 !== void 0);
5215
7250
  const stateSchema2 = createReactAgentSchema(params.stateSchema);
5216
7251
  const middlewareConfigs = params.middleware || [];
5217
7252
  const filesystemBackend = this.createFilesystemBackendFactory(middlewareConfigs);
5218
7253
  const middlewares = createCommonMiddlewares(middlewareConfigs, filesystemBackend);
5219
- return (0, import_langchain36.createAgent)({
7254
+ return (0, import_langchain45.createAgent)({
5220
7255
  model: params.model,
5221
7256
  tools,
5222
7257
  systemPrompt: params.prompt,
@@ -5229,11 +7264,11 @@ var ReActAgentGraphBuilder = class {
5229
7264
  };
5230
7265
 
5231
7266
  // src/deep_agent_new/agent.ts
5232
- var import_langchain40 = require("langchain");
7267
+ var import_langchain49 = require("langchain");
5233
7268
 
5234
7269
  // src/deep_agent_new/middleware/subagents.ts
5235
7270
  var import_v32 = require("zod/v3");
5236
- var import_langchain37 = require("langchain");
7271
+ var import_langchain46 = require("langchain");
5237
7272
  var import_langgraph6 = require("@langchain/langgraph");
5238
7273
  var import_messages = require("@langchain/core/messages");
5239
7274
 
@@ -5788,7 +7823,7 @@ function returnCommandWithStateUpdate(result, toolCallId) {
5788
7823
  update: {
5789
7824
  ...stateUpdate,
5790
7825
  messages: [
5791
- new import_langchain37.ToolMessage({
7826
+ new import_langchain46.ToolMessage({
5792
7827
  content: lastMessage?.content || "Task Failed to complete",
5793
7828
  tool_call_id: toolCallId,
5794
7829
  name: "task"
@@ -5813,10 +7848,10 @@ function getSubagents(options) {
5813
7848
  const generalPurposeMiddleware = [...defaultSubagentMiddleware];
5814
7849
  if (defaultInterruptOn) {
5815
7850
  generalPurposeMiddleware.push(
5816
- (0, import_langchain37.humanInTheLoopMiddleware)({ interruptOn: defaultInterruptOn })
7851
+ (0, import_langchain46.humanInTheLoopMiddleware)({ interruptOn: defaultInterruptOn })
5817
7852
  );
5818
7853
  }
5819
- const generalPurposeSubagent = (0, import_langchain37.createAgent)({
7854
+ const generalPurposeSubagent = (0, import_langchain46.createAgent)({
5820
7855
  model: defaultModel,
5821
7856
  systemPrompt: DEFAULT_SUBAGENT_PROMPT,
5822
7857
  tools: defaultTools,
@@ -5837,8 +7872,8 @@ function getSubagents(options) {
5837
7872
  const middleware = agentParams.middleware ? [...defaultSubagentMiddleware, ...agentParams.middleware] : [...defaultSubagentMiddleware];
5838
7873
  const interruptOn = agentParams.interruptOn || defaultInterruptOn;
5839
7874
  if (interruptOn)
5840
- middleware.push((0, import_langchain37.humanInTheLoopMiddleware)({ interruptOn }));
5841
- agents[agentParams.name] = (0, import_langchain37.createAgent)({
7875
+ middleware.push((0, import_langchain46.humanInTheLoopMiddleware)({ interruptOn }));
7876
+ agents[agentParams.name] = (0, import_langchain46.createAgent)({
5842
7877
  model: agentParams.model ?? defaultModel,
5843
7878
  systemPrompt: agentParams.systemPrompt,
5844
7879
  tools: agentParams.tools ?? defaultTools,
@@ -5867,7 +7902,7 @@ function createTaskTool(options) {
5867
7902
  generalPurposeAgent
5868
7903
  });
5869
7904
  const finalTaskDescription = taskDescription ? taskDescription : getTaskToolDescription(subagentDescriptions);
5870
- return (0, import_langchain37.tool)(
7905
+ return (0, import_langchain46.tool)(
5871
7906
  async (input, config) => {
5872
7907
  const { description, subagent_type } = input;
5873
7908
  try {
@@ -5897,7 +7932,7 @@ function createTaskTool(options) {
5897
7932
  return new import_langgraph6.Command({
5898
7933
  update: {
5899
7934
  messages: [
5900
- new import_langchain37.ToolMessage({
7935
+ new import_langchain46.ToolMessage({
5901
7936
  content: error instanceof Error ? error.message : "Task Failed to complete",
5902
7937
  tool_call_id: config.toolCall.id,
5903
7938
  name: "task"
@@ -5941,7 +7976,7 @@ function createSubAgentMiddleware(options) {
5941
7976
  generalPurposeAgent,
5942
7977
  taskDescription
5943
7978
  });
5944
- return (0, import_langchain37.createMiddleware)({
7979
+ return (0, import_langchain46.createMiddleware)({
5945
7980
  name: "subAgentMiddleware",
5946
7981
  tools: [taskTool],
5947
7982
  wrapModelCall: async (request, handler) => {
@@ -5961,11 +7996,11 @@ ${systemPrompt}` : systemPrompt;
5961
7996
  }
5962
7997
 
5963
7998
  // src/deep_agent_new/middleware/patch_tool_calls.ts
5964
- var import_langchain38 = require("langchain");
7999
+ var import_langchain47 = require("langchain");
5965
8000
  var import_messages2 = require("@langchain/core/messages");
5966
8001
  var import_langgraph7 = require("@langchain/langgraph");
5967
8002
  function createPatchToolCallsMiddleware() {
5968
- return (0, import_langchain38.createMiddleware)({
8003
+ return (0, import_langchain47.createMiddleware)({
5969
8004
  name: "patchToolCallsMiddleware",
5970
8005
  beforeAgent: async (state) => {
5971
8006
  const messages = state.messages;
@@ -5976,15 +8011,15 @@ function createPatchToolCallsMiddleware() {
5976
8011
  for (let i = 0; i < messages.length; i++) {
5977
8012
  const msg = messages[i];
5978
8013
  patchedMessages.push(msg);
5979
- if (import_langchain38.AIMessage.isInstance(msg) && msg.tool_calls != null) {
8014
+ if (import_langchain47.AIMessage.isInstance(msg) && msg.tool_calls != null) {
5980
8015
  for (const toolCall of msg.tool_calls) {
5981
8016
  const correspondingToolMsg = messages.slice(i).find(
5982
- (m) => import_langchain38.ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id
8017
+ (m) => import_langchain47.ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id
5983
8018
  );
5984
8019
  if (!correspondingToolMsg) {
5985
8020
  const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`;
5986
8021
  patchedMessages.push(
5987
- new import_langchain38.ToolMessage({
8022
+ new import_langchain47.ToolMessage({
5988
8023
  content: toolMsg,
5989
8024
  name: toolCall.name,
5990
8025
  tool_call_id: toolCall.id
@@ -6119,9 +8154,9 @@ var StoreBackend = class {
6119
8154
  if (!itemKey.startsWith(normalizedPath)) {
6120
8155
  continue;
6121
8156
  }
6122
- const relative3 = itemKey.substring(normalizedPath.length);
6123
- if (relative3.includes("/")) {
6124
- const subdirName = relative3.split("/")[0];
8157
+ const relative4 = itemKey.substring(normalizedPath.length);
8158
+ if (relative4.includes("/")) {
8159
+ const subdirName = relative4.split("/")[0];
6125
8160
  subdirs.add(normalizedPath + subdirName + "/");
6126
8161
  continue;
6127
8162
  }
@@ -6314,8 +8349,8 @@ var FilesystemBackend = class {
6314
8349
  throw new Error("Path traversal not allowed");
6315
8350
  }
6316
8351
  const full = path4.resolve(this.cwd, vpath.substring(1));
6317
- const relative3 = path4.relative(this.cwd, full);
6318
- if (relative3.startsWith("..") || path4.isAbsolute(relative3)) {
8352
+ const relative4 = path4.relative(this.cwd, full);
8353
+ if (relative4.startsWith("..") || path4.isAbsolute(relative4)) {
6319
8354
  throw new Error(`Path: ${full} outside root directory: ${this.cwd}`);
6320
8355
  }
6321
8356
  return full;
@@ -6650,9 +8685,9 @@ var FilesystemBackend = class {
6650
8685
  if (this.virtualMode) {
6651
8686
  try {
6652
8687
  const resolved = path4.resolve(ftext);
6653
- const relative3 = path4.relative(this.cwd, resolved);
6654
- if (relative3.startsWith("..")) continue;
6655
- const normalizedRelative = relative3.split(path4.sep).join("/");
8688
+ const relative4 = path4.relative(this.cwd, resolved);
8689
+ if (relative4.startsWith("..")) continue;
8690
+ const normalizedRelative = relative4.split(path4.sep).join("/");
6656
8691
  virtPath = "/" + normalizedRelative;
6657
8692
  } catch {
6658
8693
  continue;
@@ -6714,9 +8749,9 @@ var FilesystemBackend = class {
6714
8749
  let virtPath;
6715
8750
  if (this.virtualMode) {
6716
8751
  try {
6717
- const relative3 = path4.relative(this.cwd, fp);
6718
- if (relative3.startsWith("..")) continue;
6719
- const normalizedRelative = relative3.split(path4.sep).join("/");
8752
+ const relative4 = path4.relative(this.cwd, fp);
8753
+ if (relative4.startsWith("..")) continue;
8754
+ const normalizedRelative = relative4.split(path4.sep).join("/");
6720
8755
  virtPath = "/" + normalizedRelative;
6721
8756
  } catch {
6722
8757
  continue;
@@ -6999,9 +9034,9 @@ var MemoryBackend = class {
6999
9034
  if (!k.startsWith(normalizedPath)) {
7000
9035
  continue;
7001
9036
  }
7002
- const relative3 = k.substring(normalizedPath.length);
7003
- if (relative3.includes("/")) {
7004
- const subdirName = relative3.split("/")[0];
9037
+ const relative4 = k.substring(normalizedPath.length);
9038
+ if (relative4.includes("/")) {
9039
+ const subdirName = relative4.split("/")[0];
7005
9040
  subdirs.add(normalizedPath + subdirName + "/");
7006
9041
  continue;
7007
9042
  }
@@ -7097,8 +9132,8 @@ var MemoryBackend = class {
7097
9132
 
7098
9133
  // src/deep_agent_new/middleware/todos.ts
7099
9134
  var import_langgraph8 = require("@langchain/langgraph");
7100
- var import_zod36 = require("zod");
7101
- var import_langchain39 = require("langchain");
9135
+ var import_zod44 = require("zod");
9136
+ var import_langchain48 = require("langchain");
7102
9137
  var WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
7103
9138
  It also helps the user understand the progress of the task and overall progress of their requests.
7104
9139
  Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
@@ -7325,20 +9360,20 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
7325
9360
  ## Important To-Do List Usage Notes to Remember
7326
9361
  - The \`write_todos\` tool should never be called multiple times in parallel.
7327
9362
  - Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`;
7328
- var TodoStatus = import_zod36.z.enum(["pending", "in_progress", "completed"]).describe("Status of the todo");
7329
- var TodoSchema = import_zod36.z.object({
7330
- content: import_zod36.z.string().describe("Content of the todo item"),
9363
+ var TodoStatus = import_zod44.z.enum(["pending", "in_progress", "completed"]).describe("Status of the todo");
9364
+ var TodoSchema = import_zod44.z.object({
9365
+ content: import_zod44.z.string().describe("Content of the todo item"),
7331
9366
  status: TodoStatus
7332
9367
  });
7333
- var stateSchema = import_zod36.z.object({ todos: import_zod36.z.array(TodoSchema).default([]) });
9368
+ var stateSchema = import_zod44.z.object({ todos: import_zod44.z.array(TodoSchema).default([]) });
7334
9369
  function todoListMiddleware(options) {
7335
- const writeTodos = (0, import_langchain39.tool)(
9370
+ const writeTodos = (0, import_langchain48.tool)(
7336
9371
  ({ todos }, config) => {
7337
9372
  return new import_langgraph8.Command({
7338
9373
  update: {
7339
9374
  todos,
7340
9375
  messages: [
7341
- new import_langchain39.ToolMessage({
9376
+ new import_langchain48.ToolMessage({
7342
9377
  content: genUIMarkdown("todo_list", todos),
7343
9378
  tool_call_id: config.toolCall?.id
7344
9379
  })
@@ -7349,12 +9384,12 @@ function todoListMiddleware(options) {
7349
9384
  {
7350
9385
  name: "write_todos",
7351
9386
  description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION,
7352
- schema: import_zod36.z.object({
7353
- todos: import_zod36.z.array(TodoSchema).describe("List of todo items to update")
9387
+ schema: import_zod44.z.object({
9388
+ todos: import_zod44.z.array(TodoSchema).describe("List of todo items to update")
7354
9389
  })
7355
9390
  }
7356
9391
  );
7357
- return (0, import_langchain39.createMiddleware)({
9392
+ return (0, import_langchain48.createMiddleware)({
7358
9393
  name: "todoListMiddleware",
7359
9394
  stateSchema,
7360
9395
  tools: [writeTodos],
@@ -7406,13 +9441,13 @@ ${BASE_PROMPT}` : BASE_PROMPT;
7406
9441
  backend: filesystemBackend
7407
9442
  }),
7408
9443
  // Subagent middleware: Automatic conversation summarization when token limits are approached
7409
- (0, import_langchain40.summarizationMiddleware)({
9444
+ (0, import_langchain49.summarizationMiddleware)({
7410
9445
  model,
7411
9446
  trigger: { tokens: 17e4 },
7412
9447
  keep: { messages: 6 }
7413
9448
  }),
7414
9449
  // Subagent middleware: Anthropic prompt caching for improved performance
7415
- (0, import_langchain40.anthropicPromptCachingMiddleware)({
9450
+ (0, import_langchain49.anthropicPromptCachingMiddleware)({
7416
9451
  unsupportedModelBehavior: "ignore"
7417
9452
  }),
7418
9453
  // Subagent middleware: Patches tool calls for compatibility
@@ -7423,23 +9458,23 @@ ${BASE_PROMPT}` : BASE_PROMPT;
7423
9458
  generalPurposeAgent: false
7424
9459
  }),
7425
9460
  // Automatically summarizes conversation history when token limits are approached
7426
- (0, import_langchain40.summarizationMiddleware)({
9461
+ (0, import_langchain49.summarizationMiddleware)({
7427
9462
  model,
7428
9463
  trigger: { tokens: 17e4 },
7429
9464
  keep: { messages: 6 }
7430
9465
  }),
7431
9466
  // Enables Anthropic prompt caching for improved performance and reduced costs
7432
- (0, import_langchain40.anthropicPromptCachingMiddleware)({
9467
+ (0, import_langchain49.anthropicPromptCachingMiddleware)({
7433
9468
  unsupportedModelBehavior: "ignore"
7434
9469
  }),
7435
9470
  // Patches tool calls to ensure compatibility across different model providers
7436
9471
  createPatchToolCallsMiddleware()
7437
9472
  ];
7438
9473
  if (interruptOn) {
7439
- middleware.push((0, import_langchain40.humanInTheLoopMiddleware)({ interruptOn }));
9474
+ middleware.push((0, import_langchain49.humanInTheLoopMiddleware)({ interruptOn }));
7440
9475
  }
7441
9476
  middleware.push(...customMiddleware);
7442
- return (0, import_langchain40.createAgent)({
9477
+ return (0, import_langchain49.createAgent)({
7443
9478
  model,
7444
9479
  systemPrompt: finalSystemPrompt,
7445
9480
  tools,
@@ -7497,7 +9532,7 @@ var DeepAgentGraphBuilder = class {
7497
9532
  const tools = params.tools.map((t) => {
7498
9533
  const toolClient = getToolClient(t.key);
7499
9534
  return toolClient;
7500
- }).filter((tool38) => tool38 !== void 0);
9535
+ }).filter((tool46) => tool46 !== void 0);
7501
9536
  const subagents = params.subAgents.map((sa) => {
7502
9537
  if (sa.client) {
7503
9538
  return {
@@ -7536,7 +9571,7 @@ var DeepAgentGraphBuilder = class {
7536
9571
 
7537
9572
  // src/agent_team/agent_team.ts
7538
9573
  var import_v35 = require("zod/v3");
7539
- var import_langchain43 = require("langchain");
9574
+ var import_langchain52 = require("langchain");
7540
9575
 
7541
9576
  // src/agent_team/types.ts
7542
9577
  var TaskStatus = /* @__PURE__ */ ((TaskStatus3) => {
@@ -7972,13 +10007,13 @@ var InMemoryMailboxStore = class {
7972
10007
 
7973
10008
  // src/agent_team/middleware/team.ts
7974
10009
  var import_v34 = require("zod/v3");
7975
- var import_langchain42 = require("langchain");
10010
+ var import_langchain51 = require("langchain");
7976
10011
  var import_langgraph10 = require("@langchain/langgraph");
7977
10012
  var import_uuid = require("uuid");
7978
10013
 
7979
10014
  // src/agent_team/middleware/teammate_tools.ts
7980
10015
  var import_v33 = require("zod/v3");
7981
- var import_langchain41 = require("langchain");
10016
+ var import_langchain50 = require("langchain");
7982
10017
  var import_langgraph9 = require("@langchain/langgraph");
7983
10018
 
7984
10019
  // src/agent_team/middleware/formatMessages.ts
@@ -8003,7 +10038,7 @@ ${meta}${body}`;
8003
10038
  // src/agent_team/middleware/teammate_tools.ts
8004
10039
  function createTeammateTools(options) {
8005
10040
  const { teamId, agentId, taskListStore, mailboxStore } = options;
8006
- const claimTaskTool = (0, import_langchain41.tool)(
10041
+ const claimTaskTool = (0, import_langchain50.tool)(
8007
10042
  async (input) => {
8008
10043
  const task = await taskListStore.claimTaskById(
8009
10044
  teamId,
@@ -8033,7 +10068,7 @@ function createTeammateTools(options) {
8033
10068
  })
8034
10069
  }
8035
10070
  );
8036
- const completeTaskTool = (0, import_langchain41.tool)(
10071
+ const completeTaskTool = (0, import_langchain50.tool)(
8037
10072
  async (input) => {
8038
10073
  const task = await taskListStore.completeTask(
8039
10074
  teamId,
@@ -8060,7 +10095,7 @@ function createTeammateTools(options) {
8060
10095
  })
8061
10096
  }
8062
10097
  );
8063
- const failTaskTool = (0, import_langchain41.tool)(
10098
+ const failTaskTool = (0, import_langchain50.tool)(
8064
10099
  async (input) => {
8065
10100
  const task = await taskListStore.failTask(
8066
10101
  teamId,
@@ -8087,7 +10122,7 @@ function createTeammateTools(options) {
8087
10122
  })
8088
10123
  }
8089
10124
  );
8090
- const sendMessageTool = (0, import_langchain41.tool)(
10125
+ const sendMessageTool = (0, import_langchain50.tool)(
8091
10126
  async (input) => {
8092
10127
  await mailboxStore.sendMessage(
8093
10128
  teamId,
@@ -8125,7 +10160,7 @@ function createTeammateTools(options) {
8125
10160
  read: msg.read
8126
10161
  }));
8127
10162
  };
8128
- const readMessagesTool = (0, import_langchain41.tool)(
10163
+ const readMessagesTool = (0, import_langchain50.tool)(
8129
10164
  async (input, config) => {
8130
10165
  const formatAndMarkAsRead = async (msgs2) => {
8131
10166
  for (const msg of msgs2) {
@@ -8137,7 +10172,7 @@ function createTeammateTools(options) {
8137
10172
  if (msgs.length > 0) {
8138
10173
  const formatted2 = await formatAndMarkAsRead(msgs);
8139
10174
  const relevantMsgs2 = await getRelevantMessagesForState();
8140
- const toolMessage2 = new import_langchain41.ToolMessage({
10175
+ const toolMessage2 = new import_langchain50.ToolMessage({
8141
10176
  content: formatted2,
8142
10177
  tool_call_id: config.toolCall?.id,
8143
10178
  name: "read_messages"
@@ -8162,7 +10197,7 @@ function createTeammateTools(options) {
8162
10197
  });
8163
10198
  const relevantMsgs = await getRelevantMessagesForState();
8164
10199
  if (msgs.length === 0) {
8165
- const toolMessage2 = new import_langchain41.ToolMessage({
10200
+ const toolMessage2 = new import_langchain50.ToolMessage({
8166
10201
  content: "No unread messages.",
8167
10202
  tool_call_id: config.toolCall?.id,
8168
10203
  name: "read_messages"
@@ -8172,7 +10207,7 @@ function createTeammateTools(options) {
8172
10207
  });
8173
10208
  }
8174
10209
  const formatted = await formatAndMarkAsRead(msgs);
8175
- const toolMessage = new import_langchain41.ToolMessage({
10210
+ const toolMessage = new import_langchain50.ToolMessage({
8176
10211
  content: formatted,
8177
10212
  tool_call_id: config.toolCall?.id,
8178
10213
  name: "read_messages"
@@ -8187,7 +10222,7 @@ function createTeammateTools(options) {
8187
10222
  schema: import_v33.z.object({})
8188
10223
  }
8189
10224
  );
8190
- const checkTasksTool = (0, import_langchain41.tool)(
10225
+ const checkTasksTool = (0, import_langchain50.tool)(
8191
10226
  async () => {
8192
10227
  const tasks = await taskListStore.getAllTasks(teamId);
8193
10228
  return formatTaskSummary(tasks);
@@ -8198,7 +10233,7 @@ function createTeammateTools(options) {
8198
10233
  schema: import_v33.z.object({})
8199
10234
  }
8200
10235
  );
8201
- const broadcastMessageTool = (0, import_langchain41.tool)(
10236
+ const broadcastMessageTool = (0, import_langchain50.tool)(
8202
10237
  async (input) => {
8203
10238
  const allAgents = await mailboxStore.getRegisteredAgents(teamId);
8204
10239
  const recipients = allAgents.filter((a) => a !== agentId);
@@ -8383,7 +10418,7 @@ You have access to these tools:
8383
10418
  - \`read_messages\`: Read messages from team_lead or teammates
8384
10419
  - \`check_tasks\`: Get current status of all tasks in the team`;
8385
10420
  const assistantId = getTeammateAssistantId(ctx.teamId, spec.name);
8386
- agent = (0, import_langchain42.createAgent)({
10421
+ agent = (0, import_langchain51.createAgent)({
8387
10422
  model: spec.model ?? ctx.defaultModel,
8388
10423
  systemPrompt: teammatePrompt,
8389
10424
  tools: allTools,
@@ -8441,12 +10476,12 @@ async function spawnTeammate(options) {
8441
10476
  function createTeamMiddleware(options) {
8442
10477
  const { teamConfig, taskListStore, mailboxStore } = options;
8443
10478
  const defaultModel = teamConfig.model ?? "claude-sonnet-4-5-20250929";
8444
- const createTeamTool = (0, import_langchain42.tool)(
10479
+ const createTeamTool = (0, import_langchain51.tool)(
8445
10480
  async (input, config) => {
8446
10481
  const state = (0, import_langgraph10.getCurrentTaskInput)();
8447
10482
  if (state?.team?.teamId) {
8448
10483
  const existingId = state.team.teamId;
8449
- const msg = new import_langchain42.ToolMessage({
10484
+ const msg = new import_langchain51.ToolMessage({
8450
10485
  content: `A team is already active (id: ${existingId}). Use this team_id for \`check_tasks\`, \`read_messages\`, \`add_tasks\`, \`send_message\`, \`assign_task\`, \`set_task_status\`, and \`set_task_dependencies\`. Do not call \`create_team\` again unless you need a fresh team for a new objective.`,
8451
10486
  tool_call_id: config.toolCall?.id,
8452
10487
  name: "create_team"
@@ -8531,7 +10566,7 @@ Teammates are now working in the background. Keep calling \`check_tasks\` and \`
8531
10566
  \`\`\`json
8532
10567
  ${teamJson}
8533
10568
  \`\`\``;
8534
- const toolMessage = new import_langchain42.ToolMessage({
10569
+ const toolMessage = new import_langchain51.ToolMessage({
8535
10570
  content: summary,
8536
10571
  tool_call_id: config.toolCall?.id,
8537
10572
  name: "create_team"
@@ -8616,7 +10651,7 @@ After calling create_team, you MUST:
8616
10651
  if (state?.team?.teamId) return state.team.teamId;
8617
10652
  throw new Error("No team_id provided and no team in state. Call create_team first.");
8618
10653
  };
8619
- const addTasksTool = (0, import_langchain42.tool)(
10654
+ const addTasksTool = (0, import_langchain51.tool)(
8620
10655
  async (input, config) => {
8621
10656
  const teamId = resolveTeamId();
8622
10657
  const created = await taskListStore.addTasks(
@@ -8630,7 +10665,7 @@ After calling create_team, you MUST:
8630
10665
  }))
8631
10666
  );
8632
10667
  const summary = created.map((t) => `- ${t.id}: "${t.title}"`).join("\n");
8633
- return new import_langchain42.ToolMessage({
10668
+ return new import_langchain51.ToolMessage({
8634
10669
  content: `Added ${created.length} task(s) to team ${teamId}:
8635
10670
  ${summary}
8636
10671
  Sleeping teammates will wake up and claim these.`,
@@ -8681,20 +10716,20 @@ IMPORTANT: Assigning to a specific teammate
8681
10716
  })
8682
10717
  }
8683
10718
  );
8684
- const assignTaskTool = (0, import_langchain42.tool)(
10719
+ const assignTaskTool = (0, import_langchain51.tool)(
8685
10720
  async (input, config) => {
8686
10721
  const teamId = resolveTeamId();
8687
10722
  const task = await taskListStore.updateTask(teamId, input.task_id, {
8688
10723
  assignee: input.assignee
8689
10724
  });
8690
10725
  if (!task) {
8691
- return new import_langchain42.ToolMessage({
10726
+ return new import_langchain51.ToolMessage({
8692
10727
  content: `Task ${input.task_id} not found in team ${teamId}.`,
8693
10728
  tool_call_id: config.toolCall?.id,
8694
10729
  name: "assign_task"
8695
10730
  });
8696
10731
  }
8697
- return new import_langchain42.ToolMessage({
10732
+ return new import_langchain51.ToolMessage({
8698
10733
  content: `Task "${task.title}" (${task.id}) assigned to ${input.assignee}.`,
8699
10734
  tool_call_id: config.toolCall?.id,
8700
10735
  name: "assign_task"
@@ -8709,20 +10744,20 @@ IMPORTANT: Assigning to a specific teammate
8709
10744
  })
8710
10745
  }
8711
10746
  );
8712
- const setTaskStatusTool = (0, import_langchain42.tool)(
10747
+ const setTaskStatusTool = (0, import_langchain51.tool)(
8713
10748
  async (input, config) => {
8714
10749
  const teamId = resolveTeamId();
8715
10750
  const task = await taskListStore.updateTask(teamId, input.task_id, {
8716
10751
  status: input.status
8717
10752
  });
8718
10753
  if (!task) {
8719
- return new import_langchain42.ToolMessage({
10754
+ return new import_langchain51.ToolMessage({
8720
10755
  content: `Task ${input.task_id} not found in team ${teamId}.`,
8721
10756
  tool_call_id: config.toolCall?.id,
8722
10757
  name: "set_task_status"
8723
10758
  });
8724
10759
  }
8725
- return new import_langchain42.ToolMessage({
10760
+ return new import_langchain51.ToolMessage({
8726
10761
  content: `Task "${task.title}" (${task.id}) status set to ${input.status}.`,
8727
10762
  tool_call_id: config.toolCall?.id,
8728
10763
  name: "set_task_status"
@@ -8737,20 +10772,20 @@ IMPORTANT: Assigning to a specific teammate
8737
10772
  })
8738
10773
  }
8739
10774
  );
8740
- const setTaskDependenciesTool = (0, import_langchain42.tool)(
10775
+ const setTaskDependenciesTool = (0, import_langchain51.tool)(
8741
10776
  async (input, config) => {
8742
10777
  const teamId = resolveTeamId();
8743
10778
  const task = await taskListStore.updateTask(teamId, input.task_id, {
8744
10779
  dependencies: input.dependencies
8745
10780
  });
8746
10781
  if (!task) {
8747
- return new import_langchain42.ToolMessage({
10782
+ return new import_langchain51.ToolMessage({
8748
10783
  content: `Task ${input.task_id} not found in team ${teamId}.`,
8749
10784
  tool_call_id: config.toolCall?.id,
8750
10785
  name: "set_task_dependencies"
8751
10786
  });
8752
10787
  }
8753
- return new import_langchain42.ToolMessage({
10788
+ return new import_langchain51.ToolMessage({
8754
10789
  content: `Task "${task.title}" (${task.id}) dependencies set to [${input.dependencies.join(", ")}].`,
8755
10790
  tool_call_id: config.toolCall?.id,
8756
10791
  name: "set_task_dependencies"
@@ -8765,7 +10800,7 @@ IMPORTANT: Assigning to a specific teammate
8765
10800
  })
8766
10801
  }
8767
10802
  );
8768
- const checkTasksTool = (0, import_langchain42.tool)(
10803
+ const checkTasksTool = (0, import_langchain51.tool)(
8769
10804
  async (input, config) => {
8770
10805
  const teamId = resolveTeamId();
8771
10806
  const tasks = await taskListStore.getAllTasks(teamId);
@@ -8774,7 +10809,7 @@ IMPORTANT: Assigning to a specific teammate
8774
10809
  update: {
8775
10810
  tasks: tasksSnapshot,
8776
10811
  messages: [
8777
- new import_langchain42.ToolMessage({
10812
+ new import_langchain51.ToolMessage({
8778
10813
  content: formatTaskSummary(tasks),
8779
10814
  tool_call_id: config.toolCall?.id,
8780
10815
  name: "check_tasks"
@@ -8810,7 +10845,7 @@ Task Status Values:
8810
10845
  })
8811
10846
  }
8812
10847
  );
8813
- const sendMessageTool = (0, import_langchain42.tool)(
10848
+ const sendMessageTool = (0, import_langchain51.tool)(
8814
10849
  async (input, config) => {
8815
10850
  const teamId = resolveTeamId();
8816
10851
  await mailboxStore.sendMessage(
@@ -8820,7 +10855,7 @@ Task Status Values:
8820
10855
  input.content,
8821
10856
  "direct_message" /* DIRECT_MESSAGE */
8822
10857
  );
8823
- return new import_langchain42.ToolMessage({
10858
+ return new import_langchain51.ToolMessage({
8824
10859
  content: `Message sent to ${input.to}.`,
8825
10860
  tool_call_id: config.toolCall?.id,
8826
10861
  name: "send_message"
@@ -8835,7 +10870,7 @@ Task Status Values:
8835
10870
  })
8836
10871
  }
8837
10872
  );
8838
- const readMessagesTool = (0, import_langchain42.tool)(
10873
+ const readMessagesTool = (0, import_langchain51.tool)(
8839
10874
  async (input, config) => {
8840
10875
  const teamId = resolveTeamId();
8841
10876
  const formatAndMarkAsRead = async (msgs2) => {
@@ -8863,7 +10898,7 @@ Task Status Values:
8863
10898
  if (msgs.length > 0) {
8864
10899
  const formatted2 = await formatAndMarkAsRead(msgs);
8865
10900
  const allTeamMessages2 = await getAllTeamMessagesForState();
8866
- const toolMessage2 = new import_langchain42.ToolMessage({
10901
+ const toolMessage2 = new import_langchain51.ToolMessage({
8867
10902
  content: formatted2,
8868
10903
  tool_call_id: config.toolCall?.id,
8869
10904
  name: "read_messages"
@@ -8895,7 +10930,7 @@ Task Status Values:
8895
10930
  );
8896
10931
  const allTeamMessages = await getAllTeamMessagesForState();
8897
10932
  if (msgs.length === 0) {
8898
- const toolMessage2 = new import_langchain42.ToolMessage({
10933
+ const toolMessage2 = new import_langchain51.ToolMessage({
8899
10934
  content: "No unread messages from teammates.",
8900
10935
  tool_call_id: config.toolCall?.id,
8901
10936
  name: "read_messages"
@@ -8905,7 +10940,7 @@ Task Status Values:
8905
10940
  });
8906
10941
  }
8907
10942
  const formatted = await formatAndMarkAsRead(msgs);
8908
- const toolMessage = new import_langchain42.ToolMessage({
10943
+ const toolMessage = new import_langchain51.ToolMessage({
8909
10944
  content: formatted,
8910
10945
  tool_call_id: config.toolCall?.id,
8911
10946
  name: "read_messages"
@@ -8922,7 +10957,7 @@ Task Status Values:
8922
10957
  })
8923
10958
  }
8924
10959
  );
8925
- const disbandTeamTool = (0, import_langchain42.tool)(
10960
+ const disbandTeamTool = (0, import_langchain51.tool)(
8926
10961
  async (input, config) => {
8927
10962
  const teamId = resolveTeamId();
8928
10963
  await mailboxStore.broadcastMessage(
@@ -8932,7 +10967,7 @@ Task Status Values:
8932
10967
  "shutdown_request" /* SHUTDOWN_REQUEST */
8933
10968
  );
8934
10969
  await new Promise((r) => setTimeout(r, 2e3));
8935
- return new import_langchain42.ToolMessage({
10970
+ return new import_langchain51.ToolMessage({
8936
10971
  content: `Team ${teamId} has been disbanded. All teammates notified and resources cleaned up.`,
8937
10972
  tool_call_id: config.toolCall?.id,
8938
10973
  name: "disband_team"
@@ -8943,7 +10978,7 @@ Task Status Values:
8943
10978
  description: "Disband a team when all work is done. Before calling: (1) Call check_tasks to verify no tasks are still pending/in_progress; (2) if any are, discuss with the team via read_messages and broadcast_message/send_message whether to continue or stop/cancel them; (3) only after alignment (all tasks completed/failed or explicitly stopped), then call this tool. This will: 1) Send a shutdown message to all teammates, 2) Wait briefly for them to clean up, 3) Clear all tasks and messages. Omit team_id to use the active team from state."
8944
10979
  }
8945
10980
  );
8946
- const broadcastMessageTool = (0, import_langchain42.tool)(
10981
+ const broadcastMessageTool = (0, import_langchain51.tool)(
8947
10982
  async (input, config) => {
8948
10983
  const teamId = resolveTeamId();
8949
10984
  await mailboxStore.broadcastMessage(
@@ -8952,7 +10987,7 @@ Task Status Values:
8952
10987
  input.content,
8953
10988
  "broadcast" /* BROADCAST */
8954
10989
  );
8955
- return new import_langchain42.ToolMessage({
10990
+ return new import_langchain51.ToolMessage({
8956
10991
  content: `Broadcast message sent to all teammates.`,
8957
10992
  tool_call_id: config.toolCall?.id,
8958
10993
  name: "broadcast_message"
@@ -8966,7 +11001,7 @@ Task Status Values:
8966
11001
  })
8967
11002
  }
8968
11003
  );
8969
- return (0, import_langchain42.createMiddleware)({
11004
+ return (0, import_langchain51.createMiddleware)({
8970
11005
  name: "teamMiddleware",
8971
11006
  tools: [
8972
11007
  createTeamTool,
@@ -9074,7 +11109,7 @@ function createAgentTeam(config) {
9074
11109
  ];
9075
11110
  const systemPrompt = config.systemPrompt + "\n\n" + TEAM_LEAD_BASE_PROMPT;
9076
11111
  const stateSchema2 = createReactAgentSchema(TEAM_STATE_SCHEMA);
9077
- return (0, import_langchain43.createAgent)({
11112
+ return (0, import_langchain52.createAgent)({
9078
11113
  model: config.model ?? "claude-sonnet-4-5-20250929",
9079
11114
  systemPrompt,
9080
11115
  tools: [],
@@ -9104,7 +11139,7 @@ var TeamAgentGraphBuilder = class {
9104
11139
  const tools = params.tools.map((t) => {
9105
11140
  const toolClient = getToolClient(t.key);
9106
11141
  return toolClient;
9107
- }).filter((tool38) => tool38 !== void 0);
11142
+ }).filter((tool46) => tool46 !== void 0);
9108
11143
  const teammates = params.subAgents.map((sa) => {
9109
11144
  const baseConfig = sa.config;
9110
11145
  return {
@@ -11764,10 +13799,10 @@ var McpLatticeManager = class _McpLatticeManager extends BaseLatticeManager {
11764
13799
  }
11765
13800
  const tools = await this.getAllTools();
11766
13801
  console.log(`[MCP] Registering ${tools.length} tools to Tool Lattice...`);
11767
- for (const tool38 of tools) {
11768
- const toolKey = prefix ? `${prefix}_${tool38.name}` : tool38.name;
11769
- tool38.name = toolKey;
11770
- toolLatticeManager.registerExistingTool(toolKey, tool38);
13802
+ for (const tool46 of tools) {
13803
+ const toolKey = prefix ? `${prefix}_${tool46.name}` : tool46.name;
13804
+ tool46.name = toolKey;
13805
+ toolLatticeManager.registerExistingTool(toolKey, tool46);
11771
13806
  console.log(`[MCP] Registered tool: ${toolKey}`);
11772
13807
  }
11773
13808
  console.log(`[MCP] Successfully registered ${tools.length} tools to Tool Lattice`);
@@ -11852,6 +13887,7 @@ function clearEncryptionKeyCache() {
11852
13887
  ChunkBufferLatticeManager,
11853
13888
  CompositeBackend,
11854
13889
  ConsoleLoggerClient,
13890
+ CustomMetricsClient,
11855
13891
  DefaultScheduleClient,
11856
13892
  EMPTY_CONTENT_WARNING,
11857
13893
  EmbeddingsLatticeManager,
@@ -11863,7 +13899,10 @@ function clearEncryptionKeyCache() {
11863
13899
  InMemoryDatabaseConfigStore,
11864
13900
  InMemoryMailboxStore,
11865
13901
  InMemoryTaskListStore,
13902
+ InMemoryTenantStore,
11866
13903
  InMemoryThreadStore,
13904
+ InMemoryUserStore,
13905
+ InMemoryUserTenantLinkStore,
11867
13906
  LINE_NUMBER_WIDTH,
11868
13907
  LoggerLatticeManager,
11869
13908
  MAX_LINE_LENGTH,
@@ -11874,14 +13913,17 @@ function clearEncryptionKeyCache() {
11874
13913
  MemoryScheduleStorage,
11875
13914
  MemoryType,
11876
13915
  MessageType,
13916
+ MetricsServerManager,
11877
13917
  ModelLatticeManager,
11878
13918
  PinoLoggerClient,
11879
13919
  PostgresDatabase,
13920
+ PrometheusClient,
11880
13921
  Protocols,
11881
13922
  QueueLatticeManager,
11882
13923
  SandboxFilesystem,
11883
13924
  SandboxLatticeManager,
11884
13925
  ScheduleLatticeManager,
13926
+ SemanticMetricsClient,
11885
13927
  SkillLatticeManager,
11886
13928
  SqlDatabaseManager,
11887
13929
  StateBackend,
@@ -11901,9 +13943,16 @@ function clearEncryptionKeyCache() {
11901
13943
  createAgentTeam,
11902
13944
  createFileData,
11903
13945
  createInfoSqlTool,
13946
+ createListMetricsDataSourcesTool,
13947
+ createListMetricsServersTool,
11904
13948
  createListTablesSqlTool,
11905
13949
  createQueryCheckerSqlTool,
13950
+ createQueryMetricDefinitionTool,
13951
+ createQueryMetricsListTool,
13952
+ createQuerySemanticMetricDataTool,
11906
13953
  createQuerySqlTool,
13954
+ createQueryTableDefinitionTool,
13955
+ createQueryTablesListTool,
11907
13956
  createTeamMiddleware,
11908
13957
  createTeammateTools,
11909
13958
  decrypt,
@@ -11949,6 +13998,7 @@ function clearEncryptionKeyCache() {
11949
13998
  isValidSkillName,
11950
13999
  loggerLatticeManager,
11951
14000
  mcpManager,
14001
+ metricsServerManager,
11952
14002
  modelLatticeManager,
11953
14003
  normalizeSandboxName,
11954
14004
  parseCronExpression,