@usex/mikrotik-mcp 6.10.0 → 6.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  toJSONSchema,
18
18
  ZodError,
19
19
  string,
20
+ ipv4,
20
21
  number,
21
22
  boolean,
22
23
  _null,
@@ -44,8 +45,6 @@ import {
44
45
  MikrotikConfigSchema2,
45
46
  getConfigSource2,
46
47
  loadConfig2,
47
- logger,
48
- deviceEndpoints,
49
48
  onConfigChanged,
50
49
  setConfig,
51
50
  getConfig,
@@ -53,7 +52,16 @@ import {
53
52
  deviceLabels,
54
53
  resolveDeviceName,
55
54
  deviceDirectory,
55
+ getDevice,
56
+ evaluateAccess,
57
+ previewAccessPolicy,
58
+ getAccessPolicy,
59
+ hasSessionNarrowing,
60
+ recentDenials,
61
+ assertDeviceAccess,
56
62
  DeviceConnectionError,
63
+ logger,
64
+ deviceEndpoints,
57
65
  isMacTelnetDevice,
58
66
  createDeviceClient,
59
67
  describeTransport,
@@ -61,28 +69,6 @@ import {
61
69
  closeAll,
62
70
  closeDevice,
63
71
  poolStatus,
64
- ScopeSchema,
65
- RememberSchema,
66
- ReviseSchema,
67
- RecallSchema,
68
- BrowseSchema,
69
- openMemoryStore,
70
- getMemoryStore,
71
- closeMemoryStore,
72
- installMemoryStore,
73
- Cmd,
74
- isEmpty,
75
- looksLikeError,
76
- commandUnsupported,
77
- riskOf,
78
- redact,
79
- createContext,
80
- evaluateAccess,
81
- previewAccessPolicy,
82
- getAccessPolicy,
83
- hasSessionNarrowing,
84
- recentDenials,
85
- assertDeviceAccess,
86
72
  getSafeModeManager,
87
73
  parseKeyValues,
88
74
  parseRouterosDate,
@@ -90,23 +76,30 @@ import {
90
76
  parseRecords,
91
77
  parseLeadingNumber,
92
78
  executeMikrotikCommand,
93
- isYes,
94
- normalizeExport2,
95
- openSnapshotStore2,
96
- captureSnapshot,
97
- startRoutingMonitor,
98
- stopRoutingMonitor,
99
- configureRecorder,
100
- getEventStore,
101
- subscribe,
102
- subscriberCount,
103
- startFlightRecorder,
104
- stopFlightRecorder,
79
+ executeMikrotikJson,
80
+ riskOf,
81
+ redact,
82
+ createContext,
83
+ Cmd,
84
+ isEmpty,
85
+ flattenLiveOutput,
86
+ looksLikeError,
87
+ commandUnsupported,
105
88
  explainUnmet,
106
89
  serializeCapabilities,
90
+ isYes,
107
91
  getCapabilities,
108
92
  peekCapabilities,
109
93
  invalidateCapabilities,
94
+ ScopeSchema,
95
+ RememberSchema,
96
+ ReviseSchema,
97
+ RecallSchema,
98
+ BrowseSchema,
99
+ openMemoryStore,
100
+ getMemoryStore,
101
+ closeMemoryStore,
102
+ installMemoryStore,
110
103
  redactChannels,
111
104
  setMcpAlertSender,
112
105
  deliver,
@@ -122,7 +115,19 @@ import {
122
115
  AlertEngine,
123
116
  setAlertEngine,
124
117
  getAlertEngine,
118
+ configureRecorder,
119
+ getEventStore,
120
+ subscribe,
121
+ subscriberCount,
125
122
  registerTools,
123
+ bandwidthServerTools,
124
+ normalizeExport2,
125
+ openSnapshotStore2,
126
+ captureSnapshot,
127
+ startRoutingMonitor,
128
+ stopRoutingMonitor,
129
+ startFlightRecorder,
130
+ stopFlightRecorder,
126
131
  clientCheckOrigin,
127
132
  noteClientPresence,
128
133
  authorizedCheck,
@@ -345,7 +350,7 @@ import {
345
350
  allToolModules2,
346
351
  ALWAYS_ON_MODULES2,
347
352
  selectToolModules2
348
- } from "./shared/cli-81s63cts.js";
353
+ } from "./shared/cli-xkhmxe9c.js";
349
354
 
350
355
  // node_modules/ajv/dist/compile/codegen/code.js
351
356
  var require_code = __commonJS(function(exports) {
@@ -6906,6 +6911,400 @@ var require_dist = __commonJS(function(exports, module) {
6906
6911
  exports.default = formatsPlugin;
6907
6912
  });
6908
6913
 
6914
+ // src/bandwidth/service.ts
6915
+ import { join, dirname as dirname2 } from "path";
6916
+
6917
+ // src/bandwidth/model.ts
6918
+ var BandwidthJobSchema = object({
6919
+ id: string().regex(/^[a-zA-Z0-9_-]{1,64}$/),
6920
+ name: string().trim().min(1).max(100),
6921
+ source: string().min(1).max(128),
6922
+ destination: string().min(1).max(128),
6923
+ sourceInterface: string().min(1).max(128),
6924
+ sourceAddress: ipv4(),
6925
+ destinationAddress: ipv4(),
6926
+ protocol: _enum(["tcp", "udp"]).default("tcp"),
6927
+ direction: _enum(["transmit", "receive", "both"]).default("both"),
6928
+ durationSeconds: number().int().min(5).max(60).default(10),
6929
+ localTxBps: number().int().min(1).max(100000000000).default(1e7),
6930
+ remoteTxBps: number().int().min(1).max(100000000000).default(1e7),
6931
+ localUdpTxSize: number().int().min(28).max(64000).default(1500),
6932
+ remoteUdpTxSize: number().int().min(28).max(64000).default(1500),
6933
+ randomData: boolean().default(false),
6934
+ connectionCount: number().int().min(1).max(255).default(1),
6935
+ reportIntervalSeconds: number().min(0.02).max(5).refine((v) => Math.abs(v * 1000 - Math.round(v * 1000)) < 0.000000001, "Use whole milliseconds").default(1),
6936
+ intervalSeconds: number().int().min(300).max(604800).default(3600),
6937
+ enabled: boolean().default(false),
6938
+ nextRunAt: number().int().nonnegative().optional()
6939
+ }).strict();
6940
+ var PATH_WARNING = "Interface and source address are route expectations, not bindings. RouterOS bandwidth-test has no documented local-address parameter. Routing chooses the source and path; policy routing, NAT, firewall and route changes can affect delivery. Transmit is source \u2192 destination; receive is destination \u2192 source. Tests consume link bandwidth and router CPU. Destination server/firewall settings are never changed.";
6941
+ function bandwidthCommand(job, credentials) {
6942
+ const cmd = new Cmd("/tool bandwidth-test").set("address", job.destinationAddress).set("direction", job.direction).set("duration", `${job.durationSeconds}s`).set("interval", `${Math.round(job.reportIntervalSeconds * 1000)}ms`).set("protocol", job.protocol).set("local-tx-speed", job.localTxBps).set("remote-tx-speed", job.remoteTxBps).bool("random-data", job.randomData);
6943
+ if (job.protocol === "udp") {
6944
+ cmd.set("local-udp-tx-size", job.localUdpTxSize).set("remote-udp-tx-size", job.remoteUdpTxSize);
6945
+ } else
6946
+ cmd.set("connection-count", job.connectionCount);
6947
+ if (credentials)
6948
+ cmd.set("user", credentials.username).set("password", credentials.password);
6949
+ return cmd.build();
6950
+ }
6951
+ function bandwidthRate(value) {
6952
+ const match = value?.match(/^(\d+(?:\.\d+)?)\s*([kMGT]?)bps$/i);
6953
+ if (!match)
6954
+ return null;
6955
+ const valueBps = Number(match[1]) * 1000 ** ({ "": 0, k: 1, m: 2, g: 3, t: 4 }[match[2].toLowerCase()] ?? 0);
6956
+ return Number.isFinite(valueBps) ? valueBps : null;
6957
+ }
6958
+ function parseBandwidthResult(raw, direction) {
6959
+ const output = flattenLiveOutput(raw);
6960
+ const fields = Object.assign({}, ...output.split(/\r?\n/).map((line) => parseKeyValues(line)));
6961
+ const txBps = direction === "receive" ? null : bandwidthRate(fields["tx-total-average"]);
6962
+ const rxBps = direction === "transmit" ? null : bandwidthRate(fields["rx-total-average"]);
6963
+ const ok = !looksLikeError(output) && fields.status === "done testing" && (direction === "receive" || txBps !== null) && (direction === "transmit" || rxBps !== null);
6964
+ const lost = fields["lost-packets"];
6965
+ return {
6966
+ status: ok ? "ok" : "failed",
6967
+ txBps: ok ? txBps : null,
6968
+ rxBps: ok ? rxBps : null,
6969
+ lostPackets: ok && lost && /^\d+$/.test(lost) && Number.isSafeInteger(Number(lost)) ? Number(lost) : null,
6970
+ message: ok ? "Completed; averages are measured from the source router." : "No complete measurement. Check destination authentication, firewall, route, device mode and server availability. Partial output is not a successful test."
6971
+ };
6972
+ }
6973
+ function prefixLength(cidr, address) {
6974
+ if (!cidr)
6975
+ return -1;
6976
+ const [network, bitsText] = cidr.split("/");
6977
+ const bits = Number(bitsText ?? 32);
6978
+ if (!ipv4().safeParse(network).success || !Number.isInteger(bits) || bits < 0 || bits > 32)
6979
+ return -1;
6980
+ const number2 = (ip) => ip.split(".").reduce((acc, octet) => acc * 256 + Number(octet), 0);
6981
+ return Math.floor(number2(network) / 2 ** (32 - bits)) === Math.floor(number2(address) / 2 ** (32 - bits)) ? bits : -1;
6982
+ }
6983
+ function expectedRoute(job, rows) {
6984
+ const candidates = rows.filter((row) => (row.active === "true" || row.active === "yes" || /A/.test(row.flags ?? "")) && !/[XI]/.test(row.flags ?? "") && row.disabled !== "true" && row.disabled !== "yes" && (row["routing-table"] ?? "main") === "main" && !row["routing-mark"] && prefixLength(row["dst-address"], job.destinationAddress) >= 0);
6985
+ const best = Math.max(-1, ...candidates.map((row) => prefixLength(row["dst-address"], job.destinationAddress)));
6986
+ const matches = candidates.filter((row) => prefixLength(row["dst-address"], job.destinationAddress) === best);
6987
+ if (matches.length !== 1)
6988
+ return false;
6989
+ const route = matches[0];
6990
+ if (["true", "yes"].includes(route.blackhole) || ["blackhole", "unreachable", "prohibit"].includes(route.type) || /B/.test(route.flags ?? ""))
6991
+ return false;
6992
+ const gateway = route["immediate-gw"] || route.gateway || "";
6993
+ if (gateway.includes(",") || gateway.includes(";"))
6994
+ return false;
6995
+ const iface = gateway.includes("%") ? gateway.split("%").at(-1) : gateway;
6996
+ return iface === job.sourceInterface && (!route["pref-src"] || route["pref-src"] === job.sourceAddress);
6997
+ }
6998
+
6999
+ // src/bandwidth/store.ts
7000
+ import { mkdirSync } from "fs";
7001
+ import { dirname } from "path";
7002
+ var BANDWIDTH_CONCURRENCY = 2;
7003
+ var LEASE_MS = 300000;
7004
+
7005
+ class BandwidthStore {
7006
+ db;
7007
+ storeId;
7008
+ constructor(db) {
7009
+ this.db = db;
7010
+ db.run("PRAGMA journal_mode=WAL");
7011
+ db.run("PRAGMA busy_timeout=5000");
7012
+ db.run("CREATE TABLE IF NOT EXISTS bandwidth_jobs (id TEXT PRIMARY KEY, body TEXT NOT NULL)");
7013
+ db.run("CREATE TABLE IF NOT EXISTS bandwidth_runs (id TEXT PRIMARY KEY, body TEXT NOT NULL, source TEXT NOT NULL, destination TEXT NOT NULL, expires INTEGER NOT NULL)");
7014
+ db.run("CREATE TABLE IF NOT EXISTS bandwidth_notifications (sequence INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL)");
7015
+ db.run("CREATE TABLE IF NOT EXISTS bandwidth_metadata (id TEXT PRIMARY KEY, value TEXT NOT NULL)");
7016
+ db.query("INSERT OR IGNORE INTO bandwidth_metadata VALUES ('storeId', ?)").run(crypto.randomUUID());
7017
+ this.storeId = db.query("SELECT value FROM bandwidth_metadata WHERE id='storeId'").get().value;
7018
+ }
7019
+ jobs() {
7020
+ return this.db.query("SELECT body FROM bandwidth_jobs ORDER BY id").all().map((r) => JSON.parse(r.body));
7021
+ }
7022
+ job(id) {
7023
+ const row = this.db.query("SELECT body FROM bandwidth_jobs WHERE id=?").get(id);
7024
+ return row ? JSON.parse(row.body) : null;
7025
+ }
7026
+ save(job) {
7027
+ this.db.query("INSERT OR REPLACE INTO bandwidth_jobs VALUES (?,?)").run(job.id, JSON.stringify(job));
7028
+ }
7029
+ remove(id) {
7030
+ this.db.query("DELETE FROM bandwidth_jobs WHERE id=?").run(id);
7031
+ }
7032
+ runs() {
7033
+ return this.db.query("SELECT body FROM bandwidth_runs ORDER BY rowid DESC LIMIT 2000").all().map((r) => JSON.parse(r.body));
7034
+ }
7035
+ finish(run) {
7036
+ this.db.transaction(() => {
7037
+ const row = this.db.query("SELECT body FROM bandwidth_runs WHERE id=?").get(run.id);
7038
+ if (!row || JSON.parse(row.body).status !== "running")
7039
+ return;
7040
+ this.db.query("UPDATE bandwidth_runs SET body=?, expires=0 WHERE id=?").run(JSON.stringify(run), run.id);
7041
+ this.db.query("INSERT INTO bandwidth_notifications(body) VALUES (?)").run(JSON.stringify(run));
7042
+ }).immediate();
7043
+ }
7044
+ recover(now) {
7045
+ const expired = this.db.query("SELECT body FROM bandwidth_runs WHERE expires > 0 AND expires <= ?").all(now);
7046
+ for (const row of expired)
7047
+ this.finish({
7048
+ ...JSON.parse(row.body),
7049
+ status: "interrupted",
7050
+ finishedAt: now,
7051
+ message: "Host stopped before recording completion; outcome unknown. Not retried."
7052
+ });
7053
+ }
7054
+ claim(run, source, destination, now) {
7055
+ return this.db.transaction(() => {
7056
+ this.recover(now);
7057
+ const active = this.db.query("SELECT source,destination FROM bandwidth_runs WHERE expires>0").all();
7058
+ if (active.length >= BANDWIDTH_CONCURRENCY || active.some((r) => [r.source, r.destination].some((d) => d === source || d === destination)))
7059
+ return false;
7060
+ if (run.trigger === "schedule") {
7061
+ const job = this.job(run.job.id);
7062
+ if (!job?.enabled || job.nextRunAt > now || job.nextRunAt !== run.job.nextRunAt)
7063
+ return false;
7064
+ this.save({ ...job, nextRunAt: now + job.intervalSeconds * 1000 });
7065
+ }
7066
+ this.db.query("INSERT INTO bandwidth_runs VALUES (?,?,?,?,?)").run(run.id, JSON.stringify(run), source, destination, now + LEASE_MS);
7067
+ return true;
7068
+ }).immediate();
7069
+ }
7070
+ renew(id, now) {
7071
+ this.db.query("UPDATE bandwidth_runs SET expires=? WHERE id=? AND expires>0").run(now + LEASE_MS, id);
7072
+ }
7073
+ notifications(after, limit) {
7074
+ const rows = this.db.query("SELECT sequence,body FROM bandwidth_notifications WHERE sequence>? ORDER BY sequence LIMIT ?").all(after, limit + 1);
7075
+ const events = rows.slice(0, limit).map((row) => ({ sequence: row.sequence, run: JSON.parse(row.body) }));
7076
+ return {
7077
+ storeId: this.storeId,
7078
+ events,
7079
+ nextCursor: events.at(-1)?.sequence ?? after,
7080
+ hasMore: rows.length > limit
7081
+ };
7082
+ }
7083
+ close() {
7084
+ this.db.close();
7085
+ }
7086
+ }
7087
+ async function openBandwidthStore(path) {
7088
+ if (path !== ":memory:")
7089
+ mkdirSync(dirname(path), { recursive: true });
7090
+ const { Database } = await import("bun:sqlite");
7091
+ return new BandwidthStore(new Database(path, { create: true }));
7092
+ }
7093
+
7094
+ // src/bandwidth/service.ts
7095
+ class BandwidthError extends Error {
7096
+ }
7097
+ function validateBandwidthJob(input) {
7098
+ const parsed = BandwidthJobSchema.safeParse(input);
7099
+ if (!parsed.success)
7100
+ throw new BandwidthError("Invalid test settings. Check IPv4 addresses, IDs, bounded duration/rates and interval (whole milliseconds).");
7101
+ const job = { ...parsed.data, nextRunAt: parsed.data.nextRunAt ?? 0 };
7102
+ try {
7103
+ job.source = resolveDeviceName(job.source);
7104
+ job.destination = resolveDeviceName(job.destination);
7105
+ if (routerIdentity(job.source) === routerIdentity(job.destination))
7106
+ throw new Error("Source and destination resolve to the same router");
7107
+ } catch {
7108
+ throw new BandwidthError("Select two different enabled configured routers.");
7109
+ }
7110
+ for (const address of [job.sourceAddress, job.destinationAddress]) {
7111
+ const first = Number(address.split(".")[0]);
7112
+ if (first === 0 || first === 127 || first >= 224 || address === "255.255.255.255")
7113
+ throw new BandwidthError("Use unicast tunnel IPv4 addresses.");
7114
+ }
7115
+ if (job.sourceAddress === job.destinationAddress)
7116
+ throw new BandwidthError("Source and destination addresses must differ.");
7117
+ return job;
7118
+ }
7119
+ function routerIdentity(name) {
7120
+ const dc = getDevice(name);
7121
+ return dc.mac ? `mac:${dc.mac.toLowerCase()}` : `host:${dc.host.toLowerCase()}`;
7122
+ }
7123
+ function bandwidthAccess(job, write) {
7124
+ try {
7125
+ assertDeviceAccess([job.source, job.destination], "bandwidth_test", write ? "WRITE" : "READ");
7126
+ } catch {
7127
+ throw new BandwidthError("Bandwidth test access denied by server policy or read-only mode.");
7128
+ }
7129
+ }
7130
+ async function bandwidthAddresses(device) {
7131
+ assertDeviceAccess([device], "bandwidth_test", "READ");
7132
+ const out = await executeMikrotikJson(new Cmd("/ip address print").raw("detail").build(), createContext(undefined, device), { maxMs: 20000 });
7133
+ return out.rows.filter((row) => row.address && row.interface && !/[XI]/.test(row.flags ?? "") && row.disabled !== "true" && row.disabled !== "yes" && row.invalid !== "true").map((row) => ({ interface: row.interface, address: row.address.split("/")[0] }));
7134
+ }
7135
+ async function preflightBandwidth(job) {
7136
+ bandwidthAccess(job, false);
7137
+ const checks = [];
7138
+ const check = (name, ok, message) => checks.push({ name, ok, message });
7139
+ try {
7140
+ const source = getDevice(job.source);
7141
+ const safe = getSafeModeManager(job.source);
7142
+ check("transport", !source.mac && !source.api && !safe.isActive && !safe.requiresRecovery, "Source must use SSH without REST or an active/recovering Safe Mode session, to enforce the test deadline.");
7143
+ const addresses = await bandwidthAddresses(job.source);
7144
+ check("source-address", addresses.some((a) => a.interface === job.sourceInterface && a.address === job.sourceAddress), "Expected source address must be assigned and enabled on the selected interface.");
7145
+ const interfaces = await executeMikrotikJson(new Cmd("/interface print").raw("detail").build(), createContext(undefined, job.source), { maxMs: 20000 });
7146
+ check("source-interface", interfaces.rows.some((r) => r.name === job.sourceInterface && (r.running === "true" || r.running === "yes" || /R/.test(r.flags ?? "")) && !/X/.test(r.flags ?? "") && r.disabled !== "true" && r.disabled !== "yes"), "Expected source interface must be enabled and running.");
7147
+ const destination = await bandwidthAddresses(job.destination);
7148
+ check("destination-address", destination.some((a) => a.address === job.destinationAddress), "Explicit destination IP must belong to the selected destination router.");
7149
+ const routes = await executeMikrotikJson(new Cmd("/ip route print").raw("detail").build(), createContext(undefined, job.source), { maxMs: 20000 });
7150
+ check("route", expectedRoute(job, routes.rows), "Require one active longest-prefix main-table route via the selected interface; if pref-src is present it must match. ECMP/unknown paths are refused. Policy routing and firewall delivery are not proven.");
7151
+ const raw = await bandwidthServerTools[0].handler({}, createContext(undefined, job.destination));
7152
+ const server = typeof raw === "string" ? parseKeyValues(raw) : {};
7153
+ check("server", typeof raw === "string" && !looksLikeError(raw) && ["yes", "true"].includes(server.enabled), "Destination bandwidth server must already be enabled. No server or firewall settings will be changed.");
7154
+ const destinationConfig = getDevice(job.destination);
7155
+ const credentials = destinationConfig.bandwidthAuth ?? destinationConfig;
7156
+ check("authentication", ["no", "false"].includes(server.authenticate) || ["yes", "true"].includes(server.authenticate) && !!credentials.username && !!credentials.password && credentials.password.length <= 32, "Authenticated tests use destination credentials from server configuration at execution time. SSH keys cannot authenticate bandwidth-test; the password must be 1\u201332 characters. No password is collected or persisted here.");
7157
+ } catch {
7158
+ check("read", false, "Read-only preflight could not finish. Check connection, permissions and RouterOS support.");
7159
+ }
7160
+ return { ready: checks.length > 0 && checks.every((c) => c.ok), checks, warning: PATH_WARNING };
7161
+ }
7162
+ var liveExecutor2 = {
7163
+ preflight: preflightBandwidth,
7164
+ async measure(job) {
7165
+ bandwidthAccess(job, true);
7166
+ const dc = getDevice(job.source);
7167
+ const safe = getSafeModeManager(job.source);
7168
+ if (dc.mac || dc.api || safe.isActive || safe.requiresRecovery)
7169
+ throw new BandwidthError("Source transport changed; rerun preflight.");
7170
+ const destination = getDevice(job.destination);
7171
+ const auth = destination.bandwidthAuth ?? destination;
7172
+ const credentials = auth.password ? { username: auth.username, password: auth.password } : undefined;
7173
+ const ctx = { device: job.source, info: () => {}, error: () => {} };
7174
+ const raw = await executeMikrotikCommand(bandwidthCommand(job, credentials), ctx, {
7175
+ maxMs: job.durationSeconds * 1000 + 12000
7176
+ });
7177
+ return parseBandwidthResult(raw, job.direction);
7178
+ }
7179
+ };
7180
+ var outstanding = new Set;
7181
+ var stopping = false;
7182
+ function launchBandwidth(store, job, trigger, executor = liveExecutor2, now = Date.now()) {
7183
+ if (stopping)
7184
+ throw new BandwidthError("Bandwidth service is shutting down.");
7185
+ bandwidthAccess(job, true);
7186
+ const source = routerIdentity(job.source);
7187
+ const destination = routerIdentity(job.destination);
7188
+ const run = {
7189
+ id: crypto.randomUUID(),
7190
+ job,
7191
+ startedAt: now,
7192
+ finishedAt: null,
7193
+ status: "running",
7194
+ trigger,
7195
+ txBps: null,
7196
+ rxBps: null,
7197
+ lostPackets: null,
7198
+ message: "Read-only preflight in progress."
7199
+ };
7200
+ if (!store.claim(run, source, destination, now))
7201
+ throw new BandwidthError("Routers are busy, concurrency limit reached, or this schedule was already claimed. Try later.");
7202
+ const done = (async () => {
7203
+ const heartbeat = setInterval(() => {
7204
+ try {
7205
+ store.renew(run.id, Date.now());
7206
+ } catch {}
7207
+ }, 1e4);
7208
+ heartbeat.unref?.();
7209
+ try {
7210
+ const preflight = await executor.preflight(job);
7211
+ if (!preflight.ready) {
7212
+ run.status = "failed";
7213
+ run.message = preflight.checks.filter((c) => !c.ok).map((c) => c.message).join(" ");
7214
+ } else {
7215
+ bandwidthAccess(job, true);
7216
+ if (source !== routerIdentity(job.source) || destination !== routerIdentity(job.destination))
7217
+ throw new BandwidthError("Router configuration changed during preflight; test refused.");
7218
+ Object.assign(run, await executor.measure(job));
7219
+ }
7220
+ } catch {
7221
+ run.status = "failed";
7222
+ run.message = "Test did not complete. Check access, transport, credentials and path preflight. Raw command/output is not stored.";
7223
+ } finally {
7224
+ clearInterval(heartbeat);
7225
+ run.finishedAt = Date.now();
7226
+ store.finish(run);
7227
+ }
7228
+ })();
7229
+ outstanding.add(done);
7230
+ done.then(() => outstanding.delete(done), () => outstanding.delete(done));
7231
+ return { run: { ...run }, done };
7232
+ }
7233
+ var storePromise;
7234
+ function bandwidthStore() {
7235
+ storePromise ??= openBandwidthStore(join(dirname2(getConfig().dashboard.dbPath), "bandwidth.db")).catch((error) => {
7236
+ storePromise = undefined;
7237
+ throw error;
7238
+ });
7239
+ return storePromise;
7240
+ }
7241
+ var timer;
7242
+ var ticking = false;
7243
+ function tickBandwidth(store, executor = liveExecutor2, now = Date.now()) {
7244
+ store.recover(now);
7245
+ const pending = [];
7246
+ for (const job of store.jobs()) {
7247
+ if (!job.enabled || job.nextRunAt > now)
7248
+ continue;
7249
+ try {
7250
+ pending.push(launchBandwidth(store, validateBandwidthJob(job), "schedule", executor, now).done);
7251
+ } catch {}
7252
+ }
7253
+ return pending;
7254
+ }
7255
+ async function startBandwidthScheduler() {
7256
+ if (timer)
7257
+ return;
7258
+ stopping = false;
7259
+ const store = await bandwidthStore();
7260
+ timer = setInterval(() => {
7261
+ if (ticking)
7262
+ return;
7263
+ ticking = true;
7264
+ try {
7265
+ for (const done of tickBandwidth(store))
7266
+ done.catch(() => logger.error("Bandwidth result could not be persisted; lease retained for recovery."));
7267
+ } catch {
7268
+ logger.error("Bandwidth scheduler tick failed; retrying on next tick.");
7269
+ } finally {
7270
+ ticking = false;
7271
+ }
7272
+ }, 5000);
7273
+ timer.unref?.();
7274
+ }
7275
+ async function stopBandwidthScheduler() {
7276
+ stopping = true;
7277
+ if (timer)
7278
+ clearInterval(timer);
7279
+ timer = undefined;
7280
+ let timeout;
7281
+ await Promise.race([
7282
+ Promise.allSettled(outstanding),
7283
+ new Promise((resolve) => {
7284
+ timeout = setTimeout(resolve, 1e4);
7285
+ })
7286
+ ]);
7287
+ if (timeout)
7288
+ clearTimeout(timeout);
7289
+ if (!outstanding.size && storePromise) {
7290
+ try {
7291
+ (await storePromise).close();
7292
+ } catch {}
7293
+ storePromise = undefined;
7294
+ }
7295
+ }
7296
+ function canReadBandwidth(job) {
7297
+ try {
7298
+ bandwidthAccess(job, false);
7299
+ return true;
7300
+ } catch {
7301
+ return false;
7302
+ }
7303
+ }
7304
+ function bandwidthDevices() {
7305
+ return listDevices().names.filter((name) => canReadBandwidth({ source: name, destination: name }));
7306
+ }
7307
+
6909
7308
  // src/cli.ts
6910
7309
  import { existsSync as existsSync2 } from "fs";
6911
7310
 
@@ -6913,7 +7312,7 @@ import { existsSync as existsSync2 } from "fs";
6913
7312
  import { spawn } from "child_process";
6914
7313
  import { readFileSync as readFileSync4 } from "fs";
6915
7314
  import { homedir as homedir5, networkInterfaces as networkInterfaces2 } from "os";
6916
- import { dirname as dirname8, join as join8 } from "path";
7315
+ import { dirname as dirname10, join as join9 } from "path";
6917
7316
  var {serve } = globalThis.Bun;
6918
7317
 
6919
7318
  // src/observability/modules.ts
@@ -6994,16 +7393,16 @@ import { createHash } from "crypto";
6994
7393
  import { constants } from "fs";
6995
7394
  import { access, lstat, open, readdir } from "fs/promises";
6996
7395
  import { homedir } from "os";
6997
- import { basename, join, resolve } from "path";
7396
+ import { basename, join as join2, resolve } from "path";
6998
7397
  import { utils } from "ssh2";
6999
- async function listSshKeys(configuredPaths, directory = join(homedir(), ".ssh")) {
7398
+ async function listSshKeys(configuredPaths, directory = join2(homedir(), ".ssh")) {
7000
7399
  const paths = new Set(configuredPaths.filter(Boolean).map((path) => resolve(path)));
7001
7400
  let warning;
7002
7401
  try {
7003
7402
  const entries = await readdir(directory, { withFileTypes: true });
7004
7403
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
7005
7404
  if (entry.isFile() && entry.name.endsWith(".pub"))
7006
- paths.add(join(directory, entry.name.slice(0, -4)));
7405
+ paths.add(join2(directory, entry.name.slice(0, -4)));
7007
7406
  }
7008
7407
  } catch (error) {
7009
7408
  if (error.code !== "ENOENT")
@@ -7059,13 +7458,13 @@ async function listSshKeys(configuredPaths, directory = join(homedir(), ".ssh"))
7059
7458
  import { createHash as createHash2 } from "crypto";
7060
7459
  import { lstat as lstat2, mkdir, open as open2, unlink } from "fs/promises";
7061
7460
  import { homedir as homedir2 } from "os";
7062
- import { join as join2 } from "path";
7461
+ import { join as join3 } from "path";
7063
7462
  import { utils as utils2 } from "ssh2";
7064
7463
  var inputSchema = object({
7065
7464
  name: string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/)
7066
7465
  }).strict();
7067
7466
  var creating = false;
7068
- async function createSshKey(input, directory = join2(homedir2(), ".ssh")) {
7467
+ async function createSshKey(input, directory = join3(homedir2(), ".ssh")) {
7069
7468
  const parsed = inputSchema.safeParse(input);
7070
7469
  if (!parsed.success)
7071
7470
  throw new Error("Use 1\u201364 letters, digits, underscores or hyphens for the key name.");
@@ -7074,7 +7473,7 @@ async function createSshKey(input, directory = join2(homedir2(), ".ssh")) {
7074
7473
  if (creating)
7075
7474
  throw new Error("A key is already being created. Wait before trying again.");
7076
7475
  creating = true;
7077
- const path = join2(directory, parsed.data.name);
7476
+ const path = join3(directory, parsed.data.name);
7078
7477
  let privateFile;
7079
7478
  let publicFile;
7080
7479
  let complete = false;
@@ -7287,14 +7686,14 @@ async function workspaceRoutes(req, url) {
7287
7686
 
7288
7687
  // src/client-check/routes.ts
7289
7688
  import { readFileSync } from "fs";
7290
- import { join as join3 } from "path";
7689
+ import { join as join4 } from "path";
7291
7690
  import { randomBytes } from "crypto";
7292
7691
  var MiB = 1048576;
7293
7692
  var budgets = new Map;
7294
7693
  async function clientCheckRoutes(req, url, peer = "unknown") {
7295
7694
  if (url.pathname === "/client-check" && req.method === "GET") {
7296
7695
  try {
7297
- return new Response(readFileSync(join3(PROJECT_ROOT, "dist/ui/client-check.html"), "utf8"), {
7696
+ return new Response(readFileSync(join4(PROJECT_ROOT, "dist/ui/client-check.html"), "utf8"), {
7298
7697
  headers: {
7299
7698
  "content-type": "text/html;charset=utf-8",
7300
7699
  "cache-control": "no-store",
@@ -7642,8 +8041,8 @@ async function openVpnRoutes(req, url, history) {
7642
8041
 
7643
8042
  // src/observability/openvpn-history.ts
7644
8043
  import { randomUUID } from "crypto";
7645
- import { chmodSync, mkdirSync } from "fs";
7646
- import { dirname } from "path";
8044
+ import { chmodSync, mkdirSync as mkdirSync2 } from "fs";
8045
+ import { dirname as dirname3 } from "path";
7647
8046
  var OPENVPN_HISTORY_INTERVAL = 15000;
7648
8047
  function sameObservedSession(previous, session, at) {
7649
8048
  if (previous.ended !== null)
@@ -7778,7 +8177,7 @@ class OpenVpnHistoryStore {
7778
8177
  }
7779
8178
  }
7780
8179
  async function openOpenVpnHistory(path) {
7781
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
8180
+ mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
7782
8181
  const { Database } = await import("bun:sqlite");
7783
8182
  const db = new Database(path, { create: true });
7784
8183
  chmodSync(path, 384);
@@ -7842,8 +8241,8 @@ function startOpenVpnHistorySampler(store) {
7842
8241
  }
7843
8242
 
7844
8243
  // src/observability/site-activity.ts
7845
- import { chmodSync as chmodSync2, mkdirSync as mkdirSync2 } from "fs";
7846
- import { dirname as dirname2 } from "path";
8244
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync3 } from "fs";
8245
+ import { dirname as dirname4 } from "path";
7847
8246
  import { isIP as isIP2 } from "net";
7848
8247
  function validSiteHost(host) {
7849
8248
  const normalized = host.toLowerCase().replace(/\.$/, "");
@@ -8110,7 +8509,7 @@ class SqliteSiteActivityStore {
8110
8509
  }
8111
8510
  async function openSiteActivityStore(path) {
8112
8511
  if (path !== ":memory:")
8113
- mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
8512
+ mkdirSync3(dirname4(path), { recursive: true, mode: 448 });
8114
8513
  const { Database } = await import("bun:sqlite");
8115
8514
  const db = new Database(path, { create: true });
8116
8515
  if (path !== ":memory:")
@@ -8438,6 +8837,119 @@ async function ipIntelligenceRoutes(req, url) {
8438
8837
  }
8439
8838
  }
8440
8839
 
8840
+ // src/bandwidth/inventory.ts
8841
+ var cache = new Map;
8842
+ onConfigChanged(() => cache.clear());
8843
+ async function bandwidthInventory(device) {
8844
+ const name = resolveDeviceName(device);
8845
+ assertDeviceAccess([name], "bandwidth_test", "READ");
8846
+ let entry = cache.get(name);
8847
+ if (!entry || entry.expires <= Date.now()) {
8848
+ const promise = Promise.all([
8849
+ executeMikrotikJson(new Cmd("/interface print").raw("detail").build(), createContext(undefined, name), { maxMs: 20000 }),
8850
+ bandwidthAddresses(name)
8851
+ ]).then(([output, addresses]) => ({
8852
+ interfaces: output.rows.filter((row) => row.name).map((row) => ({
8853
+ name: row.name,
8854
+ disabled: ["true", "yes"].includes(row.disabled) || /X/.test(row.flags ?? ""),
8855
+ running: ["true", "yes"].includes(row.running) || /R/.test(row.flags ?? "")
8856
+ })),
8857
+ addresses
8858
+ }));
8859
+ entry = { expires: Infinity, promise };
8860
+ cache.set(name, entry);
8861
+ promise.then(() => {
8862
+ const current = cache.get(name);
8863
+ if (current?.promise === promise)
8864
+ current.expires = Date.now() + 30000;
8865
+ }, () => {
8866
+ if (cache.get(name)?.promise === promise)
8867
+ cache.delete(name);
8868
+ });
8869
+ }
8870
+ const result = await entry.promise;
8871
+ assertDeviceAccess([name], "bandwidth_test", "READ");
8872
+ return result;
8873
+ }
8874
+
8875
+ // src/observability/bandwidth-routes.ts
8876
+ async function bandwidthRoutes(req, url, getStore = bandwidthStore) {
8877
+ if (url.pathname !== "/api/bandwidth" && !url.pathname.startsWith("/api/bandwidth/"))
8878
+ return null;
8879
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
8880
+ try {
8881
+ const store = await getStore();
8882
+ store.recover(Date.now());
8883
+ if (req.method === "GET" && url.pathname === "/api/bandwidth") {
8884
+ return json({
8885
+ jobs: store.jobs().filter(canReadBandwidth),
8886
+ runs: store.runs().filter((r) => canReadBandwidth(r.job)),
8887
+ devices: bandwidthDevices(),
8888
+ concurrency: BANDWIDTH_CONCURRENCY
8889
+ });
8890
+ }
8891
+ if (req.method === "GET" && url.pathname === "/api/bandwidth/notifications") {
8892
+ const after = Number(url.searchParams.get("after") ?? 0);
8893
+ const limit = Number(url.searchParams.get("limit") ?? 50);
8894
+ if (!Number.isSafeInteger(after) || after < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100)
8895
+ return json({ error: "Invalid notification cursor or limit" }, 400);
8896
+ const feed = store.notifications(after, limit);
8897
+ return json({ ...feed, events: feed.events.filter((e) => canReadBandwidth(e.run.job)) });
8898
+ }
8899
+ if (req.method === "GET" && url.pathname === "/api/bandwidth/options") {
8900
+ const device = url.searchParams.get("device");
8901
+ if (!device || !bandwidthDevices().includes(device))
8902
+ return json({ error: "Select an allowed router" }, 400);
8903
+ return json(await bandwidthInventory(device));
8904
+ }
8905
+ if (req.method !== "POST")
8906
+ return json({ error: "Method not allowed" }, 405);
8907
+ const body = JSON.parse(await readOperationBody(req));
8908
+ if (url.pathname === "/api/bandwidth/preflight") {
8909
+ const input = object({ job: unknown() }).strict().parse(body);
8910
+ return json(await preflightBandwidth(validateBandwidthJob(input.job)));
8911
+ }
8912
+ if (url.pathname === "/api/bandwidth/save") {
8913
+ const input = object({ job: unknown(), acknowledgeImpact: boolean().optional() }).strict().parse(body);
8914
+ const job = validateBandwidthJob(input.job);
8915
+ bandwidthAccess(job, true);
8916
+ const previous = store.job(job.id);
8917
+ if (previous)
8918
+ bandwidthAccess(previous, true);
8919
+ if (job.enabled && input.acknowledgeImpact !== true)
8920
+ return json({ error: "Acknowledge bandwidth/CPU impact before enabling a schedule" }, 400);
8921
+ if (!previous && store.jobs().length >= 100)
8922
+ return json({ error: "Maximum 100 saved tests" }, 400);
8923
+ job.nextRunAt = Date.now() + job.intervalSeconds * 1000;
8924
+ store.save(job);
8925
+ return json({ job });
8926
+ }
8927
+ if (url.pathname === "/api/bandwidth/run" || url.pathname === "/api/bandwidth/delete") {
8928
+ const input = object({ id: string().min(1).max(64), acknowledgeImpact: boolean().optional() }).strict().parse(body);
8929
+ const saved = store.job(input.id);
8930
+ if (!saved || !canReadBandwidth(saved))
8931
+ return json({ error: "Saved test not found" }, 404);
8932
+ bandwidthAccess(saved, true);
8933
+ if (url.pathname.endsWith("/delete")) {
8934
+ store.remove(saved.id);
8935
+ return json({ removed: saved.id });
8936
+ }
8937
+ if (input.acknowledgeImpact !== true)
8938
+ return json({ error: "Acknowledge bandwidth/CPU impact before running" }, 400);
8939
+ const { run, done } = launchBandwidth(store, validateBandwidthJob(saved), "manual");
8940
+ done.catch(() => logger.error("Bandwidth completion could not be persisted; lease retained for recovery."));
8941
+ return json({ run }, 202);
8942
+ }
8943
+ return json({ error: "Not found" }, 404);
8944
+ } catch (error) {
8945
+ if (error instanceof DashboardInputError)
8946
+ return json({ error: error.message }, error.status);
8947
+ if (error instanceof BandwidthError)
8948
+ return json({ error: error.message }, 400);
8949
+ return json({ error: "Bandwidth operation unavailable. Check settings, access and local storage." }, 400);
8950
+ }
8951
+ }
8952
+
8441
8953
  // src/observability/round-trip-routes.ts
8442
8954
  async function roundTripRoutes(req, url) {
8443
8955
  if (url.pathname === "/api/round-trip/options") {
@@ -8506,7 +9018,7 @@ async function roundTripRoutes(req, url) {
8506
9018
  // src/observability/um-report-cache.ts
8507
9019
  import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
8508
9020
  import { mkdir as mkdir2, readFile, rename, stat, unlink as unlink2, writeFile } from "fs/promises";
8509
- import { dirname as dirname3, join as join4 } from "path";
9021
+ import { dirname as dirname5, join as join5 } from "path";
8510
9022
  var MAX_BYTES = 32 * 1024 * 1024;
8511
9023
  var MAX_AGE = 24 * 60 * 60000;
8512
9024
  var sourceSchema = object({
@@ -8535,7 +9047,7 @@ function umReportCachePath(device) {
8535
9047
  name = target?.jumpVia;
8536
9048
  }
8537
9049
  const key = createHash4("sha256").update(JSON.stringify(chain)).digest("hex");
8538
- return join4(`${config.dashboard.dbPath}.um-reports`, `${key}.json`);
9050
+ return join5(`${config.dashboard.dbPath}.um-reports`, `${key}.json`);
8539
9051
  }
8540
9052
  async function loadUmReportCache(path, device, fields) {
8541
9053
  if (!path)
@@ -8571,7 +9083,7 @@ async function saveUmReportCache(path, snapshot) {
8571
9083
  const text = JSON.stringify({ version: 1, snapshot });
8572
9084
  if (Buffer.byteLength(text) > MAX_BYTES)
8573
9085
  return false;
8574
- await mkdir2(dirname3(path), { recursive: true, mode: 448 });
9086
+ await mkdir2(dirname5(path), { recursive: true, mode: 448 });
8575
9087
  await writeFile(temp, text, { encoding: "utf8", mode: 384, flag: "wx" });
8576
9088
  await rename(temp, path);
8577
9089
  return true;
@@ -8630,8 +9142,8 @@ function umConnectionDate(value) {
8630
9142
  }
8631
9143
  return normalized;
8632
9144
  }
8633
- var cache = new Map;
8634
- onConfigChanged(() => cache.clear());
9145
+ var cache2 = new Map;
9146
+ onConfigChanged(() => cache2.clear());
8635
9147
  function getUmLastConnections(device) {
8636
9148
  try {
8637
9149
  assertDeviceAccess([device], "list_user_manager_sessions", "READ");
@@ -8639,7 +9151,7 @@ function getUmLastConnections(device) {
8639
9151
  return { status: "unavailable", values: new Map };
8640
9152
  }
8641
9153
  const config = getConfig();
8642
- let entry = cache.get(device);
9154
+ let entry = cache2.get(device);
8643
9155
  if (!entry || entry.config !== config) {
8644
9156
  entry = {
8645
9157
  config,
@@ -8650,7 +9162,7 @@ function getUmLastConnections(device) {
8650
9162
  retryAt: 0,
8651
9163
  failed: false
8652
9164
  };
8653
- cache.set(device, entry);
9165
+ cache2.set(device, entry);
8654
9166
  }
8655
9167
  const target = entry;
8656
9168
  if (!target.pending && Date.now() >= target.retryAt) {
@@ -8939,8 +9451,8 @@ async function collect(device, progress) {
8939
9451
  throw new Error("Configuration changed during report collection.");
8940
9452
  return { device, collectedAt: Date.now(), collectionMs: Date.now() - start, clock, sources };
8941
9453
  }
8942
- var cache2 = new Map;
8943
- onConfigChanged(() => cache2.clear());
9454
+ var cache3 = new Map;
9455
+ onConfigChanged(() => cache3.clear());
8944
9456
  var freshnessMs = (value) => Math.max(CACHE_MS2, Math.min(900000, (value?.collectionMs ?? 0) * 5));
8945
9457
  async function getUmSnapshot(device, refresh = false, wait = true) {
8946
9458
  const name = resolveDeviceName(device);
@@ -8954,12 +9466,12 @@ async function getUmSnapshot(device, refresh = false, wait = true) {
8954
9466
  "get_user_manager_settings"
8955
9467
  ])
8956
9468
  assertDeviceAccess([name], tool, "READ");
8957
- let entry = cache2.get(name);
9469
+ let entry = cache3.get(name);
8958
9470
  const config = getConfig();
8959
9471
  const path = umReportCachePath(name);
8960
9472
  if (!entry) {
8961
9473
  entry = { retryAt: 0, progress: { source: "users", completed: 0, total: null } };
8962
- cache2.set(name, entry);
9474
+ cache3.set(name, entry);
8963
9475
  const target = entry;
8964
9476
  target.restored = loadUmReportCache(path, name, UM_REPORT_FIELDS).then((value) => {
8965
9477
  target.value = value;
@@ -9294,14 +9806,14 @@ function buildUmReport(snapshot, query) {
9294
9806
  // src/observability/config-history.ts
9295
9807
  import {
9296
9808
  existsSync,
9297
- mkdirSync as mkdirSync3,
9809
+ mkdirSync as mkdirSync4,
9298
9810
  readFileSync as readFileSync2,
9299
9811
  readdirSync,
9300
9812
  rmSync,
9301
9813
  statSync,
9302
9814
  writeFileSync
9303
9815
  } from "fs";
9304
- import { join as join5 } from "path";
9816
+ import { join as join6 } from "path";
9305
9817
  var AUTO_RETENTION = 50;
9306
9818
  function historyDir() {
9307
9819
  return process.env.MIKROTIK_CONFIG_HISTORY_DIR || DEFAULT_CONFIG_HISTORY_DIR2;
@@ -9320,7 +9832,7 @@ function listVersions() {
9320
9832
  if (!/^v\d+\.json$/.test(f))
9321
9833
  continue;
9322
9834
  try {
9323
- const raw = readFileSync2(join5(dir, f), "utf8");
9835
+ const raw = readFileSync2(join6(dir, f), "utf8");
9324
9836
  const parsed = JSON.parse(raw);
9325
9837
  out.push({
9326
9838
  id: f.replace(/\.json$/, ""),
@@ -9334,11 +9846,11 @@ function listVersions() {
9334
9846
  return out.sort((a, b) => b.ts - a.ts);
9335
9847
  }
9336
9848
  function readVersion(id) {
9337
- const raw = readFileSync2(join5(historyDir(), idToFile(id)), "utf8");
9849
+ const raw = readFileSync2(join6(historyDir(), idToFile(id)), "utf8");
9338
9850
  return JSON.parse(raw);
9339
9851
  }
9340
9852
  function deleteVersion(id) {
9341
- const p = join5(historyDir(), idToFile(id));
9853
+ const p = join6(historyDir(), idToFile(id));
9342
9854
  if (!existsSync(p))
9343
9855
  return false;
9344
9856
  rmSync(p);
@@ -9346,12 +9858,12 @@ function deleteVersion(id) {
9346
9858
  }
9347
9859
  function recordVersion(config, kind, now, label) {
9348
9860
  const dir = historyDir();
9349
- mkdirSync3(dir, { recursive: true });
9861
+ mkdirSync4(dir, { recursive: true });
9350
9862
  let ts = now;
9351
- while (existsSync(join5(dir, `v${ts}.json`)))
9863
+ while (existsSync(join6(dir, `v${ts}.json`)))
9352
9864
  ts++;
9353
9865
  const body = { ts, kind, label, config };
9354
- writeFileSync(join5(dir, `v${ts}.json`), `${JSON.stringify(body, null, 2)}
9866
+ writeFileSync(join6(dir, `v${ts}.json`), `${JSON.stringify(body, null, 2)}
9355
9867
  `, "utf8");
9356
9868
  pruneAuto(dir);
9357
9869
  return {
@@ -9368,7 +9880,7 @@ function pruneAuto(dir) {
9368
9880
  return;
9369
9881
  for (const v of autos.slice(AUTO_RETENTION)) {
9370
9882
  try {
9371
- rmSync(join5(dir, `${v.id}.json`));
9883
+ rmSync(join6(dir, `${v.id}.json`));
9372
9884
  } catch {}
9373
9885
  }
9374
9886
  }
@@ -9387,7 +9899,7 @@ function historyBytes() {
9387
9899
  if (!/^v\d+\.json$/.test(f))
9388
9900
  continue;
9389
9901
  try {
9390
- total += statSync(join5(dir, f)).size;
9902
+ total += statSync(join6(dir, f)).size;
9391
9903
  } catch {}
9392
9904
  }
9393
9905
  return total;
@@ -9395,7 +9907,7 @@ function historyBytes() {
9395
9907
 
9396
9908
  // src/prompts/index.ts
9397
9909
  import { readFileSync as readFileSync3, readdirSync as readdirSync2 } from "fs";
9398
- import { join as join6 } from "path";
9910
+ import { join as join7 } from "path";
9399
9911
 
9400
9912
  // src/txn/guidance.ts
9401
9913
  var TRANSACTION_TOOL_NAMES = [
@@ -9545,7 +10057,7 @@ function listPrompts() {
9545
10057
  const out = [];
9546
10058
  for (const file of files) {
9547
10059
  try {
9548
- const parsed = parseFrontmatter(readFileSync3(join6(PROMPTS_DIR, file), "utf8"));
10060
+ const parsed = parseFrontmatter(readFileSync3(join7(PROMPTS_DIR, file), "utf8"));
9549
10061
  if (parsed) {
9550
10062
  out.push({
9551
10063
  name: parsed.name,
@@ -9572,7 +10084,7 @@ function registerPrompts(server, opts = {}) {
9572
10084
  for (const file of files) {
9573
10085
  let parsed;
9574
10086
  try {
9575
- parsed = parseFrontmatter(readFileSync3(join6(PROMPTS_DIR, file), "utf8"));
10087
+ parsed = parseFrontmatter(readFileSync3(join7(PROMPTS_DIR, file), "utf8"));
9576
10088
  } catch (e) {
9577
10089
  logger.warn(`Skipping prompt ${file}: ${String(e)}`);
9578
10090
  continue;
@@ -9674,14 +10186,14 @@ async function setCapsmanManager(ctx, input) {
9674
10186
  }
9675
10187
 
9676
10188
  // src/observability/flags.ts
9677
- import { join as join7 } from "path";
10189
+ import { join as join8 } from "path";
9678
10190
  import { mkdir as mkdir3, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
9679
10191
  import { homedir as homedir4 } from "os";
9680
10192
  var LOG_TAG = "mikrotik-mcp";
9681
10193
  var CODE_RE = /^[a-z]{2}$/;
9682
10194
  var sourceUrl = (code) => `https://hatscripts.github.io/circle-flags/flags/${code}.svg`;
9683
- var VENDOR_DIR = join7(PROJECT_ROOT, "assets", "flags");
9684
- var CACHE_DIR = join7(homedir4(), ".mikrotik-mcp", "flags");
10195
+ var VENDOR_DIR = join8(PROJECT_ROOT, "assets", "flags");
10196
+ var CACHE_DIR = join8(homedir4(), ".mikrotik-mcp", "flags");
9685
10197
  var mem = new Map;
9686
10198
  async function flagSvg(code) {
9687
10199
  const c = code.toLowerCase();
@@ -9690,7 +10202,7 @@ async function flagSvg(code) {
9690
10202
  const cached = mem.get(c);
9691
10203
  if (cached !== undefined)
9692
10204
  return cached;
9693
- for (const file of [join7(VENDOR_DIR, `${c}.svg`), join7(CACHE_DIR, `${c}.svg`)]) {
10205
+ for (const file of [join8(VENDOR_DIR, `${c}.svg`), join8(CACHE_DIR, `${c}.svg`)]) {
9694
10206
  try {
9695
10207
  const svg = await readFile2(file, "utf8");
9696
10208
  mem.set(c, svg);
@@ -9706,7 +10218,7 @@ async function flagSvg(code) {
9706
10218
  }
9707
10219
  const svg = await res.text();
9708
10220
  mem.set(c, svg);
9709
- mkdir3(CACHE_DIR, { recursive: true }).then(() => writeFile2(join7(CACHE_DIR, `${c}.svg`), svg)).catch(() => {});
10221
+ mkdir3(CACHE_DIR, { recursive: true }).then(() => writeFile2(join8(CACHE_DIR, `${c}.svg`), svg)).catch(() => {});
9710
10222
  return svg;
9711
10223
  } catch (e) {
9712
10224
  logger.warn(`[${LOG_TAG}] flag fetch failed for '${c}': ${e instanceof Error ? e.message : String(e)}`);
@@ -9933,8 +10445,8 @@ data: ${JSON.stringify(sample)}
9933
10445
  }
9934
10446
 
9935
10447
  // src/observability/store.ts
9936
- import { mkdirSync as mkdirSync4 } from "fs";
9937
- import { dirname as dirname4 } from "path";
10448
+ import { mkdirSync as mkdirSync5 } from "fs";
10449
+ import { dirname as dirname6 } from "path";
9938
10450
  function rowToEvent(r) {
9939
10451
  return {
9940
10452
  id: r.id,
@@ -10120,7 +10632,7 @@ class SqliteEventStore {
10120
10632
  async function openSqliteStore(path) {
10121
10633
  if (path !== ":memory:") {
10122
10634
  try {
10123
- mkdirSync4(dirname4(path), { recursive: true });
10635
+ mkdirSync5(dirname6(path), { recursive: true });
10124
10636
  } catch {}
10125
10637
  }
10126
10638
  const { Database } = await import("bun:sqlite");
@@ -10129,8 +10641,8 @@ async function openSqliteStore(path) {
10129
10641
  }
10130
10642
 
10131
10643
  // src/observability/capsman-store.ts
10132
- import { mkdirSync as mkdirSync5 } from "fs";
10133
- import { dirname as dirname5 } from "path";
10644
+ import { mkdirSync as mkdirSync6 } from "fs";
10645
+ import { dirname as dirname7 } from "path";
10134
10646
  function summariseRadioSamples(rows) {
10135
10647
  const byRadio = new Map;
10136
10648
  for (const r of rows) {
@@ -10220,7 +10732,7 @@ class SqliteCapsmanStore {
10220
10732
  async function openCapsmanStore(path) {
10221
10733
  if (path !== ":memory:") {
10222
10734
  try {
10223
- mkdirSync5(dirname5(path), { recursive: true });
10735
+ mkdirSync6(dirname7(path), { recursive: true });
10224
10736
  } catch {}
10225
10737
  }
10226
10738
  const { Database } = await import("bun:sqlite");
@@ -10234,7 +10746,7 @@ var CAPSMAN_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
10234
10746
  var DEFAULT_CAPSMAN_INTERVAL_MS = 5 * 60000;
10235
10747
  var MIN_CAPSMAN_INTERVAL_MS = 60000;
10236
10748
  var MAX_CAPSMAN_INTERVAL_MS = 6 * 60 * 60000;
10237
- var timer = null;
10749
+ var timer2 = null;
10238
10750
  var inFlight = false;
10239
10751
  var noCapsman = new Set;
10240
10752
  function clampInterval(ms) {
@@ -10289,18 +10801,18 @@ async function sampleCapsmanOnce(store) {
10289
10801
  function startCapsmanSampler(store, intervalMs = DEFAULT_CAPSMAN_INTERVAL_MS) {
10290
10802
  const ms = clampInterval(intervalMs);
10291
10803
  sampleCapsmanOnce(store);
10292
- timer = setInterval(() => void sampleCapsmanOnce(store), ms);
10804
+ timer2 = setInterval(() => void sampleCapsmanOnce(store), ms);
10293
10805
  }
10294
10806
  function stopCapsmanSampler() {
10295
- if (timer) {
10296
- clearInterval(timer);
10297
- timer = null;
10807
+ if (timer2) {
10808
+ clearInterval(timer2);
10809
+ timer2 = null;
10298
10810
  }
10299
10811
  }
10300
10812
 
10301
10813
  // src/observability/usage-store.ts
10302
- import { mkdirSync as mkdirSync6 } from "fs";
10303
- import { dirname as dirname6 } from "path";
10814
+ import { mkdirSync as mkdirSync7 } from "fs";
10815
+ import { dirname as dirname8 } from "path";
10304
10816
  function dayOf(ts) {
10305
10817
  return new Date(ts).toISOString().slice(0, 10);
10306
10818
  }
@@ -10437,7 +10949,7 @@ class SqliteUsageStore {
10437
10949
  async function openUsageStore(path) {
10438
10950
  if (path !== ":memory:") {
10439
10951
  try {
10440
- mkdirSync6(dirname6(path), { recursive: true });
10952
+ mkdirSync7(dirname8(path), { recursive: true });
10441
10953
  } catch {}
10442
10954
  }
10443
10955
  const { Database } = await import("bun:sqlite");
@@ -10457,7 +10969,7 @@ var USAGE_RETENTION_MS = 93 * 24 * 60 * 60 * 1000;
10457
10969
  var DEFAULT_USAGE_INTERVAL_MS = 60000;
10458
10970
  var MIN_USAGE_INTERVAL_MS = 30000;
10459
10971
  var MAX_USAGE_INTERVAL_MS = 6 * 60 * 60000;
10460
- var timer2 = null;
10972
+ var timer3 = null;
10461
10973
  var inFlight2 = false;
10462
10974
  var currentStore = null;
10463
10975
  var currentIntervalMs = DEFAULT_USAGE_INTERVAL_MS;
@@ -10560,25 +11072,25 @@ function startUsageSampler(store, intervalMs = DEFAULT_USAGE_INTERVAL_MS) {
10560
11072
  currentStore = store;
10561
11073
  currentIntervalMs = clampInterval2(intervalMs);
10562
11074
  sampleUsageOnce(store);
10563
- timer2 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
11075
+ timer3 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
10564
11076
  }
10565
11077
  function getUsageSamplerInterval() {
10566
11078
  return currentIntervalMs;
10567
11079
  }
10568
11080
  function setUsageSamplerInterval(intervalMs) {
10569
11081
  currentIntervalMs = clampInterval2(intervalMs);
10570
- if (timer2)
10571
- clearInterval(timer2);
11082
+ if (timer3)
11083
+ clearInterval(timer3);
10572
11084
  if (currentStore) {
10573
11085
  const store = currentStore;
10574
- timer2 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
11086
+ timer3 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
10575
11087
  }
10576
11088
  return currentIntervalMs;
10577
11089
  }
10578
11090
  function stopUsageSampler() {
10579
- if (timer2) {
10580
- clearInterval(timer2);
10581
- timer2 = null;
11091
+ if (timer3) {
11092
+ clearInterval(timer3);
11093
+ timer3 = null;
10582
11094
  }
10583
11095
  currentStore = null;
10584
11096
  }
@@ -10677,11 +11189,11 @@ function computeStats(events, opts) {
10677
11189
  }
10678
11190
 
10679
11191
  // src/observability/drift-routes.ts
10680
- var storePromise = null;
11192
+ var storePromise2 = null;
10681
11193
  function getStore() {
10682
- if (!storePromise)
10683
- storePromise = openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
10684
- return storePromise;
11194
+ if (!storePromise2)
11195
+ storePromise2 = openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
11196
+ return storePromise2;
10685
11197
  }
10686
11198
  var JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
10687
11199
  function json(body, status = 200) {
@@ -11284,8 +11796,8 @@ async function rolloutRoutes(req, url) {
11284
11796
  }
11285
11797
 
11286
11798
  // src/policy/results.ts
11287
- import { mkdirSync as mkdirSync7 } from "fs";
11288
- import { dirname as dirname7 } from "path";
11799
+ import { mkdirSync as mkdirSync8 } from "fs";
11800
+ import { dirname as dirname9 } from "path";
11289
11801
  var SCHEMA_STATEMENTS4 = [
11290
11802
  `CREATE TABLE IF NOT EXISTS policy_results (
11291
11803
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -11345,17 +11857,17 @@ class SqlitePolicyResultStore {
11345
11857
  async function openPolicyResultStore(path) {
11346
11858
  if (path !== ":memory:") {
11347
11859
  try {
11348
- mkdirSync7(dirname7(path), { recursive: true });
11860
+ mkdirSync8(dirname9(path), { recursive: true });
11349
11861
  } catch {}
11350
11862
  }
11351
11863
  const { Database } = await import("bun:sqlite");
11352
11864
  const db = new Database(path, { create: true });
11353
11865
  return new SqlitePolicyResultStore(db);
11354
11866
  }
11355
- var storePromise2 = null;
11867
+ var storePromise3 = null;
11356
11868
  function store() {
11357
- storePromise2 ??= openPolicyResultStore(DEFAULT_SNAPSHOT_DB2);
11358
- return storePromise2;
11869
+ storePromise3 ??= openPolicyResultStore(DEFAULT_SNAPSHOT_DB2);
11870
+ return storePromise3;
11359
11871
  }
11360
11872
  async function recordPolicyResult(report) {
11361
11873
  try {
@@ -11459,10 +11971,10 @@ function json8(body, status = 200) {
11459
11971
  async function bodyJson3(req) {
11460
11972
  return await req.json().catch(() => ({}));
11461
11973
  }
11462
- var storePromise3 = null;
11974
+ var storePromise4 = null;
11463
11975
  function snapshots() {
11464
- storePromise3 ??= openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
11465
- return storePromise3;
11976
+ storePromise4 ??= openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
11977
+ return storePromise4;
11466
11978
  }
11467
11979
  async function configFor(body) {
11468
11980
  if (body.configText)
@@ -11787,10 +12299,10 @@ var JSON_HEADERS9 = { "content-type": "application/json; charset=utf-8" };
11787
12299
  function json10(body, status = 200) {
11788
12300
  return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS9 });
11789
12301
  }
11790
- var storePromise4 = null;
12302
+ var storePromise5 = null;
11791
12303
  function snapshots2() {
11792
- storePromise4 ??= openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
11793
- return storePromise4;
12304
+ storePromise5 ??= openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
12305
+ return storePromise5;
11794
12306
  }
11795
12307
  async function configFor2(device, snapshotId) {
11796
12308
  if (snapshotId) {
@@ -12442,7 +12954,7 @@ spawn error: ${String(e)}` });
12442
12954
  }
12443
12955
  function dashboardHtml() {
12444
12956
  try {
12445
- return readFileSync4(join8(UI_DIST_DIR, "observability.html"), "utf8");
12957
+ return readFileSync4(join9(UI_DIST_DIR, "observability.html"), "utf8");
12446
12958
  } catch {
12447
12959
  return `<!doctype html><meta charset=utf-8><body style="font:14px system-ui;padding:24px;background:#0b0d10;color:#e8eaed">
12448
12960
  <h2>MikroTik MCP \u2014 Observability Dashboard</h2>
@@ -13378,7 +13890,7 @@ async function featureRoutes(req, url) {
13378
13890
  const raw = b?.dir?.trim();
13379
13891
  if (!raw)
13380
13892
  return json14({ error: "dir required" }, 400);
13381
- const dir = raw === "~" || raw.startsWith("~/") ? join8(homedir5(), raw.slice(1)) : raw;
13893
+ const dir = raw === "~" || raw.startsWith("~/") ? join9(homedir5(), raw.slice(1)) : raw;
13382
13894
  const next = { ...getConfig(), backupDir: dir };
13383
13895
  setConfig(next);
13384
13896
  try {
@@ -13489,7 +14001,7 @@ async function runDashboard(cfg, transportLabel) {
13489
14001
  let openVpnHistory;
13490
14002
  let stopOpenVpnHistory;
13491
14003
  try {
13492
- openVpnHistory = await openOpenVpnHistory(join8(dirname8(cfg.dbPath), "openvpn-history.db"));
14004
+ openVpnHistory = await openOpenVpnHistory(join9(dirname10(cfg.dbPath), "openvpn-history.db"));
13493
14005
  stopOpenVpnHistory = startOpenVpnHistorySampler(openVpnHistory);
13494
14006
  } catch (e) {
13495
14007
  logger.warn(`[${SERVER_TAG3}] OpenVPN history disabled: ${String(e)}`);
@@ -13508,7 +14020,7 @@ async function runDashboard(cfg, transportLabel) {
13508
14020
  }
13509
14021
  }
13510
14022
  try {
13511
- siteActivity = await openSiteActivityStore(join8(dirname8(cfg.dbPath), "site-activity.db"));
14023
+ siteActivity = await openSiteActivityStore(join9(dirname10(cfg.dbPath), "site-activity.db"));
13512
14024
  stopSiteActivity = await startSiteActivityCollector(siteActivity, openVpnHistory);
13513
14025
  } catch (e) {
13514
14026
  logger.warn(`[${SERVER_TAG3}] Site activity unavailable: ${String(e)}`);
@@ -13516,13 +14028,13 @@ async function runDashboard(cfg, transportLabel) {
13516
14028
  siteActivity = undefined;
13517
14029
  }
13518
14030
  try {
13519
- usageStore = await openUsageStore(join8(dirname8(cfg.dbPath), "usage.db"));
14031
+ usageStore = await openUsageStore(join9(dirname10(cfg.dbPath), "usage.db"));
13520
14032
  startUsageSampler(usageStore);
13521
14033
  } catch (e) {
13522
14034
  logger.warn(`[${SERVER_TAG3}] usage history disabled: ${String(e)}`);
13523
14035
  }
13524
14036
  try {
13525
- capsmanStore = await openCapsmanStore(join8(dirname8(cfg.dbPath), "capsman.db"));
14037
+ capsmanStore = await openCapsmanStore(join9(dirname10(cfg.dbPath), "capsman.db"));
13526
14038
  startCapsmanSampler(capsmanStore);
13527
14039
  } catch (e) {
13528
14040
  logger.warn(`[${SERVER_TAG3}] capsman trends disabled: ${String(e)}`);
@@ -13602,6 +14114,9 @@ async function runDashboard(cfg, transportLabel) {
13602
14114
  const ipIntelligenceResp = await ipIntelligenceRoutes(req, url);
13603
14115
  if (ipIntelligenceResp)
13604
14116
  return ipIntelligenceResp;
14117
+ const bandwidthResp = await bandwidthRoutes(req, url);
14118
+ if (bandwidthResp)
14119
+ return bandwidthResp;
13605
14120
  const roundTripResp = await roundTripRoutes(req, url);
13606
14121
  if (roundTripResp)
13607
14122
  return roundTripResp;
@@ -23754,7 +24269,7 @@ async function printBanner() {
23754
24269
 
23755
24270
  // src/alerts/sampler.ts
23756
24271
  var DEFAULT_ALERT_SAMPLE_MS = 30000;
23757
- var timer3 = null;
24272
+ var timer4 = null;
23758
24273
  var snapshotStorePromise = null;
23759
24274
  function getSnapshotStore() {
23760
24275
  snapshotStorePromise ??= openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
@@ -23832,18 +24347,18 @@ async function sampleAlertsOnce(now = Date.now()) {
23832
24347
  }
23833
24348
  function startAlertSampler(intervalMs = DEFAULT_ALERT_SAMPLE_MS) {
23834
24349
  stopAlertSampler();
23835
- timer3 = setInterval(() => {
24350
+ timer4 = setInterval(() => {
23836
24351
  sampleAlertsOnce().catch((e) => {
23837
24352
  logger.debug(`[alerts] sampler tick failed: ${e instanceof Error ? e.message : String(e)}`);
23838
24353
  });
23839
24354
  }, intervalMs);
23840
- timer3.unref?.();
24355
+ timer4.unref?.();
23841
24356
  logger.debug(`[alerts] metric sampler started (${intervalMs}ms)`);
23842
24357
  }
23843
24358
  function stopAlertSampler() {
23844
- if (timer3)
23845
- clearInterval(timer3);
23846
- timer3 = null;
24359
+ if (timer4)
24360
+ clearInterval(timer4);
24361
+ timer4 = null;
23847
24362
  }
23848
24363
 
23849
24364
  // src/cli.ts
@@ -24015,6 +24530,7 @@ async function main() {
24015
24530
  logger.error(`Alerting disabled \u2014 invalid rules: ${e instanceof Error ? e.message : String(e)}`);
24016
24531
  }
24017
24532
  }
24533
+ startBandwidthScheduler().catch(() => logger.error("Bandwidth scheduler unavailable; check local storage."));
24018
24534
  startScheduler().catch((e) => {
24019
24535
  logger.error(`Scheduled audits disabled: ${e instanceof Error ? e.message : String(e)}`);
24020
24536
  });
@@ -24024,11 +24540,12 @@ async function main() {
24024
24540
  logger.error(`Attack detection disabled: ${e instanceof Error ? e.message : String(e)}`);
24025
24541
  }
24026
24542
  let shuttingDown = false;
24027
- const shutdown = (signal) => {
24543
+ const shutdown = async (signal) => {
24028
24544
  if (shuttingDown)
24029
24545
  return;
24030
24546
  shuttingDown = true;
24031
24547
  logger.info(`Received ${signal}, shutting down\u2026`);
24548
+ await stopBandwidthScheduler();
24032
24549
  closeAll();
24033
24550
  closeMemoryStore();
24034
24551
  stopAlertSampler();