@yarkivaev/scada 2.18.0 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/index.js +13 -0
  2. package/package.json +4 -2
  3. package/src/application/cycleTimelineFetch.js +56 -0
  4. package/src/application/deploy/edgeDescriptors.js +31 -0
  5. package/src/application/deploy/fieldbusSourcePlan.js +79 -0
  6. package/src/application/deploy/plantBindingProfile.js +24 -0
  7. package/src/application/deploy/topologyGraph.js +81 -0
  8. package/src/application/edgeOperatorCatalog.js +9 -7
  9. package/src/application/mcp/analyticsMcpPort.js +20 -0
  10. package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
  11. package/src/application/mcp/analyticsTextContent.js +13 -0
  12. package/src/application/mcp/plantReadPorts.js +168 -0
  13. package/src/application/mcp/textContentCatalog.js +7 -0
  14. package/src/application/operationPrefixes.js +67 -0
  15. package/src/application/operatorCatalogView.js +8 -0
  16. package/src/application/projectPlantShops.js +17 -0
  17. package/src/application/runtime/collectorDslManifest.js +44 -0
  18. package/src/application/runtime/collectorLaunch.js +34 -0
  19. package/src/application/runtime/collectorOptions.js +21 -0
  20. package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
  21. package/src/application/runtime/embeddedCollectors.js +6 -0
  22. package/src/application/runtime/index.js +7 -1
  23. package/src/application/runtime/pagedDelivery.js +87 -0
  24. package/src/application/runtime/resolveSecrets.js +9 -0
  25. package/src/application/siteOperatorCatalog.js +8 -7
  26. package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
  27. package/src/application/siteRuntime/cutoverOperations.js +25 -0
  28. package/src/application/siteRuntime/databaseMigrations.js +27 -0
  29. package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
  30. package/src/application/siteRuntime/history.js +29 -0
  31. package/src/application/siteRuntime/index.js +16 -0
  32. package/src/application/siteRuntime/measurementTopic.js +9 -0
  33. package/src/application/siteRuntime/operationFederation.js +15 -0
  34. package/src/application/siteRuntime/operationSnapshot.js +18 -0
  35. package/src/application/siteRuntime/operatorField.js +49 -0
  36. package/src/application/siteRuntime/operatorUpdates.js +37 -0
  37. package/src/application/siteRuntime/telemetry.js +31 -0
  38. package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
  39. package/src/application/timelineMetrics.js +36 -0
  40. package/src/domain/timeline/cyclePhases.js +191 -0
  41. package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
  42. package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
  43. package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
  44. package/src/infrastructure/deploy/configuredClassification.js +74 -0
  45. package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
  46. package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
  47. package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
  48. package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
  49. package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
  50. package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
  51. package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
  52. package/src/infrastructure/deploy/highAvailability/index.js +1 -0
  53. package/src/infrastructure/deploy/index.js +19 -0
  54. package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
  55. package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
  56. package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
  57. package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
  58. package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
  59. package/src/infrastructure/http/edge/attachClassify.js +30 -0
  60. package/src/infrastructure/http/edge/classifyProxy.js +72 -0
  61. package/src/infrastructure/http/edge/classifyRecord.js +32 -0
  62. package/src/infrastructure/http/edge/classifyRouting.js +14 -0
  63. package/src/infrastructure/http/edge/siteAccess.js +7 -0
  64. package/src/infrastructure/http/edge/writeGuard.js +84 -0
  65. package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
  66. package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
  67. package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
  68. package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
  69. package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
  70. package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
  71. package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
  72. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
  73. package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
  74. package/src/infrastructure/mdmesh/index.js +3 -0
  75. package/src/infrastructure/mdmesh/publishApk.js +30 -0
  76. package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
  77. package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
  78. package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
  79. package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
  80. package/src/infrastructure/streams/boundedTextFrames.js +27 -0
  81. package/src/infrastructure/streams/framedSerialSource.js +25 -0
  82. package/src/infrastructure/streams/index.js +5 -0
  83. package/src/infrastructure/streams/namedSerialDevices.js +26 -0
  84. package/src/infrastructure/streams/serialLine.js +26 -0
  85. package/src/infrastructure/streams/watchCurrentReading.js +31 -0
  86. package/src/infrastructure/streams/windowPublication.js +73 -0
