@usex/mikrotik-mcp 5.13.0 → 5.15.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
@@ -16770,6 +16770,8 @@ function stripAnsi(text) {
16770
16770
  return text.replace(ANSI_RE, "");
16771
16771
  }
16772
16772
  var CTRL_X = "\x18";
16773
+ var PRINT_PAGER_RE = /(?:^|[\r\n])-- \[Q quit\|D dump\|(?:up\||left\||right\|)*down\][ \t\r]*$/;
16774
+ var UNCERTAIN_SESSION = "Safe Mode session is uncertain after a command timeout. Further commands and commit are " + "blocked; call rollback_safe_mode, inspect device state, and re-enable Safe Mode before retrying.";
16773
16775
  var IDLE_TIMEOUT_MS = 15000;
16774
16776
  var HARD_CAP_MS = 120000;
16775
16777
  function isSafeModeActivated(response) {
@@ -16778,7 +16780,8 @@ function isSafeModeActivated(response) {
16778
16780
  return /safe mode[^\n]*\b(?:success|taken|enabled|active)\b/i.test(response);
16779
16781
  }
16780
16782
  function lastNonEmptyLine(response) {
16781
- const lines = response.replace(/\r/g, "").split(`
16783
+ const lines = response.replace(/\r/g, `
16784
+ `).split(`
16782
16785
  `).map((l) => l.trimEnd()).filter(Boolean);
16783
16786
  return lines.at(-1) ?? "";
16784
16787
  }
@@ -16794,6 +16797,8 @@ class SafeModeManager {
16794
16797
  channel = null;
16795
16798
  active = false;
16796
16799
  droppedUnexpectedly = false;
16800
+ uncertain = false;
16801
+ probeSequence = 0;
16797
16802
  queue = Promise.resolve();
16798
16803
  constructor(deviceName) {
16799
16804
  this.deviceName = deviceName;
@@ -16813,8 +16818,9 @@ class SafeModeManager {
16813
16818
  enable() {
16814
16819
  return this.lock(async () => {
16815
16820
  if (this.active)
16816
- return "Safe mode is already active.";
16821
+ return this.uncertain ? `Error: ${UNCERTAIN_SESSION}` : "Safe mode is already active.";
16817
16822
  this.droppedUnexpectedly = false;
16823
+ this.uncertain = false;
16818
16824
  const dc = getDevice(this.deviceName);
16819
16825
  if (dc.mac) {
16820
16826
  return "Error: Safe Mode is not supported for a MAC-Telnet device " + `('${this.deviceName}' is reached by MAC ${dc.mac}). ` + "Connect over SSH (configure host/credentials) to use Safe Mode.";
@@ -16851,12 +16857,15 @@ class SafeModeManager {
16851
16857
  if (!this.active || !this.channel) {
16852
16858
  throw new Error("Safe mode session is not active.");
16853
16859
  }
16854
- const response = this.readUntilPrompt();
16860
+ if (this.uncertain)
16861
+ throw new Error(UNCERTAIN_SESSION);
16862
+ const response = this.readUntilPrompt(IDLE_TIMEOUT_MS, undefined, HARD_CAP_MS, true);
16855
16863
  this.channel.write(`${command}
16856
16864
  `);
16857
16865
  const { text, timedOut } = await response;
16858
16866
  if (timedOut) {
16859
- throw new Error(`Safe Mode command did not return a recognized prompt before the timeout (command: ${command}). ` + "Execution may have occurred; do not retry the write blindly. Inspect the session " + "and roll back if its state cannot be verified.");
16867
+ this.uncertain = true;
16868
+ throw new Error(`Safe Mode command did not return a recognized prompt before the timeout (command: ${command}). ` + `Execution may have occurred; do not retry the write blindly. ${UNCERTAIN_SESSION}`);
16860
16869
  }
16861
16870
  return this.extractOutput(text, command);
16862
16871
  });
@@ -16873,6 +16882,8 @@ class SafeModeManager {
16873
16882
  if (!this.active || !this.channel) {
16874
16883
  return { ok: true, message: "Safe mode is not active. Nothing to commit." };
16875
16884
  }
16885
+ if (this.uncertain)
16886
+ return { ok: false, message: UNCERTAIN_SESSION };
16876
16887
  const before = await this.probeMode();
16877
16888
  if (before === "released") {
16878
16889
  this.cleanup();
@@ -16922,6 +16933,8 @@ class SafeModeManager {
16922
16933
  if (this.droppedUnexpectedly) {
16923
16934
  return "Safe mode session DROPPED unexpectedly \u2014 RouterOS auto-reverted all staged changes; they " + "were NOT saved. Re-enable Safe Mode and re-apply, or apply changes directly (verify each with a read).";
16924
16935
  }
16936
+ if (this.uncertain && this.active)
16937
+ return UNCERTAIN_SESSION;
16925
16938
  return this.active ? "Safe mode is ACTIVE. Changes are pending \u2014 they are NOT yet persisted. " + "Call commit_safe_mode to persist or rollback_safe_mode to revert." : "Safe mode is NOT active. Changes take effect and persist immediately.";
16926
16939
  }
16927
16940
  handleUnexpectedDrop = () => {
@@ -16930,7 +16943,7 @@ class SafeModeManager {
16930
16943
  this.droppedUnexpectedly = true;
16931
16944
  this.cleanup();
16932
16945
  };
16933
- readUntilPrompt(idleMs = IDLE_TIMEOUT_MS, isDone = (c) => PROMPT_RE.test(c), hardCapMs = HARD_CAP_MS) {
16946
+ readUntilPrompt(idleMs = IDLE_TIMEOUT_MS, isDone = (c) => PROMPT_RE.test(c), hardCapMs = HARD_CAP_MS, drainPrintPager = false) {
16934
16947
  const channel = this.channel;
16935
16948
  if (!channel)
16936
16949
  return Promise.resolve({ text: "", timedOut: false });
@@ -16946,8 +16959,15 @@ class SafeModeManager {
16946
16959
  buf += decodeOutput(chunk);
16947
16960
  armIdle();
16948
16961
  const cleaned = stripAnsi(buf);
16949
- if (isDone(cleaned))
16962
+ if (isDone(cleaned)) {
16950
16963
  finish(cleaned, false);
16964
+ return;
16965
+ }
16966
+ const pager = drainPrintPager ? PRINT_PAGER_RE.exec(cleaned) : null;
16967
+ if (pager) {
16968
+ buf = cleaned.slice(0, pager.index);
16969
+ channel.write(" ");
16970
+ }
16951
16971
  }
16952
16972
  function finish(result, timedOut) {
16953
16973
  clearTimeout(idleTimer);
@@ -16962,7 +16982,7 @@ class SafeModeManager {
16962
16982
  async probeMode() {
16963
16983
  if (!this.channel)
16964
16984
  return "unknown";
16965
- const token = "__MCP_SAFEMODE_PROBE__";
16985
+ const token = `__MCP_SAFEMODE_PROBE_${++this.probeSequence}__`;
16966
16986
  const response = this.readUntilPrompt(8000, (cleaned) => {
16967
16987
  const lines = cleaned.replace(/\r/g, `
16968
16988
  `).split(`
@@ -16973,8 +16993,8 @@ class SafeModeManager {
16973
16993
  });
16974
16994
  this.channel.write(`:put "${token}"
16975
16995
  `);
16976
- const out = (await response).text;
16977
- return classifyPrompt(out);
16996
+ const { text, timedOut } = await response;
16997
+ return timedOut ? "unknown" : classifyPrompt(text);
16978
16998
  }
16979
16999
  extractOutput(raw, command) {
16980
17000
  const text = raw.replace(/\r\n/g, `
@@ -16984,18 +17004,24 @@ class SafeModeManager {
16984
17004
  `);
16985
17005
  const result = [];
16986
17006
  let pastEcho = false;
17007
+ const sent = command.trim();
17008
+ const isEcho = (line) => {
17009
+ if (line === sent)
17010
+ return true;
17011
+ if (line.endsWith(sent) && PROMPT_RE.test(line.slice(0, -sent.length).trimEnd())) {
17012
+ return true;
17013
+ }
17014
+ return line.startsWith("<") && line.length > 1 && sent.endsWith(line.slice(1));
17015
+ };
16987
17016
  for (const line of lines) {
16988
17017
  const stripped = line.trim();
16989
17018
  if (!pastEcho) {
16990
- if (stripped.includes(command.trim()))
17019
+ if (isEcho(stripped))
16991
17020
  pastEcho = true;
16992
17021
  continue;
16993
17022
  }
16994
- if (stripped.endsWith(command.trim())) {
16995
- const prefix = stripped.slice(0, -command.trim().length).trimEnd();
16996
- if (PROMPT_RE.test(prefix))
16997
- continue;
16998
- }
17023
+ if (isEcho(stripped))
17024
+ continue;
16999
17025
  if (PROMPT_RE.test(stripped))
17000
17026
  break;
17001
17027
  result.push(line);
@@ -17005,6 +17031,7 @@ class SafeModeManager {
17005
17031
  }
17006
17032
  cleanup() {
17007
17033
  this.active = false;
17034
+ this.uncertain = false;
17008
17035
  if (this.channel) {
17009
17036
  try {
17010
17037
  this.channel.end();
@@ -19953,31 +19980,27 @@ function normalizeMac(mac) {
19953
19980
  var resolvedSource = new Map;
19954
19981
  var firstLine = (s) => s.trim().split(`
19955
19982
  `)[0].trim();
19956
- async function enableAccounting(ctx) {
19957
- const out = await executeMikrotikCommand("/ip accounting set enabled=yes threshold=2000", ctx);
19958
- return looksLikeError(out) ? firstLine(out) : null;
19959
- }
19960
- async function enableKidControl(ctx) {
19961
- const count = await executeMikrotikCommand("/ip kid-control print count-only", ctx);
19962
- if (looksLikeError(count))
19963
- return firstLine(count);
19964
- if ((parseLeadingNumber(count.trim()) ?? 0) > 0)
19965
- return null;
19966
- const days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"].map((d) => `${d}=0s-1d`).join(" ");
19967
- const add = await executeMikrotikCommand(`/ip kid-control add name=mcp-monitor ${days}`, ctx);
19968
- return looksLikeError(add) ? firstLine(add) : null;
19983
+ async function checkAccounting(ctx) {
19984
+ const out = await executeMikrotikCommand("/ip accounting print", ctx);
19985
+ if (looksLikeError(out))
19986
+ return firstLine(out);
19987
+ return /\benabled\s*[:=]\s*yes\b/.test(out) ? null : "Accounting is not enabled";
19988
+ }
19989
+ async function checkKidControl(ctx) {
19990
+ const count = await executeMikrotikCommand("/ip kid-control device print count-only", ctx);
19991
+ return looksLikeError(count) ? firstLine(count) : null;
19969
19992
  }
19970
19993
  async function resolveSource(ctx) {
19971
19994
  const key = ctx.device ?? "";
19972
19995
  const cached = resolvedSource.get(key);
19973
19996
  if (cached)
19974
19997
  return { source: cached };
19975
- const accErr = await enableAccounting(ctx);
19998
+ const accErr = await checkAccounting(ctx);
19976
19999
  if (!accErr) {
19977
20000
  resolvedSource.set(key, "accounting");
19978
20001
  return { source: "accounting" };
19979
20002
  }
19980
- const kidErr = await enableKidControl(ctx);
20003
+ const kidErr = await checkKidControl(ctx);
19981
20004
  if (!kidErr) {
19982
20005
  resolvedSource.set(key, "kid-control");
19983
20006
  return { source: "kid-control" };
@@ -20135,25 +20158,29 @@ async function sampleAccounting(ctx, ts) {
20135
20158
  function parseKidDevices(rows) {
20136
20159
  const hosts = {};
20137
20160
  for (const row of rows) {
20138
- const ip = (row["ip-address"] ?? "").trim();
20139
- if (!ip)
20140
- continue;
20141
- hosts[ip] = {
20161
+ const addresses = (row["ip-address"] ?? "").split(",").map((ip) => ip.trim()).filter(Boolean);
20162
+ const traffic = {
20142
20163
  rxRate: parseMagnitude(row["rate-down"]),
20143
20164
  txRate: parseMagnitude(row["rate-up"]),
20144
- rxBytes: parseMagnitude(row["bytes-down"]),
20145
- txBytes: parseMagnitude(row["bytes-up"])
20165
+ rxBytes: parseSize(row["bytes-down"]) ?? parseMagnitude(row["bytes-down"]),
20166
+ txBytes: parseSize(row["bytes-up"]) ?? parseMagnitude(row["bytes-up"])
20146
20167
  };
20168
+ for (const ip of addresses)
20169
+ hosts[ip] = traffic;
20147
20170
  }
20148
20171
  return hosts;
20149
20172
  }
20173
+ function parseKidControlOutput(output) {
20174
+ const unwrapped = output.replace(/(ip-address=)([\da-fA-F:.]+(?:,\s*[\da-fA-F:.]+)*)/g, (_match, key, value) => `${key}${value.replace(/\s+/g, "")}`);
20175
+ return parseKidDevices(parseRecords(unwrapped).rows);
20176
+ }
20150
20177
  async function sampleKidControl(ctx) {
20151
- const out = await executeMikrotikCommand("/ip kid-control device print detail", ctx);
20178
+ const out = await executeMikrotikCommand("/ip kid-control device print detail without-paging", ctx);
20152
20179
  if (looksLikeError(out))
20153
20180
  throw new Error(firstLine(out));
20154
20181
  if (isEmpty(out))
20155
20182
  return {};
20156
- return parseKidDevices(parseRecords(out).rows);
20183
+ return parseKidControlOutput(out);
20157
20184
  }
20158
20185
  async function sampleAllTraffic(ctx) {
20159
20186
  const ts = Date.now();
@@ -20163,8 +20190,15 @@ async function sampleAllTraffic(ctx) {
20163
20190
  return { ts, source, note, hosts: {}, limits };
20164
20191
  try {
20165
20192
  const hosts = source === "accounting" ? await sampleAccounting(ctx, ts) : await sampleKidControl(ctx);
20166
- return { ts, source, hosts, limits };
20193
+ return {
20194
+ ts,
20195
+ source,
20196
+ hosts,
20197
+ limits,
20198
+ note: Object.keys(hosts).length ? undefined : "No per-device counters were returned. Monitoring may be inactive or no clients have been observed. Router configuration was not changed."
20199
+ };
20167
20200
  } catch (e) {
20201
+ resolvedSource.delete(ctx.device ?? "");
20168
20202
  return {
20169
20203
  ts,
20170
20204
  source: "none",
@@ -30947,7 +30981,7 @@ var cache2 = null;
30947
30981
  async function gateway() {
30948
30982
  if (cache2)
30949
30983
  return cache2;
30950
- const { moduleCatalog } = await import("./shared/cli-hfeatjkc.js");
30984
+ const { moduleCatalog } = await import("./shared/cli-p8wka734.js");
30951
30985
  const forIndex = [];
30952
30986
  const byName = new Map;
30953
30987
  for (const mod of moduleCatalog) {
@@ -53145,7 +53179,7 @@ var riskByTool = null;
53145
53179
  async function riskIndex() {
53146
53180
  if (riskByTool)
53147
53181
  return riskByTool;
53148
- const { moduleCatalog } = await import("./shared/cli-hfeatjkc.js");
53182
+ const { moduleCatalog } = await import("./shared/cli-p8wka734.js");
53149
53183
  const index = new Map;
53150
53184
  for (const mod of moduleCatalog) {
53151
53185
  for (const tool of mod.tools)
@@ -64499,6 +64533,8 @@ function dailyUsageFromSamples(samples) {
64499
64533
  for (let i = 1;i < samples.length; i++) {
64500
64534
  const prev = samples[i - 1];
64501
64535
  const cur = samples[i];
64536
+ if ((prev.source ?? "queue") !== (cur.source ?? "queue"))
64537
+ continue;
64502
64538
  const dRx = cur.rx >= prev.rx ? cur.rx - prev.rx : cur.rx;
64503
64539
  const dTx = cur.tx >= prev.tx ? cur.tx - prev.tx : cur.tx;
64504
64540
  const day = dayOf(cur.ts);
@@ -64515,7 +64551,8 @@ var SCHEMA_STATEMENTS8 = [
64515
64551
  subject TEXT NOT NULL,
64516
64552
  ts INTEGER NOT NULL,
64517
64553
  rx INTEGER NOT NULL,
64518
- tx INTEGER NOT NULL
64554
+ tx INTEGER NOT NULL,
64555
+ source TEXT NOT NULL DEFAULT 'queue'
64519
64556
  )`,
64520
64557
  "CREATE INDEX IF NOT EXISTS idx_usage_sub ON usage_samples(device, subject, ts)",
64521
64558
  "CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_samples(ts)",
@@ -64544,14 +64581,25 @@ class SqliteUsageStore {
64544
64581
  db.run("PRAGMA synchronous = NORMAL");
64545
64582
  for (const stmt of SCHEMA_STATEMENTS8)
64546
64583
  db.run(stmt);
64584
+ const columns = db.query("PRAGMA table_info(usage_samples)").all();
64585
+ if (!columns.some((column) => column.name === "source")) {
64586
+ db.run("ALTER TABLE usage_samples ADD COLUMN source TEXT NOT NULL DEFAULT 'queue'");
64587
+ }
64547
64588
  }
64548
64589
  recordClientSamples(device, ts, samples) {
64549
64590
  if (samples.length === 0)
64550
64591
  return;
64551
- const insert = this.db.query("INSERT INTO usage_samples (device, subject, ts, rx, tx) VALUES ($d,$s,$ts,$rx,$tx)");
64592
+ const insert = this.db.query("INSERT INTO usage_samples (device, subject, ts, rx, tx, source) VALUES ($d,$s,$ts,$rx,$tx,$source)");
64552
64593
  const tx = this.db.transaction((rows) => {
64553
64594
  for (const r of rows) {
64554
- insert.run({ $d: device, $s: r.ip, $ts: ts, $rx: r.rx, $tx: r.tx });
64595
+ insert.run({
64596
+ $d: device,
64597
+ $s: r.ip,
64598
+ $ts: ts,
64599
+ $rx: r.rx,
64600
+ $tx: r.tx,
64601
+ $source: r.source ?? "queue"
64602
+ });
64555
64603
  }
64556
64604
  });
64557
64605
  tx(samples);
@@ -64583,7 +64631,7 @@ class SqliteUsageStore {
64583
64631
  return n;
64584
64632
  }
64585
64633
  clientDailyUsage(device, ip, sinceTs) {
64586
- const rows = this.db.query("SELECT ts, rx, tx FROM usage_samples WHERE device=$d AND subject=$s AND ts>=$since ORDER BY ts ASC").all({ $d: device, $s: ip, $since: sinceTs });
64634
+ const rows = this.db.query("SELECT ts, rx, tx, source FROM usage_samples WHERE device=$d AND subject=$s AND ts>=$since ORDER BY ts ASC").all({ $d: device, $s: ip, $since: sinceTs });
64587
64635
  return dailyUsageFromSamples(rows);
64588
64636
  }
64589
64637
  umUserDailyUsage(device, user, sinceTs) {
@@ -64627,6 +64675,7 @@ async function openUsageStore(path) {
64627
64675
  }
64628
64676
 
64629
64677
  // src/observability/usage-sampler.ts
64678
+ import { isIPv4 } from "net";
64630
64679
  var SERVER_TAG2 = "mikrotik-mcp";
64631
64680
  var USAGE_RETENTION_MS = 93 * 24 * 60 * 60 * 1000;
64632
64681
  var DEFAULT_USAGE_INTERVAL_MS = 60000;
@@ -64645,22 +64694,34 @@ function bytesOf(v) {
64645
64694
  return parseSize(v) ?? parseLeadingNumber(v) ?? 0;
64646
64695
  }
64647
64696
  function ipOf(target) {
64648
- return (target ?? "").split("/")[0]?.trim() ?? "";
64697
+ const [ip, mask, extra] = target.trim().split("/");
64698
+ return isIPv4(ip ?? "") && (!mask || mask === "32") && !extra ? ip : "";
64649
64699
  }
64650
64700
  async function sampleClients(store, device, ts) {
64651
64701
  const ctx = createContext(undefined, device);
64702
+ const samples = new Map;
64703
+ const kid = await executeMikrotikCommand("/ip kid-control device print detail without-paging", ctx);
64704
+ if (!looksLikeError(kid) && !commandUnsupported(kid)) {
64705
+ for (const [ip, counter] of Object.entries(parseKidControlOutput(kid))) {
64706
+ if (isIPv4(ip))
64707
+ samples.set(ip, {
64708
+ ip,
64709
+ rx: counter.rxBytes,
64710
+ tx: counter.txBytes,
64711
+ source: "kid-control"
64712
+ });
64713
+ }
64714
+ }
64652
64715
  const out = await executeMikrotikCommand("/queue simple print stats detail", ctx);
64653
- if (isEmpty(out) || looksLikeError(out) || commandUnsupported(out))
64654
- return;
64655
- const samples = [];
64656
- for (const row of parseRecords(out).rows) {
64716
+ const queues = isEmpty(out) || looksLikeError(out) || commandUnsupported(out) ? [] : parseRecords(out).rows;
64717
+ for (const row of queues) {
64657
64718
  const ip = ipOf(row.target ?? "");
64658
- if (!ip)
64719
+ if (!ip || samples.has(ip) || !row.bytes)
64659
64720
  continue;
64660
64721
  const [tx, rx] = (row.bytes ?? "0/0").split("/");
64661
- samples.push({ ip, rx: bytesOf(rx), tx: bytesOf(tx) });
64722
+ samples.set(ip, { ip, rx: bytesOf(rx), tx: bytesOf(tx), source: "queue" });
64662
64723
  }
64663
- store.recordClientSamples(device, ts, samples);
64724
+ store.recordClientSamples(device, ts, [...samples.values()]);
64664
64725
  }
64665
64726
  var noUserManager = new Set;
64666
64727
  async function ingestSessions(store, device) {
package/dist/index.d.ts CHANGED
@@ -354,6 +354,10 @@ declare class SafeModeManager {
354
354
  * instead of a reassuring false success. Cleared on the next enable().
355
355
  */
356
356
  private droppedUnexpectedly;
357
+ /** Keep the session active (no one-shot fallback), but fence a desynchronised shell. */
358
+ private uncertain;
359
+ /** Distinguish each mode probe from delayed output of an earlier round trip. */
360
+ private probeSequence;
357
361
  /** Serializes channel access so concurrent tool calls don't interleave I/O. */
358
362
  private queue;
359
363
  /** The device this Safe Mode session belongs to (a configured device name). */
package/dist/index.js CHANGED
@@ -62,7 +62,7 @@ import {
62
62
  updateSummaryLine,
63
63
  allToolModules2,
64
64
  selectToolModules2
65
- } from "./shared/library-mx28f6gt.js";
65
+ } from "./shared/library-0ysgbdj6.js";
66
66
 
67
67
  // node_modules/ajv/dist/compile/codegen/code.js
68
68
  var require_code = __commonJS(function(exports) {
@@ -10187,6 +10187,8 @@ function stripAnsi(text) {
10187
10187
  return text.replace(ANSI_RE, "");
10188
10188
  }
10189
10189
  var CTRL_X = "\x18";
10190
+ var PRINT_PAGER_RE = /(?:^|[\r\n])-- \[Q quit\|D dump\|(?:up\||left\||right\|)*down\][ \t\r]*$/;
10191
+ var UNCERTAIN_SESSION = "Safe Mode session is uncertain after a command timeout. Further commands and commit are " + "blocked; call rollback_safe_mode, inspect device state, and re-enable Safe Mode before retrying.";
10190
10192
  var IDLE_TIMEOUT_MS = 15000;
10191
10193
  var HARD_CAP_MS = 120000;
10192
10194
  function isSafeModeActivated(response) {
@@ -10195,7 +10197,8 @@ function isSafeModeActivated(response) {
10195
10197
  return /safe mode[^\n]*\b(?:success|taken|enabled|active)\b/i.test(response);
10196
10198
  }
10197
10199
  function lastNonEmptyLine(response) {
10198
- const lines = response.replace(/\r/g, "").split(`
10200
+ const lines = response.replace(/\r/g, `
10201
+ `).split(`
10199
10202
  `).map((l) => l.trimEnd()).filter(Boolean);
10200
10203
  return lines.at(-1) ?? "";
10201
10204
  }
@@ -10211,6 +10214,8 @@ class SafeModeManager2 {
10211
10214
  channel = null;
10212
10215
  active = false;
10213
10216
  droppedUnexpectedly = false;
10217
+ uncertain = false;
10218
+ probeSequence = 0;
10214
10219
  queue = Promise.resolve();
10215
10220
  constructor(deviceName) {
10216
10221
  this.deviceName = deviceName;
@@ -10230,8 +10235,9 @@ class SafeModeManager2 {
10230
10235
  enable() {
10231
10236
  return this.lock(async () => {
10232
10237
  if (this.active)
10233
- return "Safe mode is already active.";
10238
+ return this.uncertain ? `Error: ${UNCERTAIN_SESSION}` : "Safe mode is already active.";
10234
10239
  this.droppedUnexpectedly = false;
10240
+ this.uncertain = false;
10235
10241
  const dc = getDevice2(this.deviceName);
10236
10242
  if (dc.mac) {
10237
10243
  return "Error: Safe Mode is not supported for a MAC-Telnet device " + `('${this.deviceName}' is reached by MAC ${dc.mac}). ` + "Connect over SSH (configure host/credentials) to use Safe Mode.";
@@ -10268,12 +10274,15 @@ class SafeModeManager2 {
10268
10274
  if (!this.active || !this.channel) {
10269
10275
  throw new Error("Safe mode session is not active.");
10270
10276
  }
10271
- const response = this.readUntilPrompt();
10277
+ if (this.uncertain)
10278
+ throw new Error(UNCERTAIN_SESSION);
10279
+ const response = this.readUntilPrompt(IDLE_TIMEOUT_MS, undefined, HARD_CAP_MS, true);
10272
10280
  this.channel.write(`${command}
10273
10281
  `);
10274
10282
  const { text, timedOut } = await response;
10275
10283
  if (timedOut) {
10276
- throw new Error(`Safe Mode command did not return a recognized prompt before the timeout (command: ${command}). ` + "Execution may have occurred; do not retry the write blindly. Inspect the session " + "and roll back if its state cannot be verified.");
10284
+ this.uncertain = true;
10285
+ throw new Error(`Safe Mode command did not return a recognized prompt before the timeout (command: ${command}). ` + `Execution may have occurred; do not retry the write blindly. ${UNCERTAIN_SESSION}`);
10277
10286
  }
10278
10287
  return this.extractOutput(text, command);
10279
10288
  });
@@ -10290,6 +10299,8 @@ class SafeModeManager2 {
10290
10299
  if (!this.active || !this.channel) {
10291
10300
  return { ok: true, message: "Safe mode is not active. Nothing to commit." };
10292
10301
  }
10302
+ if (this.uncertain)
10303
+ return { ok: false, message: UNCERTAIN_SESSION };
10293
10304
  const before = await this.probeMode();
10294
10305
  if (before === "released") {
10295
10306
  this.cleanup();
@@ -10339,6 +10350,8 @@ class SafeModeManager2 {
10339
10350
  if (this.droppedUnexpectedly) {
10340
10351
  return "Safe mode session DROPPED unexpectedly \u2014 RouterOS auto-reverted all staged changes; they " + "were NOT saved. Re-enable Safe Mode and re-apply, or apply changes directly (verify each with a read).";
10341
10352
  }
10353
+ if (this.uncertain && this.active)
10354
+ return UNCERTAIN_SESSION;
10342
10355
  return this.active ? "Safe mode is ACTIVE. Changes are pending \u2014 they are NOT yet persisted. " + "Call commit_safe_mode to persist or rollback_safe_mode to revert." : "Safe mode is NOT active. Changes take effect and persist immediately.";
10343
10356
  }
10344
10357
  handleUnexpectedDrop = () => {
@@ -10347,7 +10360,7 @@ class SafeModeManager2 {
10347
10360
  this.droppedUnexpectedly = true;
10348
10361
  this.cleanup();
10349
10362
  };
10350
- readUntilPrompt(idleMs = IDLE_TIMEOUT_MS, isDone = (c) => PROMPT_RE.test(c), hardCapMs = HARD_CAP_MS) {
10363
+ readUntilPrompt(idleMs = IDLE_TIMEOUT_MS, isDone = (c) => PROMPT_RE.test(c), hardCapMs = HARD_CAP_MS, drainPrintPager = false) {
10351
10364
  const channel = this.channel;
10352
10365
  if (!channel)
10353
10366
  return Promise.resolve({ text: "", timedOut: false });
@@ -10363,8 +10376,15 @@ class SafeModeManager2 {
10363
10376
  buf += decodeOutput(chunk);
10364
10377
  armIdle();
10365
10378
  const cleaned = stripAnsi(buf);
10366
- if (isDone(cleaned))
10379
+ if (isDone(cleaned)) {
10367
10380
  finish(cleaned, false);
10381
+ return;
10382
+ }
10383
+ const pager = drainPrintPager ? PRINT_PAGER_RE.exec(cleaned) : null;
10384
+ if (pager) {
10385
+ buf = cleaned.slice(0, pager.index);
10386
+ channel.write(" ");
10387
+ }
10368
10388
  }
10369
10389
  function finish(result, timedOut) {
10370
10390
  clearTimeout(idleTimer);
@@ -10379,7 +10399,7 @@ class SafeModeManager2 {
10379
10399
  async probeMode() {
10380
10400
  if (!this.channel)
10381
10401
  return "unknown";
10382
- const token = "__MCP_SAFEMODE_PROBE__";
10402
+ const token = `__MCP_SAFEMODE_PROBE_${++this.probeSequence}__`;
10383
10403
  const response = this.readUntilPrompt(8000, (cleaned) => {
10384
10404
  const lines = cleaned.replace(/\r/g, `
10385
10405
  `).split(`
@@ -10390,8 +10410,8 @@ class SafeModeManager2 {
10390
10410
  });
10391
10411
  this.channel.write(`:put "${token}"
10392
10412
  `);
10393
- const out = (await response).text;
10394
- return classifyPrompt(out);
10413
+ const { text, timedOut } = await response;
10414
+ return timedOut ? "unknown" : classifyPrompt(text);
10395
10415
  }
10396
10416
  extractOutput(raw, command) {
10397
10417
  const text = raw.replace(/\r\n/g, `
@@ -10401,18 +10421,24 @@ class SafeModeManager2 {
10401
10421
  `);
10402
10422
  const result = [];
10403
10423
  let pastEcho = false;
10424
+ const sent = command.trim();
10425
+ const isEcho = (line) => {
10426
+ if (line === sent)
10427
+ return true;
10428
+ if (line.endsWith(sent) && PROMPT_RE.test(line.slice(0, -sent.length).trimEnd())) {
10429
+ return true;
10430
+ }
10431
+ return line.startsWith("<") && line.length > 1 && sent.endsWith(line.slice(1));
10432
+ };
10404
10433
  for (const line of lines) {
10405
10434
  const stripped = line.trim();
10406
10435
  if (!pastEcho) {
10407
- if (stripped.includes(command.trim()))
10436
+ if (isEcho(stripped))
10408
10437
  pastEcho = true;
10409
10438
  continue;
10410
10439
  }
10411
- if (stripped.endsWith(command.trim())) {
10412
- const prefix = stripped.slice(0, -command.trim().length).trimEnd();
10413
- if (PROMPT_RE.test(prefix))
10414
- continue;
10415
- }
10440
+ if (isEcho(stripped))
10441
+ continue;
10416
10442
  if (PROMPT_RE.test(stripped))
10417
10443
  break;
10418
10444
  result.push(line);
@@ -10422,6 +10448,7 @@ class SafeModeManager2 {
10422
10448
  }
10423
10449
  cleanup() {
10424
10450
  this.active = false;
10451
+ this.uncertain = false;
10425
10452
  if (this.channel) {
10426
10453
  try {
10427
10454
  this.channel.end();
@@ -23748,7 +23775,7 @@ var cache2 = null;
23748
23775
  async function gateway() {
23749
23776
  if (cache2)
23750
23777
  return cache2;
23751
- const { moduleCatalog } = await import("./library-56rhcw1r.js");
23778
+ const { moduleCatalog } = await import("./library-pdyv4a32.js");
23752
23779
  const forIndex = [];
23753
23780
  const byName = new Map;
23754
23781
  for (const mod of moduleCatalog) {
@@ -45698,7 +45725,7 @@ var riskByTool = null;
45698
45725
  async function riskIndex() {
45699
45726
  if (riskByTool)
45700
45727
  return riskByTool;
45701
- const { moduleCatalog } = await import("./library-56rhcw1r.js");
45728
+ const { moduleCatalog } = await import("./library-pdyv4a32.js");
45702
45729
  const index = new Map;
45703
45730
  for (const mod of moduleCatalog) {
45704
45731
  for (const tool of mod.tools)
@@ -3,7 +3,7 @@ import {
3
3
  moduleCatalog2,
4
4
  allToolModules2,
5
5
  selectToolModules2
6
- } from "./library-mx28f6gt.js";
6
+ } from "./library-0ysgbdj6.js";
7
7
  export {
8
8
  allToolModules2 as allToolModules,
9
9
  moduleCatalog2 as moduleCatalog,