@camstack/core 0.1.14 → 0.1.15
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/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +220 -0
- package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js.map +1 -0
- package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +9 -0
- package/dist/builtins/addon-pages-aggregator/index.js +222 -0
- package/dist/builtins/addon-pages-aggregator/index.js.map +1 -0
- package/dist/builtins/addon-pages-aggregator/index.mjs +9 -0
- package/dist/builtins/addon-pages-aggregator/index.mjs.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +200 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +9 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/index.js +202 -0
- package/dist/builtins/addon-widgets-aggregator/index.js.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/index.mjs +9 -0
- package/dist/builtins/addon-widgets-aggregator/index.mjs.map +1 -0
- package/dist/builtins/alerts/alerts.addon.js +443 -0
- package/dist/builtins/alerts/alerts.addon.js.map +1 -0
- package/dist/builtins/alerts/alerts.addon.mjs +9 -0
- package/dist/builtins/alerts/alerts.addon.mjs.map +1 -0
- package/dist/builtins/alerts/index.js +443 -0
- package/dist/builtins/alerts/index.js.map +1 -0
- package/dist/builtins/alerts/index.mjs +8 -0
- package/dist/builtins/alerts/index.mjs.map +1 -0
- package/dist/builtins/console-logging/index.js +242 -0
- package/dist/builtins/console-logging/index.js.map +1 -0
- package/dist/builtins/console-logging/index.mjs +11 -0
- package/dist/builtins/console-logging/index.mjs.map +1 -0
- package/dist/builtins/device-manager/device-manager.addon.js +2155 -0
- package/dist/builtins/device-manager/device-manager.addon.js.map +1 -0
- package/dist/builtins/device-manager/device-manager.addon.mjs +9 -0
- package/dist/builtins/device-manager/device-manager.addon.mjs.map +1 -0
- package/dist/builtins/device-manager/index.js +2157 -0
- package/dist/builtins/device-manager/index.js.map +1 -0
- package/dist/builtins/device-manager/index.mjs +10 -0
- package/dist/builtins/device-manager/index.mjs.map +1 -0
- package/dist/builtins/hub-forwarder/index.js +297 -0
- package/dist/builtins/hub-forwarder/index.js.map +1 -0
- package/dist/builtins/hub-forwarder/index.mjs +11 -0
- package/dist/builtins/hub-forwarder/index.mjs.map +1 -0
- package/dist/builtins/local-auth/index.js +623 -0
- package/dist/builtins/local-auth/index.js.map +1 -0
- package/dist/builtins/local-auth/index.mjs +8 -0
- package/dist/builtins/local-auth/index.mjs.map +1 -0
- package/dist/builtins/local-auth/local-auth.addon.js +623 -0
- package/dist/builtins/local-auth/local-auth.addon.js.map +1 -0
- package/dist/builtins/local-auth/local-auth.addon.mjs +9 -0
- package/dist/builtins/local-auth/local-auth.addon.mjs.map +1 -0
- package/dist/builtins/local-backup/index.js +53 -68
- package/dist/builtins/local-backup/index.js.map +1 -1
- package/dist/builtins/local-backup/index.mjs +1 -1
- package/dist/builtins/native-metrics/native-metrics.addon.js +898 -0
- package/dist/builtins/native-metrics/native-metrics.addon.js.map +1 -0
- package/dist/builtins/native-metrics/native-metrics.addon.mjs +7 -0
- package/dist/builtins/native-metrics/native-metrics.addon.mjs.map +1 -0
- package/dist/builtins/snapshot/index.js +504 -0
- package/dist/builtins/snapshot/index.js.map +1 -0
- package/dist/builtins/snapshot/index.mjs +477 -0
- package/dist/builtins/snapshot/index.mjs.map +1 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +16 -166
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.js.map +1 -1
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
- package/dist/builtins/sqlite-storage/index.js +554 -621
- package/dist/builtins/sqlite-storage/index.js.map +1 -1
- package/dist/builtins/sqlite-storage/index.mjs +9 -11
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +368 -130
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.js.map +1 -1
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +1 -1
- package/dist/builtins/system-config/index.js +189 -0
- package/dist/builtins/system-config/index.js.map +1 -0
- package/dist/builtins/system-config/index.mjs +10 -0
- package/dist/builtins/system-config/index.mjs.map +1 -0
- package/dist/builtins/system-config/system-config.addon.js +187 -0
- package/dist/builtins/system-config/system-config.addon.js.map +1 -0
- package/dist/builtins/system-config/system-config.addon.mjs +9 -0
- package/dist/builtins/system-config/system-config.addon.mjs.map +1 -0
- package/dist/builtins/winston-logging/index.js +185 -65
- package/dist/builtins/winston-logging/index.js.map +1 -1
- package/dist/builtins/winston-logging/index.mjs +2 -1
- package/dist/chunk-2CIYKDRN.mjs +1 -0
- package/dist/chunk-2CIYKDRN.mjs.map +1 -0
- package/dist/chunk-2F76X6NL.mjs +136 -0
- package/dist/chunk-2F76X6NL.mjs.map +1 -0
- package/dist/chunk-2QUFBZ7M.mjs +1 -0
- package/dist/chunk-2QUFBZ7M.mjs.map +1 -0
- package/dist/chunk-3BK2Y7GY.mjs +593 -0
- package/dist/chunk-3BK2Y7GY.mjs.map +1 -0
- package/dist/chunk-4OOHFJHT.mjs +421 -0
- package/dist/chunk-4OOHFJHT.mjs.map +1 -0
- package/dist/chunk-4XHB7IHT.mjs +809 -0
- package/dist/chunk-4XHB7IHT.mjs.map +1 -0
- package/dist/{chunk-2F3XZYRW.mjs → chunk-6M2HSSTQ.mjs} +16 -7
- package/dist/chunk-6M2HSSTQ.mjs.map +1 -0
- package/dist/{chunk-SO4LROOT.mjs → chunk-7FI7SQS7.mjs} +54 -69
- package/dist/chunk-7FI7SQS7.mjs.map +1 -0
- package/dist/chunk-ED57RCQE.mjs +171 -0
- package/dist/chunk-ED57RCQE.mjs.map +1 -0
- package/dist/chunk-FZN56HGQ.mjs +626 -0
- package/dist/chunk-FZN56HGQ.mjs.map +1 -0
- package/dist/chunk-GL4OOB25.mjs +51 -0
- package/dist/chunk-GL4OOB25.mjs.map +1 -0
- package/dist/chunk-KDG2NTDB.mjs +137 -0
- package/dist/chunk-KDG2NTDB.mjs.map +1 -0
- package/dist/chunk-NRBQWBDM.mjs +191 -0
- package/dist/chunk-NRBQWBDM.mjs.map +1 -0
- package/dist/chunk-O4V246GG.mjs +2137 -0
- package/dist/chunk-O4V246GG.mjs.map +1 -0
- package/dist/chunk-QT57H266.mjs +163 -0
- package/dist/chunk-QT57H266.mjs.map +1 -0
- package/dist/chunk-QX4RH25I.mjs +141 -0
- package/dist/chunk-QX4RH25I.mjs.map +1 -0
- package/dist/chunk-TB562PZX.mjs +86 -0
- package/dist/chunk-TB562PZX.mjs.map +1 -0
- package/dist/chunk-TDYPZXK5.mjs +1 -0
- package/dist/chunk-TDYPZXK5.mjs.map +1 -0
- package/dist/chunk-UJI4LN5P.mjs +36 -0
- package/dist/chunk-UJI4LN5P.mjs.map +1 -0
- package/dist/chunk-W6RTHQGP.mjs +1 -0
- package/dist/chunk-W6RTHQGP.mjs.map +1 -0
- package/dist/chunk-ZELBCPDC.mjs +369 -0
- package/dist/chunk-ZELBCPDC.mjs.map +1 -0
- package/dist/index.d.mts +1103 -544
- package/dist/index.d.ts +1103 -544
- package/dist/index.js +7032 -6033
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +568 -2226
- package/dist/index.mjs.map +1 -1
- package/dist/resource-monitor-UZUGPIAU.mjs +9 -0
- package/dist/resource-monitor-UZUGPIAU.mjs.map +1 -0
- package/dist/storage-location-manager-HFNB3PCS.mjs +7 -0
- package/dist/storage-location-manager-HFNB3PCS.mjs.map +1 -0
- package/package.json +123 -2
- package/dist/builtins/local-backup/index.d.mts +0 -42
- package/dist/builtins/local-backup/index.d.ts +0 -42
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.mts +0 -2
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.ts +0 -2
- package/dist/builtins/sqlite-storage/index.d.mts +0 -4
- package/dist/builtins/sqlite-storage/index.d.ts +0 -4
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.mts +0 -2
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.ts +0 -2
- package/dist/builtins/winston-logging/index.d.mts +0 -30
- package/dist/builtins/winston-logging/index.d.ts +0 -30
- package/dist/chunk-2F3XZYRW.mjs.map +0 -1
- package/dist/chunk-LQFPAEQF.mjs +0 -147
- package/dist/chunk-LQFPAEQF.mjs.map +0 -1
- package/dist/chunk-R3DIIBBX.mjs +0 -532
- package/dist/chunk-R3DIIBBX.mjs.map +0 -1
- package/dist/chunk-SMNR44VG.mjs +0 -386
- package/dist/chunk-SMNR44VG.mjs.map +0 -1
- package/dist/chunk-SO4LROOT.mjs.map +0 -1
- package/dist/chunk-SPA4JBKN.mjs +0 -175
- package/dist/chunk-SPA4JBKN.mjs.map +0 -1
- package/dist/dist-3BY63UQ5.mjs +0 -2151
- package/dist/dist-3BY63UQ5.mjs.map +0 -1
- package/dist/filesystem-storage.addon-C42r589X.d.mts +0 -57
- package/dist/filesystem-storage.addon-C42r589X.d.ts +0 -57
- package/dist/sql-schema-CKz78rId.d.mts +0 -97
- package/dist/sql-schema-CKz78rId.d.ts +0 -97
- package/dist/sqlite-settings.addon-KwG-uKMP.d.mts +0 -79
- package/dist/sqlite-settings.addon-KwG-uKMP.d.ts +0 -79
- package/dist/storage-location-manager-KKDQNAKA.mjs +0 -7
- /package/dist/{storage-location-manager-KKDQNAKA.mjs.map → builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs.map} +0 -0
|
@@ -0,0 +1,898 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res) => function __init() {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
15
|
+
var __copyProps = (to, from, except, desc) => {
|
|
16
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
17
|
+
for (let key of __getOwnPropNames(from))
|
|
18
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
19
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
20
|
+
}
|
|
21
|
+
return to;
|
|
22
|
+
};
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
26
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
+
mod
|
|
30
|
+
));
|
|
31
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
|
+
|
|
33
|
+
// src/process/resource-monitor.ts
|
|
34
|
+
var resource_monitor_exports = {};
|
|
35
|
+
__export(resource_monitor_exports, {
|
|
36
|
+
getPidStats: () => getPidStats,
|
|
37
|
+
getSinglePidStats: () => getSinglePidStats
|
|
38
|
+
});
|
|
39
|
+
function execPsForPids(pids) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
(0, import_node_child_process.execFile)("ps", ["-o", "pid=,pcpu=,rss=", "-p", pids.join(",")], {
|
|
42
|
+
timeout: 5e3
|
|
43
|
+
}, (err, stdout) => {
|
|
44
|
+
if (err) return reject(err);
|
|
45
|
+
resolve(stdout);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
function parsePsOutput(stdout) {
|
|
50
|
+
const result = /* @__PURE__ */ new Map();
|
|
51
|
+
for (const line of stdout.trim().split("\n")) {
|
|
52
|
+
const trimmed = line.trim();
|
|
53
|
+
if (!trimmed) continue;
|
|
54
|
+
const parts = trimmed.split(/\s+/);
|
|
55
|
+
if (parts.length < 3) continue;
|
|
56
|
+
const pid = parseInt(parts[0], 10);
|
|
57
|
+
const cpu = parseFloat(parts[1]);
|
|
58
|
+
const rssKb = parseInt(parts[2], 10);
|
|
59
|
+
if (isNaN(pid) || isNaN(cpu) || isNaN(rssKb)) continue;
|
|
60
|
+
result.set(pid, {
|
|
61
|
+
cpu: Math.round(cpu * 10) / 10,
|
|
62
|
+
memory: rssKb * 1024
|
|
63
|
+
// KB → bytes
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
async function getPidStats(pids) {
|
|
69
|
+
const pidArray = typeof pids === "number" ? [pids] : [...pids];
|
|
70
|
+
if (pidArray.length === 0) return /* @__PURE__ */ new Map();
|
|
71
|
+
try {
|
|
72
|
+
const stdout = await execPsForPids(pidArray);
|
|
73
|
+
return parsePsOutput(stdout);
|
|
74
|
+
} catch {
|
|
75
|
+
return /* @__PURE__ */ new Map();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function getSinglePidStats(pid) {
|
|
79
|
+
const stats = await getPidStats([pid]);
|
|
80
|
+
return stats.get(pid) ?? null;
|
|
81
|
+
}
|
|
82
|
+
var import_node_child_process;
|
|
83
|
+
var init_resource_monitor = __esm({
|
|
84
|
+
"src/process/resource-monitor.ts"() {
|
|
85
|
+
"use strict";
|
|
86
|
+
import_node_child_process = require("child_process");
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// src/builtins/native-metrics/native-metrics.addon.ts
|
|
91
|
+
var native_metrics_addon_exports = {};
|
|
92
|
+
__export(native_metrics_addon_exports, {
|
|
93
|
+
default: () => NativeMetricsAddon
|
|
94
|
+
});
|
|
95
|
+
module.exports = __toCommonJS(native_metrics_addon_exports);
|
|
96
|
+
var import_types = require("@camstack/types");
|
|
97
|
+
var import_node_child_process3 = require("child_process");
|
|
98
|
+
var import_node_util = require("util");
|
|
99
|
+
|
|
100
|
+
// src/builtins/native-metrics/native-metrics-provider.ts
|
|
101
|
+
var os = __toESM(require("os"));
|
|
102
|
+
var fs = __toESM(require("fs"));
|
|
103
|
+
var import_node_child_process2 = require("child_process");
|
|
104
|
+
var IS_DARWIN = os.platform() === "darwin";
|
|
105
|
+
var IS_LINUX = os.platform() === "linux";
|
|
106
|
+
var NativeMetricsProvider = class {
|
|
107
|
+
id = "native";
|
|
108
|
+
cachedSnapshot = null;
|
|
109
|
+
samplingTimer = null;
|
|
110
|
+
macMemTimer = null;
|
|
111
|
+
prevCpu;
|
|
112
|
+
diagnostics = null;
|
|
113
|
+
consecutiveSampleErrors = 0;
|
|
114
|
+
constructor() {
|
|
115
|
+
this.prevCpu = aggregateCpuTimes();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Optional diagnostics sink for sampling errors. The first failure and
|
|
119
|
+
* every Nth failure thereafter are reported so a permanently-broken
|
|
120
|
+
* collector doesn't spam logs but is still observable.
|
|
121
|
+
*/
|
|
122
|
+
setDiagnostics(diag) {
|
|
123
|
+
this.diagnostics = diag;
|
|
124
|
+
}
|
|
125
|
+
// ─── Lifecycle (not on the cap contract) ────────────────────────────
|
|
126
|
+
startSampling(intervalMs) {
|
|
127
|
+
if (IS_DARWIN) {
|
|
128
|
+
sampleMacMemory(this);
|
|
129
|
+
this.macMemTimer = setInterval(() => sampleMacMemory(this), 5e3);
|
|
130
|
+
if (this.macMemTimer.unref) this.macMemTimer.unref();
|
|
131
|
+
}
|
|
132
|
+
this.collectSnapshot().then((s) => {
|
|
133
|
+
this.cachedSnapshot = s;
|
|
134
|
+
this.consecutiveSampleErrors = 0;
|
|
135
|
+
}).catch((err) => this.reportSampleError(err));
|
|
136
|
+
this.samplingTimer = setInterval(() => {
|
|
137
|
+
this.collectSnapshot().then((s) => {
|
|
138
|
+
this.cachedSnapshot = s;
|
|
139
|
+
this.consecutiveSampleErrors = 0;
|
|
140
|
+
}).catch((err) => this.reportSampleError(err));
|
|
141
|
+
}, intervalMs);
|
|
142
|
+
if (this.samplingTimer.unref) this.samplingTimer.unref();
|
|
143
|
+
}
|
|
144
|
+
reportSampleError(err) {
|
|
145
|
+
this.consecutiveSampleErrors++;
|
|
146
|
+
if (!this.diagnostics) return;
|
|
147
|
+
const shouldLog = this.consecutiveSampleErrors === 1 || this.consecutiveSampleErrors % 60 === 0;
|
|
148
|
+
if (!shouldLog) return;
|
|
149
|
+
this.diagnostics.warn("metrics-provider sample failed", {
|
|
150
|
+
consecutiveErrors: this.consecutiveSampleErrors,
|
|
151
|
+
error: err instanceof Error ? err.message : String(err)
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
stopSampling() {
|
|
155
|
+
if (this.samplingTimer) {
|
|
156
|
+
clearInterval(this.samplingTimer);
|
|
157
|
+
this.samplingTimer = null;
|
|
158
|
+
}
|
|
159
|
+
if (this.macMemTimer) {
|
|
160
|
+
clearInterval(this.macMemTimer);
|
|
161
|
+
this.macMemTimer = null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// ─── Cap contract — async methods ───────────────────────────────────
|
|
165
|
+
async collectSnapshot() {
|
|
166
|
+
const cpu = this.sampleCpu();
|
|
167
|
+
const memory = this.getMemoryInfo();
|
|
168
|
+
const processInfo = getProcessResources();
|
|
169
|
+
const [gpu, network, disk, cpuTemp] = await Promise.all([
|
|
170
|
+
getGpuInfoInternal().catch(() => null),
|
|
171
|
+
takeNetworkIoSnapshot(),
|
|
172
|
+
takeDiskIoSnapshot(),
|
|
173
|
+
getCpuTemperatureInternal().catch(() => null)
|
|
174
|
+
]);
|
|
175
|
+
const snapshot = {
|
|
176
|
+
cpu,
|
|
177
|
+
memory,
|
|
178
|
+
gpu,
|
|
179
|
+
network,
|
|
180
|
+
disk,
|
|
181
|
+
pressure: {
|
|
182
|
+
cpu: getPressure("cpu"),
|
|
183
|
+
memory: getPressure("memory"),
|
|
184
|
+
io: getPressure("io")
|
|
185
|
+
},
|
|
186
|
+
process: processInfo,
|
|
187
|
+
cpuTemperature: cpuTemp,
|
|
188
|
+
timestampMs: Date.now()
|
|
189
|
+
};
|
|
190
|
+
this.cachedSnapshot = snapshot;
|
|
191
|
+
return snapshot;
|
|
192
|
+
}
|
|
193
|
+
async getCached() {
|
|
194
|
+
return this.cachedSnapshot;
|
|
195
|
+
}
|
|
196
|
+
async getCurrent() {
|
|
197
|
+
const s = this.cachedSnapshot ?? await this.collectSnapshot();
|
|
198
|
+
const mb = (bytes) => Math.round(bytes / 1024 / 1024);
|
|
199
|
+
return {
|
|
200
|
+
cpuPercent: s.cpu.total,
|
|
201
|
+
memoryPercent: s.memory.percent,
|
|
202
|
+
memoryUsedMB: mb(s.memory.usedBytes),
|
|
203
|
+
memoryTotalMB: mb(s.memory.totalBytes),
|
|
204
|
+
temperature: s.cpuTemperature ?? void 0,
|
|
205
|
+
gpuPercent: s.gpu?.utilization,
|
|
206
|
+
gpuMemoryPercent: s.gpu && s.gpu.memoryTotalBytes > 0 ? Math.round(s.gpu.memoryUsedBytes / s.gpu.memoryTotalBytes * 1e3) / 10 : void 0
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
async getDiskSpace(input) {
|
|
210
|
+
return getDiskSpaceInternal(input.dirPath);
|
|
211
|
+
}
|
|
212
|
+
async getGpuInfo() {
|
|
213
|
+
return getGpuInfoInternal();
|
|
214
|
+
}
|
|
215
|
+
async getCpuTemperature() {
|
|
216
|
+
return getCpuTemperatureInternal();
|
|
217
|
+
}
|
|
218
|
+
async getProcessStats(input) {
|
|
219
|
+
const { getPidStats: getPidStats2 } = await Promise.resolve().then(() => (init_resource_monitor(), resource_monitor_exports));
|
|
220
|
+
const raw = await getPidStats2(input.pids);
|
|
221
|
+
const result = [];
|
|
222
|
+
for (const [pid, s] of raw) {
|
|
223
|
+
result.push({ pid, cpu: s.cpu, memory: s.memory });
|
|
224
|
+
}
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
// ─── Internal: CPU sampling ─────────────────────────────────────────
|
|
228
|
+
sampleCpu() {
|
|
229
|
+
const curr = aggregateCpuTimes();
|
|
230
|
+
const prev = this.prevCpu;
|
|
231
|
+
this.prevCpu = curr;
|
|
232
|
+
const dUser = curr.user - prev.user;
|
|
233
|
+
const dNice = curr.nice - prev.nice;
|
|
234
|
+
const dSys = curr.sys - prev.sys;
|
|
235
|
+
const dIrq = curr.irq - prev.irq;
|
|
236
|
+
const dIdle = curr.idle - prev.idle;
|
|
237
|
+
const dTotal = dUser + dNice + dSys + dIrq + dIdle;
|
|
238
|
+
const pct = (v) => dTotal === 0 ? 0 : Math.round(v / dTotal * 1e3) / 10;
|
|
239
|
+
return {
|
|
240
|
+
total: pct(dUser + dNice + dSys + dIrq),
|
|
241
|
+
user: pct(dUser),
|
|
242
|
+
system: pct(dSys),
|
|
243
|
+
irq: pct(dIrq),
|
|
244
|
+
nice: pct(dNice),
|
|
245
|
+
loadAvg: os.loadavg(),
|
|
246
|
+
cores: os.cpus().length
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
// ─── Internal: Memory ───────────────────────────────────────────────
|
|
250
|
+
/** Cached macOS memory (set by sampleMacMemory timer). */
|
|
251
|
+
_cachedMacMem = null;
|
|
252
|
+
getMemoryInfo() {
|
|
253
|
+
const total = os.totalmem();
|
|
254
|
+
if (total === 0) {
|
|
255
|
+
return { percent: 0, totalBytes: 0, usedBytes: 0, availableBytes: 0, swapUsedBytes: 0, swapTotalBytes: 0 };
|
|
256
|
+
}
|
|
257
|
+
if (IS_DARWIN && this._cachedMacMem !== null) {
|
|
258
|
+
return this._cachedMacMem;
|
|
259
|
+
}
|
|
260
|
+
const free = os.freemem();
|
|
261
|
+
const used = total - free;
|
|
262
|
+
let swapUsedBytes = 0;
|
|
263
|
+
let swapTotalBytes = 0;
|
|
264
|
+
if (IS_LINUX) {
|
|
265
|
+
try {
|
|
266
|
+
const meminfo = fs.readFileSync("/proc/meminfo", "utf-8");
|
|
267
|
+
const swapTotal = parseInt(meminfo.match(/SwapTotal:\s+(\d+)/)?.[1] ?? "0", 10) * 1024;
|
|
268
|
+
const swapFree = parseInt(meminfo.match(/SwapFree:\s+(\d+)/)?.[1] ?? "0", 10) * 1024;
|
|
269
|
+
swapTotalBytes = swapTotal;
|
|
270
|
+
swapUsedBytes = swapTotal - swapFree;
|
|
271
|
+
} catch {
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
percent: Math.round((total - free) / total * 1e3) / 10,
|
|
276
|
+
totalBytes: total,
|
|
277
|
+
usedBytes: used,
|
|
278
|
+
availableBytes: free,
|
|
279
|
+
swapUsedBytes,
|
|
280
|
+
swapTotalBytes
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
function aggregateCpuTimes() {
|
|
285
|
+
const cpus2 = os.cpus();
|
|
286
|
+
let user = 0, nice = 0, sys = 0, irq = 0, idle = 0;
|
|
287
|
+
for (const cpu of cpus2) {
|
|
288
|
+
user += cpu.times.user;
|
|
289
|
+
nice += cpu.times.nice;
|
|
290
|
+
sys += cpu.times.sys;
|
|
291
|
+
irq += cpu.times.irq;
|
|
292
|
+
idle += cpu.times.idle;
|
|
293
|
+
}
|
|
294
|
+
return { user, nice, sys, irq, idle };
|
|
295
|
+
}
|
|
296
|
+
function sampleMacMemory(provider) {
|
|
297
|
+
try {
|
|
298
|
+
const output = (0, import_node_child_process2.execFileSync)("vm_stat", { timeout: 2e3, encoding: "utf-8" });
|
|
299
|
+
const pageSize = 16384;
|
|
300
|
+
const parse = (label) => {
|
|
301
|
+
const match = output.match(new RegExp(`${label}:\\s+(\\d+)`));
|
|
302
|
+
return match ? parseInt(match[1], 10) * pageSize : 0;
|
|
303
|
+
};
|
|
304
|
+
const free = parse("Pages free");
|
|
305
|
+
const inactive = parse("Pages inactive");
|
|
306
|
+
const purgeable = parse("Pages purgeable");
|
|
307
|
+
const speculative = parse("Pages speculative");
|
|
308
|
+
const available = free + inactive + purgeable + speculative;
|
|
309
|
+
const total = os.totalmem();
|
|
310
|
+
const used = total - available;
|
|
311
|
+
let swapUsedBytes = 0;
|
|
312
|
+
let swapTotalBytes = 0;
|
|
313
|
+
try {
|
|
314
|
+
const swapOut = (0, import_node_child_process2.execFileSync)("sysctl", ["-n", "vm.swapusage"], { timeout: 2e3, encoding: "utf-8" });
|
|
315
|
+
const totalMatch = swapOut.match(/total\s*=\s*([\d.]+)M/);
|
|
316
|
+
const usedMatch = swapOut.match(/used\s*=\s*([\d.]+)M/);
|
|
317
|
+
if (totalMatch) swapTotalBytes = parseFloat(totalMatch[1]) * 1024 * 1024;
|
|
318
|
+
if (usedMatch) swapUsedBytes = parseFloat(usedMatch[1]) * 1024 * 1024;
|
|
319
|
+
} catch {
|
|
320
|
+
}
|
|
321
|
+
provider._cachedMacMem = {
|
|
322
|
+
percent: Math.round(used / total * 1e3) / 10,
|
|
323
|
+
totalBytes: total,
|
|
324
|
+
usedBytes: used,
|
|
325
|
+
availableBytes: available,
|
|
326
|
+
swapUsedBytes,
|
|
327
|
+
swapTotalBytes
|
|
328
|
+
};
|
|
329
|
+
} catch {
|
|
330
|
+
provider._cachedMacMem = null;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function getDiskSpaceInternal(dirPath) {
|
|
334
|
+
return new Promise((resolve, reject) => {
|
|
335
|
+
fs.statfs(dirPath, (err, stats) => {
|
|
336
|
+
if (err) return reject(err);
|
|
337
|
+
const totalBytes = stats.blocks * stats.bsize;
|
|
338
|
+
const availableBytes = stats.bavail * stats.bsize;
|
|
339
|
+
const usedBytes = totalBytes - stats.bfree * stats.bsize;
|
|
340
|
+
resolve({
|
|
341
|
+
path: dirPath,
|
|
342
|
+
totalBytes,
|
|
343
|
+
usedBytes,
|
|
344
|
+
availableBytes,
|
|
345
|
+
percent: totalBytes > 0 ? Math.round(usedBytes / totalBytes * 1e3) / 10 : 0
|
|
346
|
+
});
|
|
347
|
+
});
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
async function takeDiskIoSnapshot() {
|
|
351
|
+
const now = Date.now();
|
|
352
|
+
if (IS_LINUX) {
|
|
353
|
+
try {
|
|
354
|
+
const data = fs.readFileSync("/proc/diskstats", "utf-8");
|
|
355
|
+
let readOps = 0, readBytes = 0, writeOps = 0, writeBytes = 0;
|
|
356
|
+
for (const line of data.split("\n")) {
|
|
357
|
+
const parts = line.trim().split(/\s+/);
|
|
358
|
+
if (parts.length < 14) continue;
|
|
359
|
+
const devName = parts[2];
|
|
360
|
+
if (/\d+$/.test(devName) && !/^nvme\d+n\d+$/.test(devName)) continue;
|
|
361
|
+
readOps += parseInt(parts[3], 10) || 0;
|
|
362
|
+
readBytes += (parseInt(parts[5], 10) || 0) * 512;
|
|
363
|
+
writeOps += parseInt(parts[7], 10) || 0;
|
|
364
|
+
writeBytes += (parseInt(parts[9], 10) || 0) * 512;
|
|
365
|
+
}
|
|
366
|
+
return { readBytes, writeBytes, readOps, writeOps, timestampMs: now };
|
|
367
|
+
} catch {
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return { readBytes: 0, writeBytes: 0, readOps: 0, writeOps: 0, timestampMs: now };
|
|
371
|
+
}
|
|
372
|
+
async function takeNetworkIoSnapshot() {
|
|
373
|
+
const now = Date.now();
|
|
374
|
+
if (IS_LINUX) {
|
|
375
|
+
try {
|
|
376
|
+
const data = fs.readFileSync("/proc/net/dev", "utf-8");
|
|
377
|
+
let rxBytes = 0, txBytes = 0, rxPackets = 0, txPackets = 0, rxErrors = 0, txErrors = 0;
|
|
378
|
+
for (const line of data.split("\n")) {
|
|
379
|
+
const match = line.match(/^\s*(\w+):\s+(.+)$/);
|
|
380
|
+
if (!match) continue;
|
|
381
|
+
if (match[1] === "lo") continue;
|
|
382
|
+
const cols = match[2].trim().split(/\s+/);
|
|
383
|
+
rxBytes += parseInt(cols[0], 10) || 0;
|
|
384
|
+
rxPackets += parseInt(cols[1], 10) || 0;
|
|
385
|
+
rxErrors += parseInt(cols[2], 10) || 0;
|
|
386
|
+
txBytes += parseInt(cols[8], 10) || 0;
|
|
387
|
+
txPackets += parseInt(cols[9], 10) || 0;
|
|
388
|
+
txErrors += parseInt(cols[10], 10) || 0;
|
|
389
|
+
}
|
|
390
|
+
return { rxBytes, txBytes, rxPackets, txPackets, rxErrors, txErrors, timestampMs: now };
|
|
391
|
+
} catch {
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (IS_DARWIN) {
|
|
395
|
+
try {
|
|
396
|
+
const stdout = await execAsync("netstat", ["-ib"]);
|
|
397
|
+
let rxBytes = 0, txBytes = 0, rxPackets = 0, txPackets = 0, rxErrors = 0, txErrors = 0;
|
|
398
|
+
for (const line of stdout.split("\n")) {
|
|
399
|
+
const parts = line.trim().split(/\s+/);
|
|
400
|
+
if (parts.length < 11) continue;
|
|
401
|
+
if (parts[0] === "lo0" || parts[0] === "Name") continue;
|
|
402
|
+
if (!parts[2]?.startsWith("Link#")) continue;
|
|
403
|
+
rxPackets += parseInt(parts[4], 10) || 0;
|
|
404
|
+
rxErrors += parseInt(parts[5], 10) || 0;
|
|
405
|
+
rxBytes += parseInt(parts[6], 10) || 0;
|
|
406
|
+
txPackets += parseInt(parts[7], 10) || 0;
|
|
407
|
+
txErrors += parseInt(parts[8], 10) || 0;
|
|
408
|
+
txBytes += parseInt(parts[9], 10) || 0;
|
|
409
|
+
}
|
|
410
|
+
return { rxBytes, txBytes, rxPackets, txPackets, rxErrors, txErrors, timestampMs: now };
|
|
411
|
+
} catch {
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
return { rxBytes: 0, txBytes: 0, rxPackets: 0, txPackets: 0, rxErrors: 0, txErrors: 0, timestampMs: now };
|
|
415
|
+
}
|
|
416
|
+
async function getCpuTemperatureInternal() {
|
|
417
|
+
if (IS_LINUX) {
|
|
418
|
+
const paths = ["/sys/class/thermal/thermal_zone0/temp", "/sys/class/hwmon/hwmon0/temp1_input"];
|
|
419
|
+
for (const p of paths) {
|
|
420
|
+
try {
|
|
421
|
+
const raw = fs.readFileSync(p, "utf-8").trim();
|
|
422
|
+
const millideg = parseInt(raw, 10);
|
|
423
|
+
if (!isNaN(millideg)) return Math.round(millideg / 100) / 10;
|
|
424
|
+
} catch {
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (IS_DARWIN) {
|
|
430
|
+
try {
|
|
431
|
+
const stdout = await execAsync("sudo", ["-n", "powermetrics", "--samplers", "smc", "-i", "1", "-n", "1"], 3e3);
|
|
432
|
+
const match = stdout.match(/CPU die temperature:\s+([\d.]+)\s*C/);
|
|
433
|
+
if (match) return Math.round(parseFloat(match[1]) * 10) / 10;
|
|
434
|
+
} catch {
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return null;
|
|
438
|
+
}
|
|
439
|
+
async function getGpuInfoInternal() {
|
|
440
|
+
if (IS_DARWIN) {
|
|
441
|
+
try {
|
|
442
|
+
const stdout = await execAsync("ioreg", ["-r", "-d", "1", "-c", "IOAccelerator"]);
|
|
443
|
+
const utilMatch = stdout.match(/"GPU Core Utilization"\s*=\s*(\d+)/);
|
|
444
|
+
const util = utilMatch ? parseInt(utilMatch[1], 10) : 0;
|
|
445
|
+
const utilPct = util > 1e3 ? Math.round(util / 1e7) : util;
|
|
446
|
+
return {
|
|
447
|
+
utilization: Math.min(100, utilPct),
|
|
448
|
+
model: "Apple Silicon GPU",
|
|
449
|
+
memoryUsedBytes: 0,
|
|
450
|
+
memoryTotalBytes: 0,
|
|
451
|
+
temperature: null
|
|
452
|
+
};
|
|
453
|
+
} catch {
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (IS_LINUX) {
|
|
457
|
+
try {
|
|
458
|
+
const stdout = await execAsync("nvidia-smi", [
|
|
459
|
+
"--query-gpu=utilization.gpu,name,memory.used,memory.total,temperature.gpu",
|
|
460
|
+
"--format=csv,noheader,nounits"
|
|
461
|
+
]);
|
|
462
|
+
const parts = stdout.trim().split(",").map((s) => s.trim());
|
|
463
|
+
if (parts.length >= 5) {
|
|
464
|
+
return {
|
|
465
|
+
utilization: parseInt(parts[0], 10) || 0,
|
|
466
|
+
model: parts[1] ?? "Unknown GPU",
|
|
467
|
+
memoryUsedBytes: (parseInt(parts[2], 10) || 0) * 1024 * 1024,
|
|
468
|
+
memoryTotalBytes: (parseInt(parts[3], 10) || 0) * 1024 * 1024,
|
|
469
|
+
temperature: parseInt(parts[4], 10) || null
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
} catch {
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return null;
|
|
476
|
+
}
|
|
477
|
+
function getProcessResources() {
|
|
478
|
+
let openFds = 0;
|
|
479
|
+
let threadCount = 0;
|
|
480
|
+
if (IS_LINUX) {
|
|
481
|
+
try {
|
|
482
|
+
openFds = fs.readdirSync(`/proc/${process.pid}/fd`).length;
|
|
483
|
+
} catch {
|
|
484
|
+
}
|
|
485
|
+
try {
|
|
486
|
+
const status = fs.readFileSync(`/proc/${process.pid}/status`, "utf-8");
|
|
487
|
+
const match = status.match(/Threads:\s+(\d+)/);
|
|
488
|
+
if (match) threadCount = parseInt(match[1], 10);
|
|
489
|
+
} catch {
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
const nodeProcess = process;
|
|
493
|
+
return {
|
|
494
|
+
openFds,
|
|
495
|
+
threadCount,
|
|
496
|
+
activeHandles: (nodeProcess._getActiveHandles?.() ?? []).length,
|
|
497
|
+
activeRequests: (nodeProcess._getActiveRequests?.() ?? []).length
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
function getPressure(resource) {
|
|
501
|
+
if (!IS_LINUX) return null;
|
|
502
|
+
try {
|
|
503
|
+
const data = fs.readFileSync(`/proc/pressure/${resource}`, "utf-8");
|
|
504
|
+
const parseLine = (prefix) => {
|
|
505
|
+
const match = data.match(new RegExp(`${prefix} avg10=(\\d+\\.\\d+) avg60=(\\d+\\.\\d+) avg300=(\\d+\\.\\d+)`));
|
|
506
|
+
if (!match) return null;
|
|
507
|
+
return { avg10: parseFloat(match[1]), avg60: parseFloat(match[2]), avg300: parseFloat(match[3]) };
|
|
508
|
+
};
|
|
509
|
+
const some = parseLine("some");
|
|
510
|
+
if (!some) return null;
|
|
511
|
+
return { some, full: parseLine("full") };
|
|
512
|
+
} catch {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function execAsync(cmd, args, timeoutMs = 5e3) {
|
|
517
|
+
return new Promise((resolve, reject) => {
|
|
518
|
+
(0, import_node_child_process2.execFile)(cmd, args, { timeout: timeoutMs }, (err, stdout) => {
|
|
519
|
+
if (err) return reject(err);
|
|
520
|
+
resolve(stdout);
|
|
521
|
+
});
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// src/builtins/native-metrics/native-metrics.addon.ts
|
|
526
|
+
var execFileAsync = (0, import_node_util.promisify)(import_node_child_process3.execFile);
|
|
527
|
+
var CAMSTACK_CMD_RE = /(camstack|tsx\s+watch\s.*launcher\.ts|packages\/agent\/dist\/cli\.js|inference_pool\.py|bench-(inference-pool|nodeav)|node .*\/packages\/)/;
|
|
528
|
+
var SUPERVISOR_BOUNDARY_RE = /(tsx\s+watch\s.*launcher\.ts|packages\/agent\/dist\/cli\.js|\.bin\/concurrently|\/concurrently\/dist|\bnpm-cli\.js\b|npm exec |\.bin\/vite|\/vite\/bin\/vite\.js|node_modules\/\.bin\/(vite|concurrently|tsup|rollup|esbuild|tsx)(\s|$))/;
|
|
529
|
+
var METRICS_SNAPSHOT_INTERVAL_MS = 5e3;
|
|
530
|
+
var METRICS_SNAPSHOT_HEARTBEAT_MS = 6e4;
|
|
531
|
+
function coarsenResourcesSnapshot(snapshot) {
|
|
532
|
+
if (!snapshot || typeof snapshot !== "object") return JSON.stringify(snapshot);
|
|
533
|
+
const round = (v) => {
|
|
534
|
+
if (typeof v === "number") {
|
|
535
|
+
if (v >= 0 && v <= 100) return Math.round(v / 5) * 5;
|
|
536
|
+
return Math.round(v / 1e5) * 1e5;
|
|
537
|
+
}
|
|
538
|
+
if (Array.isArray(v)) return v.map(round);
|
|
539
|
+
if (v && typeof v === "object") {
|
|
540
|
+
const out = {};
|
|
541
|
+
for (const [k, val] of Object.entries(v)) {
|
|
542
|
+
out[k] = round(val);
|
|
543
|
+
}
|
|
544
|
+
return out;
|
|
545
|
+
}
|
|
546
|
+
return v;
|
|
547
|
+
};
|
|
548
|
+
return JSON.stringify(round(snapshot));
|
|
549
|
+
}
|
|
550
|
+
function coarsenProcessList(processes) {
|
|
551
|
+
const summary = processes.filter((p) => !!p && typeof p === "object").map((p) => {
|
|
552
|
+
const pid = p["pid"];
|
|
553
|
+
const addonId = p["addonId"];
|
|
554
|
+
const state = p["state"];
|
|
555
|
+
const cpu = typeof p["cpuPercent"] === "number" ? Math.round(p["cpuPercent"] / 5) * 5 : null;
|
|
556
|
+
const mem = typeof p["memoryRss"] === "number" ? Math.round(p["memoryRss"] / (50 * 1024 * 1024)) : null;
|
|
557
|
+
return [pid, addonId, state, cpu, mem];
|
|
558
|
+
});
|
|
559
|
+
return JSON.stringify(summary);
|
|
560
|
+
}
|
|
561
|
+
function narrowWorkerState(state) {
|
|
562
|
+
switch (state) {
|
|
563
|
+
case "starting":
|
|
564
|
+
case "running":
|
|
565
|
+
case "stopping":
|
|
566
|
+
case "stopped":
|
|
567
|
+
case "crashed":
|
|
568
|
+
return state;
|
|
569
|
+
default:
|
|
570
|
+
return "running";
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
var NativeMetricsAddon = class extends import_types.BaseAddon {
|
|
574
|
+
provider = null;
|
|
575
|
+
startedAtMs = Date.now();
|
|
576
|
+
snapshotTimer = null;
|
|
577
|
+
/**
|
|
578
|
+
* Snapshot-equality cache for the resources + processes emit.
|
|
579
|
+
* Stores the coarsened JSON and timestamp; a tick where the
|
|
580
|
+
* coarsened payload matches the cache (and the heartbeat hasn't
|
|
581
|
+
* elapsed) is skipped.
|
|
582
|
+
*/
|
|
583
|
+
lastResourcesEmit = null;
|
|
584
|
+
lastProcessesEmit = null;
|
|
585
|
+
constructor() {
|
|
586
|
+
super({ samplingIntervalMs: 5e3 });
|
|
587
|
+
}
|
|
588
|
+
async onInitialize() {
|
|
589
|
+
const provider = new NativeMetricsProvider();
|
|
590
|
+
provider.setDiagnostics({
|
|
591
|
+
warn: (message, meta) => this.ctx.logger.warn(message, { meta: meta ?? {} })
|
|
592
|
+
});
|
|
593
|
+
provider.startSampling(this.config.samplingIntervalMs);
|
|
594
|
+
this.provider = provider;
|
|
595
|
+
this.startedAtMs = Date.now();
|
|
596
|
+
this.ctx.logger.info("Native metrics provider started", { meta: { intervalMs: this.config.samplingIntervalMs } });
|
|
597
|
+
const composed = {
|
|
598
|
+
collectSnapshot: () => provider.collectSnapshot(),
|
|
599
|
+
getCached: () => provider.getCached(),
|
|
600
|
+
getCurrent: () => provider.getCurrent(),
|
|
601
|
+
getDiskSpace: (params) => provider.getDiskSpace(params),
|
|
602
|
+
getGpuInfo: () => provider.getGpuInfo(),
|
|
603
|
+
getCpuTemperature: () => provider.getCpuTemperature(),
|
|
604
|
+
getProcessStats: (params) => provider.getProcessStats(params),
|
|
605
|
+
listAddonInstances: () => this.listAddonInstances(),
|
|
606
|
+
getAddonStats: (params) => this.getAddonStats(params.addonId),
|
|
607
|
+
listNodeProcesses: () => this.listNodeProcesses(),
|
|
608
|
+
killProcess: (params) => this.killProcess(params)
|
|
609
|
+
};
|
|
610
|
+
this.snapshotTimer = setInterval(
|
|
611
|
+
() => this.emitMetricsSnapshots(),
|
|
612
|
+
METRICS_SNAPSHOT_INTERVAL_MS
|
|
613
|
+
);
|
|
614
|
+
return [{ capability: import_types.metricsProviderCapability, provider: composed }];
|
|
615
|
+
}
|
|
616
|
+
async onShutdown() {
|
|
617
|
+
if (this.snapshotTimer) {
|
|
618
|
+
clearInterval(this.snapshotTimer);
|
|
619
|
+
this.snapshotTimer = null;
|
|
620
|
+
}
|
|
621
|
+
this.provider?.stopSampling();
|
|
622
|
+
this.provider = null;
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Emit one `metrics.node-resources-snapshot` + one
|
|
626
|
+
* `metrics.node-processes-snapshot` for this node. UI consumers
|
|
627
|
+
* subscribe and read state directly from the payload.
|
|
628
|
+
*/
|
|
629
|
+
async emitMetricsSnapshots() {
|
|
630
|
+
const provider = this.provider;
|
|
631
|
+
const eventBus = this.ctx.eventBus;
|
|
632
|
+
if (!provider || !eventBus) return;
|
|
633
|
+
const rawNodeId = this.ctx.kernel.localNodeId ?? this.ctx.id;
|
|
634
|
+
const nodeId = rawNodeId.includes("/") ? rawNodeId.split("/")[0] : rawNodeId;
|
|
635
|
+
const timestamp = Date.now();
|
|
636
|
+
try {
|
|
637
|
+
const cached = await provider.getCached();
|
|
638
|
+
const snapshot = cached ?? await provider.collectSnapshot();
|
|
639
|
+
const coarse = coarsenResourcesSnapshot(snapshot);
|
|
640
|
+
const prev = this.lastResourcesEmit;
|
|
641
|
+
const heartbeatDue = !prev || timestamp - prev.emittedAt >= METRICS_SNAPSHOT_HEARTBEAT_MS;
|
|
642
|
+
if (!prev || prev.coarse !== coarse || heartbeatDue) {
|
|
643
|
+
this.lastResourcesEmit = { coarse, emittedAt: timestamp };
|
|
644
|
+
eventBus.emit((0, import_types.createEvent)(
|
|
645
|
+
import_types.EventCategory.MetricsNodeResourcesSnapshot,
|
|
646
|
+
{ type: "node", id: nodeId, nodeId },
|
|
647
|
+
{ nodeId, snapshot, timestamp }
|
|
648
|
+
));
|
|
649
|
+
}
|
|
650
|
+
} catch {
|
|
651
|
+
}
|
|
652
|
+
try {
|
|
653
|
+
const processes = await this.listNodeProcesses();
|
|
654
|
+
const coarse = coarsenProcessList(processes);
|
|
655
|
+
const prev = this.lastProcessesEmit;
|
|
656
|
+
const heartbeatDue = !prev || timestamp - prev.emittedAt >= METRICS_SNAPSHOT_HEARTBEAT_MS;
|
|
657
|
+
if (!prev || prev.coarse !== coarse || heartbeatDue) {
|
|
658
|
+
this.lastProcessesEmit = { coarse, emittedAt: timestamp };
|
|
659
|
+
eventBus.emit((0, import_types.createEvent)(
|
|
660
|
+
import_types.EventCategory.MetricsNodeProcessesSnapshot,
|
|
661
|
+
{ type: "node", id: nodeId, nodeId },
|
|
662
|
+
{ nodeId, processes, timestamp }
|
|
663
|
+
));
|
|
664
|
+
}
|
|
665
|
+
} catch {
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
async onConfigChanged() {
|
|
669
|
+
this.provider?.stopSampling();
|
|
670
|
+
this.provider?.startSampling(this.config.samplingIntervalMs);
|
|
671
|
+
}
|
|
672
|
+
async listWorkerInstances() {
|
|
673
|
+
const broker = this.ctx.kernel.cluster?.broker;
|
|
674
|
+
if (!broker) return [];
|
|
675
|
+
try {
|
|
676
|
+
return await broker.call("$process.list");
|
|
677
|
+
} catch {
|
|
678
|
+
return [];
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
async listAddonInstances() {
|
|
682
|
+
const broker = this.ctx.kernel.cluster?.broker;
|
|
683
|
+
const hubNodeId = broker?.nodeID ?? "hub";
|
|
684
|
+
const uptimeSec = Math.max(0, Math.floor((Date.now() - this.startedAtMs) / 1e3));
|
|
685
|
+
const instances = [{
|
|
686
|
+
addonId: "$hub",
|
|
687
|
+
nodeId: hubNodeId,
|
|
688
|
+
role: "hub",
|
|
689
|
+
pid: process.pid,
|
|
690
|
+
state: "running",
|
|
691
|
+
uptimeSec
|
|
692
|
+
}];
|
|
693
|
+
const workers = await this.listWorkerInstances();
|
|
694
|
+
for (const w of workers) {
|
|
695
|
+
instances.push({
|
|
696
|
+
addonId: w.addonId,
|
|
697
|
+
nodeId: w.nodeId,
|
|
698
|
+
role: "worker",
|
|
699
|
+
pid: w.pid,
|
|
700
|
+
state: narrowWorkerState(w.state),
|
|
701
|
+
uptimeSec: w.uptimeSeconds
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
return instances;
|
|
705
|
+
}
|
|
706
|
+
async getAddonStats(addonId) {
|
|
707
|
+
const provider = this.provider;
|
|
708
|
+
if (!provider) return null;
|
|
709
|
+
if (addonId === "$hub") {
|
|
710
|
+
const stats2 = await provider.getProcessStats({ pids: [process.pid] });
|
|
711
|
+
return stats2[0] ?? null;
|
|
712
|
+
}
|
|
713
|
+
const workers = await this.listWorkerInstances();
|
|
714
|
+
const target = workers.find((w) => w.addonId === addonId);
|
|
715
|
+
if (!target) return null;
|
|
716
|
+
const stats = await provider.getProcessStats({ pids: [target.pid] });
|
|
717
|
+
return stats[0] ?? null;
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* Walk the OS process table and classify each camstack-shaped process.
|
|
721
|
+
*
|
|
722
|
+
* Classification (ancestry-driven, NOT pattern-driven):
|
|
723
|
+
* - root — the current node's own pid (`process.pid`).
|
|
724
|
+
* - managed — pid is registered in the kernel's `$process.list`
|
|
725
|
+
* (forked addon worker spawned by this hub).
|
|
726
|
+
* - system — ancestry walk crosses a SUPERVISOR_BOUNDARY_RE match
|
|
727
|
+
* (tsx-watch launcher, agent CLI, concurrently, vite,
|
|
728
|
+
* npm exec wrapper). The process belongs to the dev
|
|
729
|
+
* tree even if not in `$process.list`. NEVER killable.
|
|
730
|
+
* - ghost — ancestry walk reaches `ppid=1` without crossing any
|
|
731
|
+
* supervisor boundary AND the parent isn't visible in
|
|
732
|
+
* `ps`. A truly orphaned camstack-shaped process. The
|
|
733
|
+
* ONLY classification that's eligible for kill.
|
|
734
|
+
*
|
|
735
|
+
* Old pattern-only ghost detection produced false positives: every
|
|
736
|
+
* monorepo-path process matched CAMSTACK_CMD_RE, ancestry walk
|
|
737
|
+
* stopping at ppid=hub returned false-positive ghosts whenever a
|
|
738
|
+
* concurrently sibling sat above hub. Ancestry-driven classification
|
|
739
|
+
* fixes that.
|
|
740
|
+
*/
|
|
741
|
+
async listNodeProcesses() {
|
|
742
|
+
const ps = await this.runPs();
|
|
743
|
+
if (ps.length === 0) return [];
|
|
744
|
+
const managedPids = /* @__PURE__ */ new Map();
|
|
745
|
+
const workers = await this.listWorkerInstances();
|
|
746
|
+
for (const w of workers) {
|
|
747
|
+
managedPids.set(w.pid, { addonId: w.addonId, nodeId: w.nodeId });
|
|
748
|
+
}
|
|
749
|
+
const hubNodeId = this.ctx.kernel.cluster?.broker?.nodeID ?? "hub";
|
|
750
|
+
const selfPid = process.pid;
|
|
751
|
+
const psIndex = /* @__PURE__ */ new Map();
|
|
752
|
+
for (const p of ps) psIndex.set(p.pid, { ppid: p.ppid, command: p.command });
|
|
753
|
+
const classifyByAncestry = (startPid) => {
|
|
754
|
+
let cur = startPid;
|
|
755
|
+
for (let depth = 0; depth < 32; depth++) {
|
|
756
|
+
const node = psIndex.get(cur);
|
|
757
|
+
if (!node) return "ghost";
|
|
758
|
+
if (cur === selfPid) return "system";
|
|
759
|
+
if (SUPERVISOR_BOUNDARY_RE.test(node.command)) return "system";
|
|
760
|
+
if (node.ppid === 1) return "ghost";
|
|
761
|
+
if (node.ppid === selfPid) return "system";
|
|
762
|
+
cur = node.ppid;
|
|
763
|
+
}
|
|
764
|
+
return "system";
|
|
765
|
+
};
|
|
766
|
+
const out = [];
|
|
767
|
+
for (const p of ps) {
|
|
768
|
+
if (!CAMSTACK_CMD_RE.test(p.command)) continue;
|
|
769
|
+
const managed = managedPids.get(p.pid);
|
|
770
|
+
let classification;
|
|
771
|
+
if (p.pid === selfPid) {
|
|
772
|
+
classification = "root";
|
|
773
|
+
} else if (managed) {
|
|
774
|
+
classification = "managed";
|
|
775
|
+
} else {
|
|
776
|
+
classification = classifyByAncestry(p.pid);
|
|
777
|
+
}
|
|
778
|
+
const orphaned = classification === "ghost";
|
|
779
|
+
out.push({
|
|
780
|
+
pid: p.pid,
|
|
781
|
+
ppid: p.ppid,
|
|
782
|
+
pgid: p.pgid,
|
|
783
|
+
classification,
|
|
784
|
+
addonId: managed?.addonId ?? null,
|
|
785
|
+
nodeId: managed?.nodeId ?? (p.pid === selfPid ? hubNodeId : null),
|
|
786
|
+
command: p.command,
|
|
787
|
+
cpuPercent: p.cpuPercent,
|
|
788
|
+
memoryRssBytes: p.memoryRssBytes,
|
|
789
|
+
uptimeSec: p.uptimeSec,
|
|
790
|
+
orphaned
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
return out;
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Send SIGTERM / SIGKILL to a pid. Refuses pids that don't appear in
|
|
797
|
+
* `listNodeProcesses()` to prevent arbitrary system kills — a dedicated
|
|
798
|
+
* admin-path for resurrected zombies, not a generic shell replacement.
|
|
799
|
+
*
|
|
800
|
+
* `root`-classified pids (the running launcher / agent CLI / hub itself)
|
|
801
|
+
* are also refused: killing them tears down the whole node and the
|
|
802
|
+
* operator's intent is almost always to nuke a leaked child, not the
|
|
803
|
+
* supervisor that keeps the rest alive. Process restart goes through
|
|
804
|
+
* the dedicated `$process.restart` action, not this kill API.
|
|
805
|
+
*/
|
|
806
|
+
async killProcess(input) {
|
|
807
|
+
const visible = await this.listNodeProcesses();
|
|
808
|
+
const match = visible.find((p) => p.pid === input.pid);
|
|
809
|
+
if (!match) {
|
|
810
|
+
return { success: false, reason: "pid not in node process table" };
|
|
811
|
+
}
|
|
812
|
+
if (match.classification === "root" || match.classification === "system") {
|
|
813
|
+
this.ctx.logger.warn("Refused to kill protected process", {
|
|
814
|
+
meta: { pid: input.pid, classification: match.classification, addonId: match.addonId, command: match.command }
|
|
815
|
+
});
|
|
816
|
+
const reason = match.classification === "root" ? "cannot kill root (current node supervisor)" : "cannot kill system (intentional dev-tree ancestor \u2014 vite, concurrently, npm, etc.)";
|
|
817
|
+
return { success: false, reason };
|
|
818
|
+
}
|
|
819
|
+
const signal = input.force ? "SIGKILL" : "SIGTERM";
|
|
820
|
+
try {
|
|
821
|
+
process.kill(input.pid, signal);
|
|
822
|
+
this.ctx.logger.info("Killed node process", { meta: { pid: input.pid, signal, classification: match.classification, addonId: match.addonId } });
|
|
823
|
+
return { success: true, signal };
|
|
824
|
+
} catch (err) {
|
|
825
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
826
|
+
return { success: false, reason: msg, signal };
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
/** Raw `ps` scan returning every pid + command + resource stats. */
|
|
830
|
+
async runPs() {
|
|
831
|
+
try {
|
|
832
|
+
const { stdout } = await execFileAsync(
|
|
833
|
+
"ps",
|
|
834
|
+
["-eo", "pid=,ppid=,pgid=,pcpu=,rss=,etime=,command="],
|
|
835
|
+
{ timeout: 5e3, maxBuffer: 8 * 1024 * 1024 }
|
|
836
|
+
);
|
|
837
|
+
const lines = stdout.split("\n");
|
|
838
|
+
const rows = [];
|
|
839
|
+
for (const line of lines) {
|
|
840
|
+
const trimmed = line.trim();
|
|
841
|
+
if (!trimmed) continue;
|
|
842
|
+
const match = trimmed.match(/^(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(\S+)\s+(.+)$/);
|
|
843
|
+
if (!match) continue;
|
|
844
|
+
const [, pidS, ppidS, pgidS, cpuS, rssS, etimeS, command] = match;
|
|
845
|
+
rows.push({
|
|
846
|
+
pid: parseInt(pidS, 10),
|
|
847
|
+
ppid: parseInt(ppidS, 10),
|
|
848
|
+
pgid: parseInt(pgidS, 10),
|
|
849
|
+
cpuPercent: Math.round(parseFloat(cpuS) * 10) / 10,
|
|
850
|
+
memoryRssBytes: parseInt(rssS, 10) * 1024,
|
|
851
|
+
uptimeSec: parseEtime(etimeS),
|
|
852
|
+
command
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
return rows;
|
|
856
|
+
} catch (err) {
|
|
857
|
+
this.ctx.logger.warn("ps scan failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
|
|
858
|
+
return [];
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
globalSettingsSchema() {
|
|
862
|
+
return this.schema({
|
|
863
|
+
sections: [{
|
|
864
|
+
id: "native-metrics-settings",
|
|
865
|
+
title: "System Metrics",
|
|
866
|
+
fields: [
|
|
867
|
+
this.field({
|
|
868
|
+
type: "number",
|
|
869
|
+
key: "samplingIntervalMs",
|
|
870
|
+
label: "Sampling Interval",
|
|
871
|
+
description: "How often to collect system metrics",
|
|
872
|
+
min: 1e3,
|
|
873
|
+
max: 6e4,
|
|
874
|
+
step: 1e3,
|
|
875
|
+
default: 5e3,
|
|
876
|
+
unit: "ms"
|
|
877
|
+
})
|
|
878
|
+
]
|
|
879
|
+
}]
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
function parseEtime(etime) {
|
|
884
|
+
const dashParts = etime.split("-");
|
|
885
|
+
let days = 0;
|
|
886
|
+
let hms = etime;
|
|
887
|
+
if (dashParts.length === 2) {
|
|
888
|
+
days = parseInt(dashParts[0], 10) || 0;
|
|
889
|
+
hms = dashParts[1];
|
|
890
|
+
}
|
|
891
|
+
const parts = hms.split(":").map((p) => parseInt(p, 10) || 0);
|
|
892
|
+
let hours = 0, minutes = 0, seconds = 0;
|
|
893
|
+
if (parts.length === 3) [hours, minutes, seconds] = parts;
|
|
894
|
+
else if (parts.length === 2) [minutes, seconds] = parts;
|
|
895
|
+
else if (parts.length === 1) [seconds] = parts;
|
|
896
|
+
return days * 86400 + hours * 3600 + minutes * 60 + seconds;
|
|
897
|
+
}
|
|
898
|
+
//# sourceMappingURL=native-metrics.addon.js.map
|