package/index.js CHANGED
@@ -158,3 +158,16 @@ export { default as executeKubeSeed } from './src/infrastructure/deploy/executeK
158
158
  export { default as edgeTelemetryRuntime } from './src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js';
159
159
  export { default as kubeServiceAccount } from './src/infrastructure/management/kubeServiceAccount.js';
160
160
  export * from './src/infrastructure/deploy/index.js';
161
+ export { default as plantReadPorts } from './src/application/mcp/plantReadPorts.js';
162
+ export { default as analyticsMcpPort } from './src/application/mcp/analyticsMcpPort.js';
163
+ export { default as analyticsNamespaceNodes } from './src/application/mcp/analyticsNamespaceNodes.js';
164
+ export { default as analyticsTextContent } from './src/application/mcp/analyticsTextContent.js';
165
+ export { modbusFloat } from './src/infrastructure/ingest/mqtt/registerPoint.js';
166
+ export { default as cyclePrior } from './src/infrastructure/persistence/pg/cyclePrior.js';
167
+ export { default as cyclePhaseQuery } from './src/infrastructure/persistence/pg/cyclePhaseQuery.js';
168
+ export { default as operationPrefixes } from './src/application/operationPrefixes.js';
169
+ export { default as cyclePhases } from './src/domain/timeline/cyclePhases.js';
170
+ export { default as cycleTimelineFetch } from './src/application/cycleTimelineFetch.js';
171
+ export { default as textContentCatalog } from './src/application/mcp/textContentCatalog.js';
172
+ export { timelineSegments, measurementBounds, measurementPeaks } from './src/application/timelineMetrics.js';
173
+ export { default as projectPlantShops } from './src/application/projectPlantShops.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.18.0",
3
+ "version": "2.19.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,7 +23,9 @@
23
23
  "./control": "./src/application/control/index.js",
24
24
  "./mdmesh": "./src/infrastructure/mdmesh/index.js",
25
25
  "./deployment": "./src/infrastructure/deploy/index.js",
26
- "./deployment/high-availability": "./src/infrastructure/deploy/highAvailability/index.js"
26
+ "./deployment/high-availability": "./src/infrastructure/deploy/highAvailability/index.js",
27
+ "./site/runtime": "./src/application/siteRuntime/index.js",
28
+ "./http/site-access": "./src/infrastructure/http/edge/siteAccess.js"
27
29
  },
28
30
  "bin": {
29
31
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Sorts timeline rows by start time ascending.
3
+ *
4
+ * @param {object} leftRow - left timeline row
5
+ * @param {object} rightRow - right timeline row
6
+ * @returns {number} sort order
7
+ */
8
+ function sortByStartTime(leftRow, rightRow) {
9
+ return leftRow.start_time.getTime() - rightRow.start_time.getTime();
10
+ }
11
+
12
+ /**
13
+ * Merges timeline rows by start time without duplicates.
14
+ *
15
+ * @param {Array<object>} left - first timeline row batch
16
+ * @param {Array<object>} right - second timeline row batch
17
+ * @returns {Array<object>} sorted unique rows
18
+ */
19
+ function mergeSegmentRows(left, right) {
20
+ const seen = new Set();
21
+ const merged = [];
22
+ const all = left.concat(right);
23
+ all.sort(sortByStartTime);
24
+ for (let index = 0; index < all.length; index += 1) {
25
+ const row = all[index];
26
+ const key = row.start_time.toISOString();
27
+ if (!seen.has(key)) {
28
+ seen.add(key);
29
+ merged.push(row);
30
+ }
31
+ }
32
+ return merged;
33
+ }
34
+
35
+ /**
36
+ * Loads timeline rows needed to derive cycles intersecting a query window.
37
+ *
38
+ * @param {object} timeline - machine timeline with list method
39
+ * @param {object} range - query window with from and to Date values
40
+ * @returns {Promise<Array<object>>} rows spanning cycle anchors before from
41
+ *
42
+ * @example
43
+ * const rows = await cycleTimelineFetch(machine.timeline, { from, to });
44
+ */
45
+ export default async function cycleTimelineFetch(timeline, range, lookbackMs) {
46
+ const lookbackFrom = new Date(range.from.getTime() - lookbackMs);
47
+ const beforeRows = await timeline.list({
48
+ from: lookbackFrom.toISOString(),
49
+ to: range.from.toISOString()
50
+ });
51
+ const windowRows = await timeline.list({
52
+ from: range.from.toISOString(),
53
+ to: range.to.toISOString()
54
+ });
55
+ return mergeSegmentRows(beforeRows, windowRows);
56
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Edge machine list from EDGE_MACHINES or the plant profile.
3
+ *
4
+ * @example
5
+ * const rows = edgeDescriptors(process.env, profile);
6
+ *
7
+ * @param {object} env - process environment
8
+ * @param {{ machines: function(): Array }} profile - plant profile
9
+ * @returns {Array<{device: string, id: string, shop?: string, kind?: string}>}
10
+ */
11
+ export default function edgeDescriptors(env, profile) {
12
+ const raw = env.EDGE_MACHINES;
13
+ if (typeof raw === 'string' && raw.length > 0) {
14
+ return JSON.parse(raw).map((entry) => {
15
+ return {
16
+ device: entry.device,
17
+ id: entry.id,
18
+ shop: entry.shop,
19
+ kind: entry.kind
20
+ };
21
+ });
22
+ }
23
+ return profile.machines().map((entry) => {
24
+ return {
25
+ device: entry.device,
26
+ id: entry.machine,
27
+ shop: entry.shop,
28
+ kind: entry.kind
29
+ };
30
+ });
31
+ }
@@ -0,0 +1,79 @@
1
+ import { parseSerialSource } from './collectorSourcePlan.js';
2
+
3
+ function registerOrigin(address) {
4
+ const text = new URL(address).searchParams.get('at');
5
+ if (text === null) { return undefined; }
6
+ const origin = parseInt(text, 10);
7
+ if (Number.isNaN(origin)) { throw new Error(`Address at must be a number, got: ${text}`); }
8
+ return origin;
9
+ }
10
+
11
+ function holdingPoint(value, address, profiles) {
12
+ const channel = String(value);
13
+ if (channel.startsWith('holding:')) { return channel; }
14
+ const origin = registerOrigin(address);
15
+ for (const profile of profiles) {
16
+ const entry = profile.layout.find((row) => { return row.channel === channel; });
17
+ if (entry) { return `holding:${(origin ?? profile.origin) + entry.offset}:${profile.order}`; }
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function registerMap(mapping, address, profiles) {
23
+ const next = {};
24
+ for (const [key, value] of Object.entries(mapping || {})) {
25
+ const point = holdingPoint(value, address, profiles);
26
+ if (point === null) { return null; }
27
+ next[key] = point;
28
+ }
29
+ return next;
30
+ }
31
+
32
+ /** Convert named device channels into portable holding points using declared register profiles. */
33
+ export function projectRegisterMaps(maps, addresses, profiles) {
34
+ if (!Array.isArray(maps) || !Array.isArray(addresses) || maps.length !== addresses.length) { return null; }
35
+ const rows = maps.map((mapping, index) => { return registerMap(mapping, addresses[index], profiles); });
36
+ return rows.includes(null) ? null : rows;
37
+ }
38
+
39
+ /** Validate the ordered RTU sources sharing one serial port and register window. */
40
+ export function sharedRegisterBus(rows, { label, count }) {
41
+ const ports = rows.map(({ from }) => { return parseSerialSource(from); });
42
+ const [first] = ports;
43
+ if (!first) { throw new TypeError(`${label} requires at least one serial source`); }
44
+ if (new Set(ports.map(({ slave }) => { return slave; })).size !== ports.length) {
45
+ throw new Error('duplicate Modbus slave address');
46
+ }
47
+ const at = first.query.get('at');
48
+ const size = first.query.get('count');
49
+ if (!/^\d+$/u.test(at || '') || size !== String(count)) {
50
+ throw new Error(`${label} requires a numeric address and ${count} registers`);
51
+ }
52
+ if (ports.some(({ path, baud, line, query, slave }) => {
53
+ return path !== first.path || baud !== first.baud || line !== first.line || query.toString() !== first.query.toString() || !slave;
54
+ })) { throw new Error(`${label} sources must share one serial bus and register range`); }
55
+ return { at, count: size, ports };
56
+ }
57
+
58
+ /** Validate independent raw serial inputs and produce the runtime's device-list ABI. */
59
+ export function rawSerialDeviceList(rows, { label, name }) {
60
+ const ports = rows.map(({ from }) => { return parseSerialSource(from); });
61
+ if (new Set(ports.map(({ path }) => { return path; })).size !== ports.length) {
62
+ throw new Error(`duplicate ${label} port`);
63
+ }
64
+ if (ports.some(({ slave, query }) => { return slave || query.toString(); })) {
65
+ throw new Error(`${label} serial sources cannot specify a Modbus slave or register range`);
66
+ }
67
+ return ports.map(({ path, baud, line }, index) => { return `${name(rows[index])}:${path}:${baud}:${line}`; }).join(',');
68
+ }
69
+
70
+ /** Group stream URLs by database endpoint in source order, ignoring URL query selectors. */
71
+ export function databaseSourceGroups(rows, { port, identity }) {
72
+ const sources = new Map();
73
+ rows.forEach(({ from }) => {
74
+ const address = new URL(from);
75
+ const source = { host: address.hostname, port: Number(address.port || port), database: address.pathname.slice(1), ...identity };
76
+ sources.set(JSON.stringify(source), source);
77
+ });
78
+ return [...sources.values()];
79
+ }
@@ -0,0 +1,24 @@
1
+ function taxonomy(declarations) {
2
+ return Object.freeze(Object.fromEntries(Object.entries(declarations).map(([section, value]) => {
3
+ const declared = Array.isArray(value) ? Object.freeze([...value]) : value;
4
+ return [section, () => { return declared; }];
5
+ })));
6
+ }
7
+
8
+ /** Combine an installation's topology, taxonomy and application-supplied integrations. */
9
+ export default function plantBindingProfile({ topology, taxonomy: declarations, integrations }) {
10
+ return function profile() {
11
+ const layout = topology();
12
+ const tags = taxonomy(declarations);
13
+ const links = integrations();
14
+ return Object.freeze({
15
+ name() { return layout.plant; },
16
+ topology() { return layout; },
17
+ taxonomy() { return tags; },
18
+ integrations() { return links; },
19
+ machines() {
20
+ return layout.machines.map(({ device, id: machine, shop, kind }) => { return Object.freeze({ device, machine, shop, kind }); });
21
+ }
22
+ });
23
+ };
24
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Project the configured topology onto the SCADA graph contract.
3
+ *
4
+ * @param {object} layout - layout
5
+ * @param {string} [version] - optional package or env version
6
+ * @returns {object} { plant, nodes, links }
7
+ *
8
+ * @example
9
+ * topologyGraph(layout);
10
+ */
11
+ function shopNodes(layout) {
12
+ return layout.shops.map((area) => {
13
+ return { id: area.id, kind: 'shop', title: area.label, status: 'unknown' };
14
+ });
15
+ }
16
+
17
+ function machineNode(entry) {
18
+ const node = {
19
+ id: entry.id,
20
+ kind: 'machine',
21
+ title: entry.label,
22
+ parent: entry.shop,
23
+ status: 'unknown'
24
+ };
25
+ if (entry.inspect) {
26
+ node.inspect = entry.inspect;
27
+ }
28
+ return node;
29
+ }
30
+
31
+ function sensorNodes(entry) {
32
+ if (!entry.sensors) {
33
+ return { nodes: [], links: [] };
34
+ }
35
+ const nodes = [];
36
+ const links = [];
37
+ Object.keys(entry.sensors).forEach((key) => {
38
+ const id = `${entry.id}-${key}`;
39
+ nodes.push({ id, kind: 'collector', title: key, parent: entry.id, status: 'unknown' });
40
+ links.push({ from: entry.id, to: id, kind: 'contains' });
41
+ });
42
+ return { nodes, links };
43
+ }
44
+
45
+ function collectorNodes(layout) {
46
+ const nodes = [];
47
+ const links = [];
48
+ (layout.collectors || []).forEach((item) => {
49
+ nodes.push({
50
+ id: item.id,
51
+ kind: 'collector',
52
+ title: item.title,
53
+ parent: item.shop,
54
+ status: 'unknown'
55
+ });
56
+ item.feeds.forEach((machineId) => {
57
+ links.push({ from: item.id, to: machineId, kind: 'feeds' });
58
+ });
59
+ });
60
+ return { nodes, links };
61
+ }
62
+
63
+ export default function topologyGraph(layout, version) {
64
+ const plant = { id: layout.plant, title: layout.title };
65
+ if (version) {
66
+ plant.version = version;
67
+ }
68
+ const nodes = [...shopNodes(layout)];
69
+ const links = [];
70
+ layout.machines.forEach((entry) => {
71
+ nodes.push(machineNode(entry));
72
+ links.push({ from: entry.shop, to: entry.id, kind: 'contains' });
73
+ const nested = sensorNodes(entry);
74
+ nodes.push(...nested.nodes);
75
+ links.push(...nested.links);
76
+ });
77
+ const extra = collectorNodes(layout);
78
+ nodes.push(...extra.nodes);
79
+ links.push(...extra.links);
80
+ return { plant, nodes, links };
81
+ }
@@ -3,7 +3,8 @@ import centralOperators from '../infrastructure/operators/centralOperators.js';
3
3
  import operatorsSync from '../infrastructure/operators/operatorsSync.js';
4
4
  import edgeOperators from '../infrastructure/operators/edgeOperators.js';
5
5
  import stateHttpClient from '../infrastructure/http/edge/stateHttpClient.js';
6
- import operatorRoute from '../infrastructure/http/plant/routes/operatorRoute.js';
6
+ import operatorCatalogView from './operatorCatalogView.js';
7
+ import { centralOperatorsUpdate, edgeOperatorsUpdate } from './siteRuntime/operatorUpdates.js';
7
8
 
8
9
  const DEFAULT_SYNC_INTERVAL_SEC = 30;
9
10
 
@@ -27,19 +28,20 @@ function syncIntervalMs(env) {
27
28
  * @example
28
29
  * edgeOperatorCatalog('/api/v1', process.env);
29
30
  */
30
- export default function edgeOperatorCatalog(basePath, env) {
31
+ export default function edgeOperatorCatalog(basePath, env, { update = false, ...extensions } = {}) {
31
32
  const cache = operators();
33
+ const createProvider = update ? edgeOperatorsUpdate : edgeOperators;
34
+ const createSource = update ? centralOperatorsUpdate : centralOperators;
32
35
  const centralUrl = env.CENTRAL_PLANT_URL;
33
36
  if (!centralUrl) {
34
- const provider = edgeOperators(cache, undefined);
35
- return { routes: operatorRoute(basePath, provider), sync: undefined, provider };
37
+ return { ...operatorCatalogView(basePath, createProvider(cache), extensions), sync: undefined };
36
38
  }
37
39
  const client = stateHttpClient({
38
40
  baseUrl: centralUrl,
39
41
  token: env.CENTRAL_PLANT_TOKEN
40
42
  });
41
- const source = centralOperators(client, basePath);
42
- const provider = edgeOperators(cache, source);
43
+ const source = createSource(client, basePath);
44
+ const provider = createProvider(cache, source);
43
45
  const sync = operatorsSync(source, cache, { intervalMs: syncIntervalMs(env) });
44
- return { routes: operatorRoute(basePath, provider), sync, provider };
46
+ return { ...operatorCatalogView(basePath, provider, extensions), sync };
45
47
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Picks the HTTP port for the analytics MCP process.
3
+ *
4
+ * ANALYTICS_MCP_PORT wins. PORT is the infra fallback. Default is 3100.
5
+ *
6
+ * @param {NodeJS.ProcessEnv} env - process environment
7
+ * @returns {number} listen port
8
+ *
9
+ * @example
10
+ * analyticsMcpPort({ ANALYTICS_MCP_PORT: '3100' });
11
+ */
12
+ export default function analyticsMcpPort(env) {
13
+ if (env.ANALYTICS_MCP_PORT) {
14
+ return Number(env.ANALYTICS_MCP_PORT);
15
+ }
16
+ if (env.PORT) {
17
+ return Number(env.PORT);
18
+ }
19
+ return 3100;
20
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Maps a deployment namespace projection to the analytics namespace tree.
3
+ *
4
+ * Plant data uses `silence` and `binding.topic`. The library wants
5
+ * `silenceSeconds` and `source`.
6
+ *
7
+ * @param {ReadonlyArray<object>} nodes - namespace() result
8
+ * @returns {Array<object>} nodes for namespaceTree
9
+ *
10
+ * @example
11
+ * analyticsNamespaceNodes(namespace())[0].silenceSeconds;
12
+ */
13
+ export default function analyticsNamespaceNodes(nodes) {
14
+ return nodes.map((node) => {
15
+ const mapped = {
16
+ kind: node.kind,
17
+ path: node.path,
18
+ silenceSeconds: node.silence,
19
+ title: node.title
20
+ };
21
+ if (node.binding && typeof node.binding.topic === 'string') {
22
+ mapped.source = node.binding.topic;
23
+ }
24
+ if (node.binding && typeof node.binding.unit === 'string') {
25
+ mapped.unit = node.binding.unit;
26
+ }
27
+ return mapped;
28
+ });
29
+ }
@@ -0,0 +1,13 @@
1
+ /** Register configured text resources and prompts with the analytics server. */
2
+ export default function analyticsTextContent(server, { resources = [], prompts = [] }) {
3
+ resources.forEach(({ name, uri, description, text }) => {
4
+ server.registerResource(name, uri, { description, mimeType: 'text/plain' }, () => {
5
+ return { contents: [{ mimeType: 'text/plain', text, uri }] };
6
+ });
7
+ });
8
+ prompts.forEach(({ name, text }) => {
9
+ server.registerPrompt(name, { description: text }, () => {
10
+ return { messages: [{ content: { text, type: 'text' }, role: 'user' }] };
11
+ });
12
+ });
13
+ }
@@ -0,0 +1,168 @@
1
+ import loadSeries from './loadMetricSeries.js';
2
+ import locate from './locateMachineMetric.js';
3
+
4
+ /**
5
+ * Reads measurements for every requested path.
6
+ *
7
+ * @param {object} plant - plant hierarchy
8
+ * @param {object} args - paths, from, to, step, mode
9
+ * @returns {Promise<object>} points payload
10
+ *
11
+ * @example
12
+ * readMeasurements(plant, { paths: ['site/unit/power'], from, to, step: 60 });
13
+ */
14
+ function readMeasurements(plant, args) {
15
+ const jobs = args.paths.map((path) => {
16
+ return loadSeries(plant, path, args);
17
+ });
18
+ return Promise.all(jobs).then((lists) => {
19
+ return { points: lists.flat() };
20
+ });
21
+ }
22
+
23
+ /**
24
+ * Reads timeline segments for the machine on a path.
25
+ *
26
+ * @param {object} plant - plant hierarchy
27
+ * @param {object} args - path, from, to, kinds
28
+ * @returns {Promise<Array>} segment rows
29
+ *
30
+ * @example
31
+ * readSegments(plant, { path: 'site/unit', from, to });
32
+ */
33
+ async function readSegments(plant, args) {
34
+ const { machine } = locate(plant, args.path);
35
+ if (!machine.timeline || typeof machine.timeline.list !== 'function') {
36
+ return [];
37
+ }
38
+ const rows = await machine.timeline.list({ from: args.from, to: args.to });
39
+ if (!args.kinds) {
40
+ return rows;
41
+ }
42
+ return rows.filter((row) => {
43
+ return args.kinds.includes(row.kind || row.name);
44
+ });
45
+ }
46
+
47
+ /**
48
+ * Reads operations for the machine on a path.
49
+ *
50
+ * @param {object} plant - plant hierarchy
51
+ * @param {object} args - path, kind, from, to
52
+ * @returns {Promise<Array>} operation rows
53
+ *
54
+ * @example
55
+ * readOperations(plant, { path: 'site/unit', kind: 'bath', from, to });
56
+ */
57
+ function readOperations(plant, args) {
58
+ const { machine } = locate(plant, args.path);
59
+ if (!plant.operations || typeof plant.operations.listForMachine !== 'function') {
60
+ return Promise.resolve([]);
61
+ }
62
+ return plant.operations.listForMachine(machine.name(), args.kind, {
63
+ from: args.from,
64
+ to: args.to
65
+ });
66
+ }
67
+
68
+ /**
69
+ * Reads alerts for the machine on a path.
70
+ *
71
+ * @param {object} plant - plant hierarchy
72
+ * @param {object} args - path, from, to
73
+ * @returns {Promise<Array>|Array} alert rows
74
+ *
75
+ * @example
76
+ * readAlerts(plant, { path: 'site/unit', from, to });
77
+ */
78
+ function readAlerts(plant, args) {
79
+ const { machine } = locate(plant, args.path);
80
+ if (plant.alerts && typeof plant.alerts.list === 'function') {
81
+ return plant.alerts.list({
82
+ from: args.from,
83
+ machine: machine.name(),
84
+ to: args.to
85
+ });
86
+ }
87
+ const start = Date.parse(args.from);
88
+ const stop = Date.parse(args.to);
89
+ return machine.alerts().filter((item) => {
90
+ const at = item.timestamp instanceof Date ? item.timestamp.getTime() : Date.parse(item.timestamp);
91
+ return at >= start && at <= stop;
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Reads latest values under a path.
97
+ *
98
+ * @param {object} plant - plant hierarchy
99
+ * @param {object} args - path
100
+ * @returns {Promise<object>} state payload
101
+ *
102
+ * @example
103
+ * readState(plant, { path: 'site/unit/power' });
104
+ */
105
+ async function readState(plant, args) {
106
+ const found = locate(plant, args.path);
107
+ if (found.metric && found.machine.sensors[found.metric]) {
108
+ const row = await found.machine.sensors[found.metric].current();
109
+ if (!row.found) {
110
+ return { found: false };
111
+ }
112
+ return {
113
+ found: true,
114
+ time: row.timestamp.toISOString(),
115
+ unit: row.unit,
116
+ value: row.value
117
+ };
118
+ }
119
+ const keys = Object.keys(found.machine.sensors || {});
120
+ const items = await Promise.all(keys.map(async (key) => {
121
+ const row = await found.machine.sensors[key].current();
122
+ return { found: row.found === true, key, time: row.timestamp && row.timestamp.toISOString(), value: row.value };
123
+ }));
124
+ return { items };
125
+ }
126
+
127
+ /**
128
+ * Builds named-tool ports over a plant and optional SQL extras.
129
+ *
130
+ * @param {object} plant - plant hierarchy
131
+ * @param {object} extras - cursor, queryClickhouse, optional queryPostgres
132
+ * @returns {object} analyticsMcp ports
133
+ *
134
+ * @example
135
+ * plantReadPorts(plant, { cursor, queryClickhouse });
136
+ */
137
+ export default function plantReadPorts(plant, extras) {
138
+ const ports = {
139
+ alerts(args) {
140
+ return readAlerts(plant, args);
141
+ },
142
+ cursor(args) {
143
+ return extras.cursor(args);
144
+ },
145
+ measurements(args) {
146
+ return readMeasurements(plant, args);
147
+ },
148
+ operations(args) {
149
+ return readOperations(plant, args);
150
+ },
151
+ queryClickhouse(sql) {
152
+ return extras.queryClickhouse(sql);
153
+ },
154
+ samples(args) {
155
+ return loadSeries(plant, args.path, { from: args.from, mode: 'samples', to: args.to });
156
+ },
157
+ segments(args) {
158
+ return readSegments(plant, args);
159
+ },
160
+ state(args) {
161
+ return readState(plant, args);
162
+ }
163
+ };
164
+ if (typeof extras.queryPostgres === 'function') {
165
+ ports.queryPostgres = extras.queryPostgres;
166
+ }
167
+ return ports;
168
+ }
@@ -0,0 +1,7 @@
1
+ /** Build immutable text and prompt declarations for an analytics adapter. */
2
+ export default function textContentCatalog(policy, payload) {
3
+ return Object.freeze({
4
+ prompts: Object.freeze(policy.prompts.map((prompt) => { return Object.freeze({ ...prompt }); })),
5
+ [policy.resource.key]: Object.freeze({ uri: policy.resource.uri, text: `${policy.resource.heading} ${JSON.stringify(payload)}` })
6
+ });
7
+ }
@@ -0,0 +1,67 @@
1
+ function changedRows(rows, { fold, field, initial }) {
2
+ let prefix = initial;
3
+ const updates = [];
4
+ for (const row of rows) {
5
+ prefix = fold(prefix, row);
6
+ if (row.payload?.[field] !== prefix) {
7
+ const { machine, occurred_at: occurredAt, kind, key } = row;
8
+ updates.push({ machine, occurred_at: occurredAt, kind, key, payload: { ...row.payload, [field]: prefix } });
9
+ }
10
+ }
11
+ return updates;
12
+ }
13
+
14
+ function forEachInOrder(items, apply) {
15
+ return items.reduce((chain, item) => { return chain.then(() => { return apply(item); }); }, Promise.resolve());
16
+ }
17
+
18
+ function port(store, kind, recompute, ensure) {
19
+ if (!store || typeof store.upsert !== 'function') { throw new Error('Operations port must have an upsert() method'); }
20
+ return {
21
+ listForMachine(...args) { return store.listForMachine(...args); },
22
+ latestForMachine(...args) {
23
+ if (typeof store.latestForMachine !== 'function') { throw new Error('Operations port must have a latestForMachine() method'); }
24
+ return store.latestForMachine(...args);
25
+ },
26
+ stream: store.stream,
27
+ get(...args) { return store.get(...args); },
28
+ ensure(machineIds) { return ensure(store, machineIds); },
29
+ async upsert(item) {
30
+ await store.upsert(item);
31
+ if (item.kind === kind) { await recompute(store, item.machine); }
32
+ },
33
+ async upsertMany(items) {
34
+ if (typeof store.upsertMany !== 'function') { throw new Error('Operations port must have an upsertMany() method'); }
35
+ await store.upsertMany(items);
36
+ const machines = [...new Set(items.filter((item) => { return item.kind === kind; }).map((item) => { return item.machine; }))];
37
+ await forEachInOrder(machines, (id) => { return recompute(store, id); });
38
+ },
39
+ async remove(machineId, key) {
40
+ const removed = await store.remove(machineId, key);
41
+ if (removed.kind === kind) { await recompute(store, machineId); }
42
+ return removed;
43
+ }
44
+ };
45
+ }
46
+
47
+ /** Persist a running prefix over one operation kind, using the application's fold. */
48
+ export default function operationPrefixes({ kind, field, fold, initial = 0, present = (value) => { return typeof value === 'number'; } }) {
49
+ async function recompute(store, machine) {
50
+ const rows = await store.listForMachine(machine, kind, {});
51
+ const updates = changedRows(rows, { fold, field, initial });
52
+ await forEachInOrder(updates, (item) => { return store.upsert(item); });
53
+ return updates.length;
54
+ }
55
+ async function ensure(store, machineIds) {
56
+ let recomputed = 0;
57
+ await forEachInOrder(machineIds || [], async (id) => {
58
+ const latest = await store.latestForMachine(id, kind, { to: new Date() });
59
+ if (latest && !present(latest.payload?.[field])) {
60
+ await recompute(store, id);
61
+ recomputed += 1;
62
+ }
63
+ });
64
+ return recomputed;
65
+ }
66
+ return { recompute, ensure, wrap(store) { return port(store, kind, recompute, ensure); } };
67
+ }
@@ -0,0 +1,8 @@
1
+ import operatorRoute from '../infrastructure/http/plant/routes/operatorRoute.js';
2
+
3
+ /** Compose shared operator endpoints with optional installation fields and routes. */
4
+ export default function operatorCatalogView(basePath, provider, { decorate, extraRoutes } = {}) {
5
+ const selected = decorate ? decorate(provider) : provider;
6
+ const routes = [...operatorRoute(basePath, selected), ...(extraRoutes?.(basePath, selected) ?? [])];
7
+ return { provider: selected, routes };
8
+ }