@usex/mikrotik-mcp 5.12.0 → 5.14.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.
@@ -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();
@@ -11121,6 +11148,14 @@ var REPORT_VIEW_TOOLS = {
11121
11148
  "packet_capture_status"
11122
11149
  ],
11123
11150
  reports: [
11151
+ "diagnose_home_internet",
11152
+ "compare_home_paths",
11153
+ "get_home_internet",
11154
+ "refresh_home_devices",
11155
+ "name_home_device",
11156
+ "preview_home_policy",
11157
+ "apply_home_policy",
11158
+ "undo_home_policy",
11124
11159
  "diagnose",
11125
11160
  "trace_path",
11126
11161
  "correlate_events",
@@ -15298,12 +15333,892 @@ var investigationTools = [
15298
15333
  })
15299
15334
  ];
15300
15335
 
15301
- // src/tools/service-contracts.ts
15302
- import { randomUUID as randomUUID3 } from "crypto";
15336
+ // src/home/model.ts
15337
+ var macInput = string().regex(/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i);
15338
+ var diagnosisInput = object({
15339
+ client: ipv42(),
15340
+ target: string().max(253).regex(/^[a-z\d](?:[a-z\d.-]*[a-z\d])?$/i).default("example.com")
15341
+ });
15342
+ var compareInput = object({
15343
+ target: ipv42(),
15344
+ tables: array(string().min(1).max(64)).min(1).max(3),
15345
+ goal: _enum(["calls", "gaming", "download"]).default("calls")
15346
+ });
15347
+ var policyInput = object({
15348
+ mac: macInput,
15349
+ action: _enum(["pause", "priority", "route"]),
15350
+ minutes: number().int().min(5).max(120).default(30),
15351
+ startInMinutes: number().int().min(0).max(1440).default(0),
15352
+ table: string().min(1).max(64).optional()
15353
+ });
15354
+ function enabled2(row) {
15355
+ return !isYes(row.disabled) && !/[XI]/.test(row.flags ?? "");
15356
+ }
15357
+ function activeRoute(row) {
15358
+ return enabled2(row) && (isYes(row.active) || /A/.test(row.flags ?? ""));
15359
+ }
15360
+ function milliseconds(text) {
15361
+ if (!text)
15362
+ return null;
15363
+ const units = [...text.matchAll(/(\d+(?:\.\d+)?)(us|ms|s)/g)];
15364
+ if (!units.length || units.map((m) => m[0]).join("") !== text)
15365
+ return null;
15366
+ return units.reduce((sum, m) => sum + Number(m[1]) * (m[2] === "s" ? 1000 : m[2] === "us" ? 0.001 : 1), 0);
15367
+ }
15368
+ function pingSample(table, raw) {
15369
+ const sent = Number(raw.match(/sent=(\d+)/)?.[1]);
15370
+ const received = Number(raw.match(/received=(\d+)/)?.[1]);
15371
+ const rtt = (key) => milliseconds(raw.match(new RegExp(`${key}-rtt=([^\\s]+)`))?.[1]);
15372
+ const min = rtt("min"), max = rtt("max");
15373
+ if (!Number.isFinite(sent) || sent < 1 || !Number.isFinite(received) || received > sent)
15374
+ return {
15375
+ table,
15376
+ state: "unknown",
15377
+ loss: null,
15378
+ latency: null,
15379
+ spread: null,
15380
+ note: "No usable ICMP summary. This RouterOS version may not support table-scoped ping."
15381
+ };
15382
+ return {
15383
+ table,
15384
+ state: "observed",
15385
+ loss: (sent - received) * 100 / sent,
15386
+ latency: rtt("avg"),
15387
+ spread: min === null || max === null ? null : Math.max(0, max - min),
15388
+ note: "Five router-originated ICMP probes; RTT range is not a client jitter or throughput measurement."
15389
+ };
15390
+ }
15391
+ function recommendPath(paths, goal) {
15392
+ if (goal === "download")
15393
+ return null;
15394
+ const usable = paths.filter((p) => p.state === "observed" && p.loss !== null && p.loss < 100 && p.latency !== null && p.spread !== null);
15395
+ const score = (p) => p.loss * 1000 + p.latency + p.spread * (goal === "calls" ? 2 : 1);
15396
+ return usable.sort((a, b) => score(a) - score(b))[0]?.table ?? null;
15397
+ }
15398
+ function tagSelector(tag) {
15399
+ return `[find where comment=${quoteValue(tag)}]`;
15400
+ }
15401
+ function temporaryCommands(id, input, ip, setup, activate, revert) {
15402
+ const tag = `mcp-home-${id}`;
15403
+ const clearMarkers = new Cmd(`/ip firewall address-list remove ${tagSelector(tag)}`).build();
15404
+ const clearScheduler = new Cmd(`/system scheduler remove ${tagSelector(tag)}`).build();
15405
+ const undo = [...revert, clearMarkers, clearScheduler];
15406
+ const leaseMatch = `[/ip dhcp-server lease find where mac-address=${quoteValue(input.mac)} address=${quoteValue(ip)} dynamic=no status=bound]`;
15407
+ const expired = `([:len [/ip firewall address-list find where list=${quoteValue(`${tag}-end`)}]] = 0 || [:len ${leaseMatch}] != 1)`;
15408
+ const waiting = `[:len [/ip firewall address-list find where list=${quoteValue(`${tag}-start`)}]] = 0`;
15409
+ const tick = `:if (${expired}) do={ ${undo.join("; ")} } else={ :if (${waiting}) do={ ${activate.join("; ")} } }`;
15410
+ const commands = [
15411
+ ...setup,
15412
+ new Cmd("/ip firewall address-list add").set("list", `${tag}-end`).set("address", ip).set("timeout", `${input.minutes + input.startInMinutes}m`).set("comment", tag).build(),
15413
+ ...input.startInMinutes ? [
15414
+ new Cmd("/ip firewall address-list add").set("list", `${tag}-start`).set("address", ip).set("timeout", `${input.startInMinutes}m`).set("comment", tag).build()
15415
+ ] : [],
15416
+ new Cmd("/system scheduler add").set("name", tag).set("comment", tag).set("interval", "30s").set("start-time", "startup").set("policy", "read,write").set("on-event", tick).build(),
15417
+ new Cmd("/system scheduler add").set("name", `${tag}-boot`).set("comment", tag).set("interval", "0s").set("start-time", "startup").set("policy", "read,write").set("on-event", tick).build(),
15418
+ ...!input.startInMinutes ? activate : []
15419
+ ];
15420
+ return { commands, undo };
15421
+ }
15422
+
15423
+ // src/home/read.ts
15424
+ async function checkedRead(command, ctx, read = executeMikrotikCommand2) {
15425
+ const raw = await read(command, ctx, { maxMs: 8000 });
15426
+ if (looksLikeError(raw) || raw.length > 512000)
15427
+ throw new Error("Router rejected the command or returned too much data; its outcome was not confirmed.");
15428
+ return raw;
15429
+ }
15430
+ async function rows(path, fields, ctx, read = executeMikrotikCommand2) {
15431
+ const raw = await checkedRead(new Cmd(`${path} print detail without-paging`).build(), ctx, read);
15432
+ const result = parseRecords(raw).rows;
15433
+ if (!result.length && !isEmpty(raw) && !/^\s*(?:Flags:.*)?\s*$/.test(raw) || result.length > 1000)
15434
+ throw new Error(`Cannot safely interpret ${path}.`);
15435
+ const keys = new Set(["#", "flags", ...fields.split(",")]);
15436
+ return result.map((row) => Object.fromEntries(Object.entries(row).filter(([key]) => keys.has(key))));
15437
+ }
15438
+ async function diagnoseInternet(input, ctx, read = executeMikrotikCommand2) {
15439
+ const a = diagnosisInput.parse(input), device = resolveDeviceName2(ctx.device);
15440
+ assertDeviceAccess([device], "diagnose_home_internet", "READ");
15441
+ const findings = [];
15442
+ const capture = async (area, work) => {
15443
+ try {
15444
+ findings.push(await work());
15445
+ } catch {
15446
+ findings.push({
15447
+ area,
15448
+ state: "unknown",
15449
+ title: `${area} could not be measured`,
15450
+ detail: "The router query failed or is unsupported. Missing evidence is not a healthy result.",
15451
+ next: "Check permissions and device support, then retry."
15452
+ });
15453
+ }
15454
+ };
15455
+ await capture("Router", async () => {
15456
+ const resource = parseKeyValues(await checkedRead("/system resource print", ctx, read));
15457
+ const cpu = Number(resource["cpu-load"]?.replace("%", ""));
15458
+ const free = parseSize(resource["free-memory"]), total = parseSize(resource["total-memory"]);
15459
+ if (!Number.isFinite(cpu) || !total || free === undefined)
15460
+ throw new Error("No resources");
15461
+ const memory = Math.round((1 - free / total) * 100), hot = cpu >= 85 || memory >= 90;
15462
+ return {
15463
+ area: "Router",
15464
+ state: hot ? "suspected" : "observed",
15465
+ title: hot ? "The router may be under pressure" : "Router resources have headroom in this sample",
15466
+ detail: `CPU ${cpu}% \xB7 memory ${memory}%. One sample does not establish a bottleneck.`,
15467
+ next: "Repeat while the slow download is running; compare with the Devices page."
15468
+ };
15469
+ });
15470
+ await capture("DNS", async () => {
15471
+ const start = Date.now();
15472
+ const resolved = (await checkedRead(`:put [:resolve ${new Cmd("").set("domain-name", a.target).build().trim()}]`, ctx, read)).trim();
15473
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(resolved))
15474
+ throw new Error("Not an IPv4 result");
15475
+ return {
15476
+ area: "DNS",
15477
+ state: "observed",
15478
+ title: "The router resolved this destination",
15479
+ detail: `${a.target} \u2192 ${resolved}. Query plus SSH round trip: ${Date.now() - start} ms (not pure DNS latency).`,
15480
+ next: "If only one device is affected, compare its DNS and secure-DNS settings."
15481
+ };
15482
+ });
15483
+ await capture("Internet", async () => {
15484
+ const result = pingSample("main", await checkedRead(new Cmd("/ping").set("address", a.target).set("count", 5).set("interval", "200ms").build(), ctx, read));
15485
+ if (result.state === "unknown")
15486
+ throw new Error("No ping");
15487
+ return {
15488
+ area: "Internet",
15489
+ state: result.loss > 0 ? "suspected" : "observed",
15490
+ title: result.loss > 0 ? "Some router probes did not return" : "All router probes returned",
15491
+ detail: `${result.loss}% loss \xB7 average RTT ${result.latency ?? "unknown"} ms. ICMP can be deprioritized; this does not locate a failing hop.`,
15492
+ next: "Compare paths below. Router probes do not test the client's firewall path or application."
15493
+ };
15494
+ });
15495
+ await capture("Wi-Fi", async () => {
15496
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,active-address", ctx, read);
15497
+ const mac = leases.find((r) => r.address === a.client || r["active-address"] === a.client)?.["mac-address"];
15498
+ if (!mac)
15499
+ throw new Error("No attachment");
15500
+ let registrations;
15501
+ try {
15502
+ registrations = await rows("/interface wifi registration-table", "mac-address,signal,tx-rate,rx-rate", ctx, read);
15503
+ } catch {
15504
+ registrations = await rows("/interface wireless registration-table", "mac-address,signal-strength,tx-rate,rx-rate", ctx, read);
15505
+ }
15506
+ const entry = registrations.find((r) => r["mac-address"]?.toUpperCase() === mac.toUpperCase());
15507
+ const signal = Number.parseFloat(entry?.signal ?? entry?.["signal-strength"] ?? "");
15508
+ if (!entry || !Number.isFinite(signal))
15509
+ throw new Error("No Wi-Fi measurement");
15510
+ return {
15511
+ area: "Wi-Fi",
15512
+ state: signal < -70 ? "suspected" : "observed",
15513
+ title: signal < -70 ? "Weak Wi-Fi signal may be slowing this device" : "Wi-Fi signal is not weak in this sample",
15514
+ detail: `${signal} dBm \xB7 PHY transmit rate ${entry["tx-rate"] ?? "unknown"}. PHY rate is not download speed.`,
15515
+ next: "Move closer to the access point and compare; interference and airtime remain unmeasured."
15516
+ };
15517
+ });
15518
+ await capture("Bandwidth", async () => {
15519
+ const queues = await rows("/queue simple", "name,target,max-limit,disabled", ctx, read);
15520
+ const matches = queues.filter((q) => enabled2(q) && q.target?.split(",").some((t) => t === a.client || t === `${a.client}/32`));
15521
+ return {
15522
+ area: "Bandwidth",
15523
+ state: matches.length ? "observed" : "unknown",
15524
+ title: matches.length ? "A per-device bandwidth policy exists" : "Available bandwidth has not been measured",
15525
+ detail: matches.length ? matches.map((q) => `${q.name}: upload/download ceiling ${q["max-limit"] ?? "unknown"}`).join("; ") : "No exact per-device simple queue was found. Shared queues, link utilization, MTU and VPN throughput can still matter.",
15526
+ next: "Run an endpoint speed test before and during the problem. These checks do not download test files or change MTU."
15527
+ };
15528
+ });
15529
+ return {
15530
+ device,
15531
+ client: a.client,
15532
+ target: a.target,
15533
+ at: Date.now(),
15534
+ applicationHealth: "unverified",
15535
+ findings
15536
+ };
15537
+ }
15538
+ async function comparePaths(input, ctx, read = executeMikrotikCommand2) {
15539
+ const a = compareInput.parse(input), device = resolveDeviceName2(ctx.device);
15540
+ assertDeviceAccess([device], "compare_home_paths", "READ");
15541
+ const tables = await rows("/routing table", "name,fib,disabled", ctx, read);
15542
+ const names = [...new Set(a.tables)];
15543
+ if (names.some((name) => !tables.some((t) => t.name === name && enabled2(t) && (t.fib === "yes" || t.fib === "true"))))
15544
+ throw new Error("Choose an existing enabled FIB routing table.");
15545
+ const paths = [];
15546
+ for (const table of names) {
15547
+ try {
15548
+ paths.push(pingSample(table, await checkedRead(new Cmd("/ping").set("address", a.target).set("routing-table", table).set("count", 5).set("interval", "200ms").build(), ctx, read)));
15549
+ } catch {
15550
+ paths.push(pingSample(table, ""));
15551
+ }
15552
+ }
15553
+ return {
15554
+ device,
15555
+ at: Date.now(),
15556
+ target: a.target,
15557
+ goal: a.goal,
15558
+ paths,
15559
+ recommended: recommendPath(paths, a.goal),
15560
+ explanation: a.goal === "download" ? "Download speed is not inferred from ping. Choose only after an endpoint throughput test." : "Lowest loss, then latency and RTT range in this small router sample. Not a guarantee of client performance; output mangle can affect router probes."
15561
+ };
15562
+ }
15303
15563
 
15304
- // src/service-contracts/store.ts
15564
+ // src/home/policies.ts
15565
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
15566
+
15567
+ // src/snapshots/format.ts
15568
+ import { createHash } from "crypto";
15569
+ var TIMESTAMP_HEADER = /^#\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b.*by RouterOS/i;
15570
+ function parseExportMeta(body) {
15571
+ const head = body.slice(0, 600);
15572
+ const version = head.match(/by RouterOS ([^\s#]+)/i)?.[1];
15573
+ const exportedAt = head.match(/#\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1];
15574
+ return { rosVersion: version, exportedAt };
15575
+ }
15576
+ function normalizeExport(body) {
15577
+ return body.replace(/\r\n/g, `
15578
+ `).split(`
15579
+ `).filter((line) => !TIMESTAMP_HEADER.test(line)).join(`
15580
+ `).replace(/\n+$/, "");
15581
+ }
15582
+ function contentSha(normalizedBody) {
15583
+ return createHash("sha256").update(normalizedBody, "utf8").digest("hex").slice(0, 16);
15584
+ }
15585
+ function countLines(body) {
15586
+ const trimmed = body.replace(/\n+$/, "");
15587
+ return trimmed === "" ? 0 : trimmed.split(`
15588
+ `).length;
15589
+ }
15590
+
15591
+ // src/snapshots/store.ts
15305
15592
  import { mkdirSync as mkdirSync4 } from "fs";
15306
15593
  import { dirname as dirname4 } from "path";
15594
+ function rowToBaseline(r) {
15595
+ return {
15596
+ device: r.device,
15597
+ snapshotId: r.snapshot_id,
15598
+ setAt: r.set_at,
15599
+ setBy: r.set_by,
15600
+ label: r.label ?? undefined,
15601
+ notes: r.notes ?? undefined
15602
+ };
15603
+ }
15604
+ function rowToSnapshot(r, body) {
15605
+ return {
15606
+ id: r.id,
15607
+ device: r.device,
15608
+ ts: r.ts,
15609
+ label: r.label ?? undefined,
15610
+ rosVersion: r.ros_version ?? undefined,
15611
+ body,
15612
+ bytes: r.bytes,
15613
+ lines: r.lines,
15614
+ sha: r.sha
15615
+ };
15616
+ }
15617
+ var SCHEMA_STATEMENTS3 = [
15618
+ `CREATE TABLE IF NOT EXISTS snapshots (
15619
+ id TEXT PRIMARY KEY,
15620
+ device TEXT NOT NULL,
15621
+ ts INTEGER NOT NULL,
15622
+ label TEXT,
15623
+ ros_version TEXT,
15624
+ body TEXT NOT NULL,
15625
+ bytes INTEGER NOT NULL,
15626
+ lines INTEGER NOT NULL,
15627
+ sha TEXT NOT NULL
15628
+ )`,
15629
+ "CREATE INDEX IF NOT EXISTS idx_snapshots_device_ts ON snapshots(device, ts)",
15630
+ `CREATE TABLE IF NOT EXISTS baselines (
15631
+ device TEXT PRIMARY KEY,
15632
+ snapshot_id TEXT NOT NULL,
15633
+ set_at INTEGER NOT NULL,
15634
+ set_by TEXT NOT NULL DEFAULT 'agent',
15635
+ label TEXT,
15636
+ notes TEXT
15637
+ )`
15638
+ ];
15639
+
15640
+ class SqliteSnapshotStore {
15641
+ db;
15642
+ constructor(db) {
15643
+ this.db = db;
15644
+ db.run("PRAGMA journal_mode = WAL");
15645
+ db.run("PRAGMA synchronous = NORMAL");
15646
+ for (const stmt of SCHEMA_STATEMENTS3)
15647
+ db.run(stmt);
15648
+ }
15649
+ insert(s) {
15650
+ this.db.query(`INSERT OR REPLACE INTO snapshots
15651
+ (id, device, ts, label, ros_version, body, bytes, lines, sha)
15652
+ VALUES ($id,$device,$ts,$label,$ver,$body,$bytes,$lines,$sha)`).run({
15653
+ $id: s.id,
15654
+ $device: s.device,
15655
+ $ts: s.ts,
15656
+ $label: s.label ?? null,
15657
+ $ver: s.rosVersion ?? null,
15658
+ $body: s.body,
15659
+ $bytes: s.bytes,
15660
+ $lines: s.lines,
15661
+ $sha: s.sha
15662
+ });
15663
+ }
15664
+ get(id) {
15665
+ const row = this.db.query("SELECT * FROM snapshots WHERE id = $id").get({ $id: id });
15666
+ return row ? rowToSnapshot(row, row.body) : null;
15667
+ }
15668
+ latest(device) {
15669
+ const row = this.db.query("SELECT * FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT 1").get({ $d: device });
15670
+ return row ? rowToSnapshot(row, row.body) : null;
15671
+ }
15672
+ list(device, limit = 50, withBody = false) {
15673
+ const cols = withBody ? "*" : "id, device, ts, label, ros_version, bytes, lines, sha";
15674
+ const n = Math.min(Math.max(limit, 1), 500);
15675
+ const rows = this.db.query(`SELECT ${cols} FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT $n`).all({ $d: device, $n: n });
15676
+ return rows.map((r) => rowToSnapshot(r, withBody ? r.body : ""));
15677
+ }
15678
+ count(device) {
15679
+ const r = this.db.query("SELECT COUNT(*) AS n FROM snapshots WHERE device = $d").get({ $d: device });
15680
+ return r.n;
15681
+ }
15682
+ delete(ids) {
15683
+ if (ids.length === 0)
15684
+ return 0;
15685
+ const placeholders = ids.map((_, j) => `$id${j}`).join(",");
15686
+ const params = {};
15687
+ ids.forEach((id, j) => {
15688
+ params[`$id${j}`] = id;
15689
+ });
15690
+ const res = this.db.query(`DELETE FROM snapshots WHERE id IN (${placeholders})`).run(params);
15691
+ return Number(res.changes ?? 0);
15692
+ }
15693
+ setBaseline(device, snapshotId, setBy = "agent", label, notes) {
15694
+ this.db.query(`INSERT OR REPLACE INTO baselines (device, snapshot_id, set_at, set_by, label, notes)
15695
+ VALUES ($device, $snapId, $setAt, $setBy, $label, $notes)`).run({
15696
+ $device: device,
15697
+ $snapId: snapshotId,
15698
+ $setAt: Date.now(),
15699
+ $setBy: setBy,
15700
+ $label: label ?? null,
15701
+ $notes: notes ?? null
15702
+ });
15703
+ }
15704
+ getBaseline(device) {
15705
+ const row = this.db.query("SELECT * FROM baselines WHERE device = $d").get({ $d: device });
15706
+ return row ? rowToBaseline(row) : null;
15707
+ }
15708
+ removeBaseline(device) {
15709
+ const res = this.db.query("DELETE FROM baselines WHERE device = $d").run({ $d: device });
15710
+ return (res.changes ?? 0) > 0;
15711
+ }
15712
+ listBaselines() {
15713
+ const rows = this.db.query("SELECT * FROM baselines ORDER BY set_at DESC").all();
15714
+ return rows.map(rowToBaseline);
15715
+ }
15716
+ close() {
15717
+ this.db.close();
15718
+ }
15719
+ }
15720
+ async function openSnapshotStore(path) {
15721
+ if (path !== ":memory:") {
15722
+ try {
15723
+ mkdirSync4(dirname4(path), { recursive: true });
15724
+ } catch {}
15725
+ }
15726
+ const { Database } = await import("bun:sqlite");
15727
+ const db = new Database(path, { create: true });
15728
+ return new SqliteSnapshotStore(db);
15729
+ }
15730
+
15731
+ // src/snapshots/capture.ts
15732
+ var storePromise3 = null;
15733
+ function snapshots() {
15734
+ if (!storePromise3)
15735
+ storePromise3 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
15736
+ return storePromise3;
15737
+ }
15738
+ async function captureSnapshot(ctx, label, requireExport = false) {
15739
+ const device = resolveDeviceName2(ctx.device);
15740
+ const body = await executeMikrotikCommand2("/export terse", ctx);
15741
+ if (requireExport && (looksLikeError(body) || !/^\/[a-z]/m.test(body) || /#\s*error exporting/i.test(body)))
15742
+ throw new Error("A complete pre-change configuration export could not be captured; no policy was applied.");
15743
+ const meta = parseExportMeta(body);
15744
+ const sha = contentSha(normalizeExport(body));
15745
+ const ts = Date.now();
15746
+ const snap = {
15747
+ id: `snap_${ts}_${sha.slice(0, 8)}`,
15748
+ device,
15749
+ ts,
15750
+ label,
15751
+ rosVersion: meta.rosVersion,
15752
+ body,
15753
+ bytes: Buffer.byteLength(body, "utf8"),
15754
+ lines: countLines(body),
15755
+ sha
15756
+ };
15757
+ (await snapshots()).insert(snap);
15758
+ return snap.id;
15759
+ }
15760
+
15761
+ // src/home/store.ts
15762
+ import { mkdirSync as mkdirSync5 } from "fs";
15763
+ import { dirname as dirname5 } from "path";
15764
+ class HomeStore {
15765
+ db;
15766
+ constructor(db) {
15767
+ this.db = db;
15768
+ db.run("CREATE TABLE IF NOT EXISTS home_clients (device TEXT NOT NULL, mac TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY(device,mac))");
15769
+ db.run("CREATE TABLE IF NOT EXISTS home_plans (id TEXT PRIMARY KEY, device TEXT NOT NULL, created INTEGER NOT NULL, body TEXT NOT NULL)");
15770
+ db.run("CREATE UNIQUE INDEX IF NOT EXISTS home_one_active_client ON home_plans(device, json_extract(body,'$.input.mac')) WHERE json_extract(body,'$.status') IN ('applying','scheduled','active','uncertain')");
15771
+ }
15772
+ clients(device) {
15773
+ return this.db.query("SELECT body FROM home_clients WHERE device=?").all(device).map((r) => JSON.parse(r.body));
15774
+ }
15775
+ saveClient(device, client) {
15776
+ this.db.query("INSERT INTO home_clients VALUES (?,?,?) ON CONFLICT(device,mac) DO UPDATE SET body=excluded.body").run(device, client.mac, JSON.stringify(client));
15777
+ }
15778
+ savePlan(plan) {
15779
+ this.db.query("INSERT INTO home_plans VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET body=excluded.body").run(plan.id, plan.device, plan.createdAt, JSON.stringify(plan));
15780
+ }
15781
+ plan(id, device) {
15782
+ const row = this.db.query("SELECT body FROM home_plans WHERE id=? AND device=?").get(id, device);
15783
+ return row ? JSON.parse(row.body) : undefined;
15784
+ }
15785
+ claim(plan) {
15786
+ const result = this.db.query("UPDATE home_plans SET body=? WHERE id=? AND device=? AND json_extract(body,'$.status')='preview' AND json_extract(body,'$.previewExpiresAt')>=?").run(JSON.stringify(plan), plan.id, plan.device, Date.now());
15787
+ if (result.changes !== 1)
15788
+ throw new Error("Preview expired or was already claimed by another process.");
15789
+ }
15790
+ unresolved(device) {
15791
+ return this.db.query("SELECT body FROM home_plans WHERE device=? AND json_extract(body,'$.status') IN ('applying','scheduled','active','uncertain')").all(device).map((r) => JSON.parse(r.body));
15792
+ }
15793
+ plans(device) {
15794
+ const recent = this.db.query("SELECT body FROM home_plans WHERE device=? ORDER BY created DESC LIMIT 200").all(device).map((r) => JSON.parse(r.body));
15795
+ return [
15796
+ ...new Map([...recent, ...this.unresolved(device)].map((p) => [p.id, p])).values()
15797
+ ].sort((a, b) => b.createdAt - a.createdAt);
15798
+ }
15799
+ }
15800
+ var pending2;
15801
+ function homeStore() {
15802
+ return pending2 ??= (async () => {
15803
+ mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
15804
+ const { Database } = await import("bun:sqlite");
15805
+ const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
15806
+ db.run("PRAGMA journal_mode=WAL");
15807
+ db.run("PRAGMA busy_timeout=5000");
15808
+ return new HomeStore(db);
15809
+ })().catch((e) => {
15810
+ pending2 = undefined;
15811
+ throw e;
15812
+ });
15813
+ }
15814
+
15815
+ // src/home/policies.ts
15816
+ function buildPolicy(id, input, facts) {
15817
+ input = { ...input, mac: input.mac.toUpperCase() };
15818
+ if (!isYes(facts.deviceMode.scheduler))
15819
+ throw new Error("Router device-mode must explicitly allow scheduler execution for automatic expiry.");
15820
+ const candidates = facts.leases.filter((l) => l["mac-address"]?.toUpperCase() === input.mac);
15821
+ const lease = candidates[0];
15822
+ if (candidates.length !== 1 || !lease || isYes(lease.dynamic) || /D/.test(lease.flags ?? "") || !enabled2(lease) || lease.status !== "bound" || !lease.address)
15823
+ throw new Error("This control requires exactly one bound, static DHCP lease. Pin the client's IP in Clients first.");
15824
+ if (facts.leases.some((l) => l !== lease && (l.address === lease.address || l["active-address"] === lease.address)))
15825
+ throw new Error("The client IP is ambiguous.");
15826
+ if (lease["active-address"] && lease["active-address"] !== lease.address)
15827
+ throw new Error("The client lease changed; reconnect it before continuing.");
15828
+ if (lease["active-mac-address"] && lease["active-mac-address"].toUpperCase() !== input.mac)
15829
+ throw new Error("The active client MAC does not match its reservation.");
15830
+ if (facts.addresses.some((r) => r.address?.split("/")[0] === lease.address))
15831
+ throw new Error("Cannot target a router address.");
15832
+ if (facts.filters.some((r) => enabled2(r) && r.action === "fasttrack-connection") || facts.connections.some((r) => isYes(r.fasttrack) || /F/.test(r.flags ?? "")))
15833
+ throw new Error("FastTrack is configured or still active. These controls cannot guarantee enforcement. Ask the administrator to design a per-client FastTrack exclusion first.");
15834
+ if (input.action === "pause" && !isYes(facts.ipv6["disable-ipv6"]) && facts.ipv6.forward !== "no" && facts.ipv6.forward !== "false")
15835
+ throw new Error("IPv6 forwarding is enabled or unknown. An IPv4-only pause could be bypassed; use a dual-stack policy instead.");
15836
+ const tag = `mcp-home-${id}`, ip = lease.address;
15837
+ const setup = [], activate = [], revert = [];
15838
+ let queueBefore;
15839
+ const warnings = [
15840
+ "Only this reserved IPv4 client is targeted. Other configuration is left in place.",
15841
+ "The router expires this policy even when the dashboard is closed. Scheduler cleanup can take up to 30 seconds. Reboot ends the policy.",
15842
+ "Existing connections may disconnect. Review before applying; this is not a speed guarantee."
15843
+ ];
15844
+ const manage = (path) => {
15845
+ activate.push(new Cmd(`${path} enable ${tagSelector(tag)}`).build());
15846
+ revert.push(new Cmd(`${path} remove ${tagSelector(tag)}`).build());
15847
+ };
15848
+ if (input.action === "pause") {
15849
+ for (const direction of ["src", "dst"])
15850
+ setup.push(new Cmd("/ip firewall filter add").set("chain", "forward").set(`${direction}-address-list`, `${tag}-end`).set("action", "drop").set("comment", tag).bool("disabled", true).raw(facts.filters.length ? "place-before=0" : "").build());
15851
+ manage("/ip firewall filter");
15852
+ warnings.push("Pauses all routed traffic for this IP, including routed LAN traffic; router management and same-bridge traffic are not blocked.");
15853
+ } else if (input.action === "route") {
15854
+ if (!input.table || !facts.tables.some((t) => t.name === input.table && isYes(t.fib) && enabled2(t)) || !facts.routes.some((r) => r["routing-table"] === input.table && r["dst-address"] === "0.0.0.0/0" && activeRoute(r)))
15855
+ throw new Error("Select an enabled FIB table with an active default route. This feature does not create WANs or VPNs.");
15856
+ if (facts.mangle.some((r) => enabled2(r) && r.action === "mark-routing"))
15857
+ throw new Error("Existing routing marks require an administrator review; this control will not override them.");
15858
+ const exclusions = new Set([
15859
+ "10.0.0.0/8",
15860
+ "172.16.0.0/12",
15861
+ "192.168.0.0/16",
15862
+ "100.64.0.0/10",
15863
+ "127.0.0.0/8",
15864
+ "169.254.0.0/16",
15865
+ "224.0.0.0/4",
15866
+ "255.255.255.255"
15867
+ ]);
15868
+ for (const a of facts.addresses)
15869
+ if (a.address)
15870
+ exclusions.add(a.address);
15871
+ for (const prefix of exclusions)
15872
+ setup.push(new Cmd("/ip firewall address-list add").set("list", `${tag}-local`).set("address", prefix).set("comment", tag).build());
15873
+ setup.push(new Cmd("/ip firewall mangle add").set("chain", "prerouting").set("src-address-list", `${tag}-end`).set("src-mac-address", input.mac).set("dst-address-type", "!local").set("dst-address-list", `!${tag}-local`).set("action", "mark-routing").set("new-routing-mark", input.table).bool("passthrough", false).bool("disabled", true).set("comment", tag).raw(facts.mangle.length ? "place-before=0" : "").build());
15874
+ manage("/ip firewall mangle");
15875
+ warnings.push("IPv6 remains on its existing path. Private/local destinations are excluded. NAT, return routing and actual client delivery must already work for this table; no WAN/VPN/NAT is created.");
15876
+ } else {
15877
+ const queues = facts.queues.filter((q) => q.target === `${ip}/32` && enabled2(q));
15878
+ const q = queues[0], parent = facts.queues.find((r) => r.name === q?.parent && enabled2(r));
15879
+ if (queues.length !== 1 || !q?.name || !parent || !parent["max-limit"]?.split("/").every((r) => Number.parseFloat(r) > 0) || !q["max-limit"]?.split("/").every((r) => Number.parseFloat(r) > 0) || q["packet-marks"] || !/^[1-8]\/[1-8]$/.test(q.priority ?? ""))
15880
+ throw new Error("Meeting priority needs one existing /32 child simple queue with finite parent/child bandwidth and no packet marks. Configure QoS capacity first; this control never guesses line speed.");
15881
+ if (facts.queues.some((r) => r.parent === q.name))
15882
+ throw new Error("Only leaf queues can receive meeting priority.");
15883
+ if (q.priority === "1/1")
15884
+ throw new Error("This client already has the highest queue priority.");
15885
+ queueBefore = { name: q.name, target: q.target, parent: q.parent, priority: q.priority };
15886
+ const selector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority=${quoteValue(q.priority)}]`;
15887
+ activate.push(new Cmd(`/queue simple set ${selector}`).set("priority", "1/1").build());
15888
+ const restoreSelector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority="1/1"]`;
15889
+ revert.push(new Cmd(`/queue simple set ${restoreSelector}`).set("priority", q.priority).build());
15890
+ warnings.push("Priority applies to all IPv4 traffic of this device within its existing queue hierarchy, not just a meeting app. Externally changed queue settings are not overwritten during restoration.");
15891
+ }
15892
+ const generated = temporaryCommands(id, input, ip, setup, activate, revert);
15893
+ if (generated.commands.length > 40)
15894
+ throw new Error("This router needs too many policy objects for a bounded Safe Mode change. Ask an administrator to review it.");
15895
+ const stable = JSON.stringify(facts, (key, value) => key === "#" ? undefined : value);
15896
+ return {
15897
+ ip,
15898
+ ...generated,
15899
+ warnings,
15900
+ queueBefore,
15901
+ fingerprint: createHash2("sha256").update(stable).digest("hex")
15902
+ };
15903
+ }
15904
+ async function policyFacts(ctx, read = executeMikrotikCommand2) {
15905
+ const fasttrackCount = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx, read)).trim();
15906
+ if (!/^\d+$/.test(fasttrackCount))
15907
+ throw new Error("Cannot establish whether FastTrack connections remain active.");
15908
+ return {
15909
+ leases: await rows("/ip dhcp-server lease", "address,active-address,mac-address,active-mac-address,dynamic,disabled,status", ctx, read),
15910
+ filters: await rows("/ip firewall filter", "chain,action,disabled,comment", ctx, read),
15911
+ connections: Number(fasttrackCount) > 0 ? [{ fasttrack: "yes" }] : [],
15912
+ mangle: await rows("/ip firewall mangle", "chain,action,disabled,comment", ctx, read),
15913
+ queues: await rows("/queue simple", "name,target,parent,priority,max-limit,packet-marks,disabled", ctx, read),
15914
+ tables: await rows("/routing table", "name,fib,disabled", ctx, read),
15915
+ routes: await rows("/ip route", "dst-address,routing-table,active,disabled,gateway", ctx, read),
15916
+ addresses: await rows("/ip address", "address,interface", ctx, read),
15917
+ ipv6: parseKeyValues(await checkedRead("/ipv6 settings print", ctx, read)),
15918
+ deviceMode: parseKeyValues(await checkedRead("/system device-mode print", ctx, read))
15919
+ };
15920
+ }
15921
+ var busy3 = new Set;
15922
+ async function exclusive(device, work) {
15923
+ if (busy3.has(device))
15924
+ throw new Error("Another Home Internet operation is in progress for this router.");
15925
+ busy3.add(device);
15926
+ try {
15927
+ return await work();
15928
+ } finally {
15929
+ busy3.delete(device);
15930
+ }
15931
+ }
15932
+ async function previewPolicy(input, ctx) {
15933
+ const a = policyInput.parse(input), device = resolveDeviceName2(ctx.device);
15934
+ a.mac = a.mac.toUpperCase();
15935
+ assertDeviceAccess([device], "preview_home_policy", "WRITE");
15936
+ return exclusive(device, async () => {
15937
+ const id = randomUUID2();
15938
+ const plan = {
15939
+ id,
15940
+ device,
15941
+ input: a,
15942
+ createdAt: Date.now(),
15943
+ previewExpiresAt: Date.now() + 300000,
15944
+ status: "preview",
15945
+ ...buildPolicy(id, a, await policyFacts(ctx))
15946
+ };
15947
+ (await homeStore()).savePlan(plan);
15948
+ return plan;
15949
+ });
15950
+ }
15951
+ async function applyPolicy(id, confirm, ctx) {
15952
+ const device = resolveDeviceName2(ctx.device);
15953
+ assertDeviceAccess([device], "apply_home_policy", "WRITE");
15954
+ if (!confirm)
15955
+ throw new Error("Review the preview and explicitly confirm before applying.");
15956
+ return exclusive(device, async () => {
15957
+ const store = await homeStore(), plan = store.plan(id, device);
15958
+ if (!plan || plan.status !== "preview" || plan.previewExpiresAt < Date.now())
15959
+ throw new Error("Preview expired, already used, or belongs to another router.");
15960
+ if (store.unresolved(device).some((p) => p.input.mac === plan.input.mac && ["applying", "scheduled", "active", "uncertain"].includes(p.status)))
15961
+ throw new Error("Undo or reconcile the previous policy for this device first.");
15962
+ const fresh = buildPolicy(id, plan.input, await policyFacts(ctx));
15963
+ if (fresh.fingerprint !== plan.fingerprint)
15964
+ throw new Error("Router state changed after the preview. Create a fresh preview.");
15965
+ const safe = getSafeModeManager2(device);
15966
+ if (safe.isActive)
15967
+ throw new Error("An existing Safe Mode session is active; finish it before applying a Home Internet policy.");
15968
+ plan.snapshot = await captureSnapshot(ctx, `Before Home Internet ${plan.input.action}`, true);
15969
+ plan.status = "applying";
15970
+ store.claim(plan);
15971
+ let owned = false;
15972
+ try {
15973
+ const status = await safe.enable();
15974
+ if (!status.startsWith("Safe mode ENABLED"))
15975
+ throw new Error("Could not acquire a new Safe Mode session.");
15976
+ owned = true;
15977
+ const lockedFacts = await policyFacts(ctx);
15978
+ if (buildPolicy(id, plan.input, lockedFacts).fingerprint !== plan.fingerprint)
15979
+ throw new Error("Configuration changed while acquiring Safe Mode; create a new preview.");
15980
+ const started = Date.now();
15981
+ for (const command of plan.commands) {
15982
+ if (Date.now() - started > 120000)
15983
+ throw new Error("Policy apply exceeded its time budget.");
15984
+ await checkedRead(command, ctx);
15985
+ }
15986
+ const tag = `mcp-home-${id}`;
15987
+ const count = (await checkedRead(new Cmd("/system scheduler print count-only").raw(`where comment=${quoteValue(tag)}`).build(), ctx)).trim();
15988
+ if (count !== "2")
15989
+ throw new Error("Router-side expiry could not be verified.");
15990
+ const parsed = (await checkedRead(`:put [:typeof [:parse [/system scheduler get [find where name=${quoteValue(tag)}] on-event]]]`, ctx)).trim();
15991
+ if (parsed !== "code")
15992
+ throw new Error("Router could not compile the expiry script.");
15993
+ await verifyPolicyObjects(plan, lockedFacts, ctx);
15994
+ await checkedRead("/system identity print", ctx);
15995
+ const outcome = await safe.commit();
15996
+ if (!outcome.ok)
15997
+ throw new Error("Commit outcome is uncertain; inspect the router before retrying.");
15998
+ owned = false;
15999
+ plan.startsAt = started + plan.input.startInMinutes * 60000;
16000
+ plan.endsAt = plan.startsAt + plan.input.minutes * 60000;
16001
+ plan.status = plan.input.startInMinutes ? "scheduled" : "active";
16002
+ store.savePlan(plan);
16003
+ return plan;
16004
+ } catch (error) {
16005
+ if (owned)
16006
+ await safe.rollback().catch(() => {});
16007
+ plan.status = "uncertain";
16008
+ plan.error = error instanceof Error ? error.message : "Policy operation failed";
16009
+ store.savePlan(plan);
16010
+ throw new Error(`Policy not confirmed: ${plan.error}. Inspect/undo policy ${id}; do not blindly retry.`);
16011
+ }
16012
+ });
16013
+ }
16014
+ async function undoPolicy(id, confirm, ctx) {
16015
+ const device = resolveDeviceName2(ctx.device);
16016
+ assertDeviceAccess([device], "undo_home_policy", "WRITE");
16017
+ if (!confirm)
16018
+ throw new Error("Explicit confirmation is required to undo a policy.");
16019
+ return exclusive(device, async () => {
16020
+ const store = await homeStore(), plan = store.plan(id, device);
16021
+ if (!plan || plan.status === "preview")
16022
+ throw new Error("No applied policy on this router.");
16023
+ if (plan.status === "undone")
16024
+ return plan;
16025
+ const safe = getSafeModeManager2(device);
16026
+ if (safe.isActive)
16027
+ throw new Error("Finish the active Safe Mode session first.");
16028
+ const status = await safe.enable();
16029
+ if (!status.startsWith("Safe mode ENABLED"))
16030
+ throw new Error("Could not acquire Safe Mode.");
16031
+ try {
16032
+ await checkedRead(new Cmd(`/system scheduler disable ${tagSelector(`mcp-home-${id}`)}`).build(), ctx);
16033
+ for (const cmd of plan.undo)
16034
+ await checkedRead(cmd, ctx);
16035
+ if (plan.input.action === "priority") {
16036
+ const expected = plan.queueBefore;
16037
+ if (!expected)
16038
+ throw new Error("Missing queue restoration evidence; reconcile this policy manually.");
16039
+ const current = await rows("/queue simple", "name,target,parent,priority", ctx);
16040
+ const matching = current.filter((q) => q.name === expected.name && q.target === expected.target && q.parent === expected.parent);
16041
+ if (matching.length !== 1 || matching[0].priority !== expected.priority)
16042
+ throw new Error("Queue restoration was not verified. External queue changes require manual reconciliation.");
16043
+ }
16044
+ for (const path of [
16045
+ "/system scheduler",
16046
+ "/ip firewall address-list",
16047
+ "/ip firewall filter",
16048
+ "/ip firewall mangle"
16049
+ ]) {
16050
+ const remaining = (await checkedRead(new Cmd(`${path} print count-only`).raw(`where comment=${quoteValue(`mcp-home-${id}`)}`).build(), ctx)).trim();
16051
+ if (remaining !== "0")
16052
+ throw new Error("Policy cleanup could not be verified; the undo was not committed.");
16053
+ }
16054
+ const committed = await safe.commit();
16055
+ if (!committed.ok)
16056
+ throw new Error("Undo commit could not be confirmed");
16057
+ plan.status = "undone";
16058
+ store.savePlan(plan);
16059
+ return plan;
16060
+ } catch (e) {
16061
+ await safe.rollback().catch(() => {});
16062
+ throw e;
16063
+ }
16064
+ });
16065
+ }
16066
+ async function verifyPolicyObjects(plan, before, ctx) {
16067
+ const tag = `mcp-home-${plan.id}`;
16068
+ const marker = (await checkedRead(new Cmd("/ip firewall address-list print count-only").raw(`where list=${quoteValue(`${tag}-end`)}`).build(), ctx)).trim();
16069
+ if (marker !== "1")
16070
+ throw new Error("Expiry marker could not be verified.");
16071
+ if (plan.input.action === "priority") {
16072
+ const old = before.queues.find((q) => q.target === `${plan.ip}/32` && enabled2(q));
16073
+ const current = await rows("/queue simple", "name,target,parent,priority,max-limit,disabled", ctx);
16074
+ const q = current.find((r) => r.name === old.name && r.target === old.target && r.parent === old.parent);
16075
+ if (!q || q.priority !== (plan.input.startInMinutes ? old.priority : "1/1"))
16076
+ throw new Error("Meeting queue priority was not verified.");
16077
+ } else {
16078
+ const path = plan.input.action === "pause" ? "/ip firewall filter" : "/ip firewall mangle";
16079
+ const current = await rows(path, "comment,disabled,action,chain,src-address-list,dst-address-list,new-routing-mark,src-mac-address,dst-address-type", ctx);
16080
+ const owned = current.filter((r) => r.comment === tag);
16081
+ if (owned.length !== (plan.input.action === "pause" ? 2 : 1) || owned.some((r) => enabled2(r) === plan.input.startInMinutes > 0))
16082
+ throw new Error("Policy rules were not verified in their expected state.");
16083
+ if (plan.input.action === "pause") {
16084
+ if (owned.some((r) => r.chain !== "forward" || r.action !== "drop") || owned.filter((r) => r["src-address-list"] === `${tag}-end`).length !== 1 || owned.filter((r) => r["dst-address-list"] === `${tag}-end`).length !== 1)
16085
+ throw new Error("Pause rule targeting could not be verified.");
16086
+ } else if (owned.some((r) => r.chain !== "prerouting" || r.action !== "mark-routing" || r["src-address-list"] !== `${tag}-end` || r["src-mac-address"]?.toUpperCase() !== plan.input.mac || r["new-routing-mark"] !== plan.input.table || r["dst-address-type"] !== "!local" || r["dst-address-list"] !== `!${tag}-local`)) {
16087
+ throw new Error("Path selection targeting could not be verified.");
16088
+ }
16089
+ }
16090
+ }
16091
+
16092
+ // src/tools/home-internet.ts
16093
+ var homeInternetTools = [
16094
+ defineTool2({
16095
+ name: "diagnose_home_internet",
16096
+ title: "Why Is My Internet Slow?",
16097
+ annotations: READ,
16098
+ description: "Start here when a household client reports slow internet. Read router CPU/memory, client Wi-Fi signal, DNS, exact-IP queues and five bounded router ICMP probes. Return plain-language observed facts, suspected causes and unknowns with next steps. Never changes MTU/config, enables accounting or claims client application success. No throughput test is run.",
16099
+ inputSchema: diagnosisInput.shape,
16100
+ handler: async (a, ctx) => JSON.stringify(await diagnoseInternet(a, ctx))
16101
+ }),
16102
+ defineTool2({
16103
+ name: "compare_home_paths",
16104
+ title: "Compare Internet Paths",
16105
+ annotations: READ,
16106
+ description: "Compare up to three existing enabled FIB routing tables with five ICMP probes each to one explicit IPv4 target. For calls/gaming suggest the lowest-loss/latency candidate; download throughput is unmeasured, so no fastest-download recommendation. Router output mangle may affect probes. Selection is separate: preview_home_policy, then explicit user approval and apply_home_policy. Never switches routes automatically.",
16107
+ inputSchema: compareInput.shape,
16108
+ handler: async (a, ctx) => JSON.stringify(await comparePaths(a, ctx))
16109
+ }),
16110
+ defineTool2({
16111
+ name: "get_home_internet",
16112
+ title: "Read Household Internet Workspace",
16113
+ annotations: READ,
16114
+ description: "Read locally saved household device names, people, newly discovered devices and temporary policy history for this router. Historical policy status is not current router proof. No router queries; refresh_home_devices explicitly collects current DHCP records and available routing tables.",
16115
+ inputSchema: {},
16116
+ async handler(_a, ctx) {
16117
+ const device = resolveDeviceName2(ctx.device);
16118
+ assertDeviceAccess([device], "get_home_internet", "READ");
16119
+ const store = await homeStore();
16120
+ return JSON.stringify({
16121
+ device,
16122
+ clients: store.clients(device),
16123
+ policies: store.plans(device),
16124
+ statusNote: "Saved status only. A passed expiry time is not a verified cleanup result; Undo can reconcile owned objects."
16125
+ });
16126
+ }
16127
+ }),
16128
+ defineTool2({
16129
+ name: "refresh_home_devices",
16130
+ title: "Discover Household Devices",
16131
+ annotations: WRITE,
16132
+ description: "Read DHCP clients and routing tables, saving a local first/last-seen household inventory. First scan establishes a baseline; later new MACs appear as unacknowledged notices. No router writes or background scans. WRITE reflects local persistence. Randomized MACs may look like new devices; absence does not prove offline.",
16133
+ inputSchema: {},
16134
+ async handler(_a, ctx) {
16135
+ const device = resolveDeviceName2(ctx.device);
16136
+ assertDeviceAccess([device], "refresh_home_devices", "WRITE");
16137
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,host-name,status", ctx);
16138
+ const tables = await rows("/routing table", "name,fib,disabled", ctx);
16139
+ const store = await homeStore(), old = store.clients(device), now = Date.now();
16140
+ const seen = new Set;
16141
+ for (const r of leases) {
16142
+ const parsed = macInput.safeParse(r["mac-address"]);
16143
+ if (!parsed.success)
16144
+ continue;
16145
+ const mac = parsed.data.toUpperCase(), prior = old.find((c) => c.mac === mac);
16146
+ seen.add(mac);
16147
+ store.saveClient(device, {
16148
+ mac,
16149
+ ip: r.address ?? "",
16150
+ hostname: r["host-name"] ?? "",
16151
+ name: prior?.name ?? "",
16152
+ person: prior?.person ?? "",
16153
+ firstSeen: prior?.firstSeen ?? now,
16154
+ lastSeen: now,
16155
+ acknowledged: prior?.acknowledged ?? old.length === 0,
16156
+ present: r.status === "bound"
16157
+ });
16158
+ }
16159
+ for (const client of old)
16160
+ if (!seen.has(client.mac))
16161
+ store.saveClient(device, { ...client, present: false });
16162
+ return JSON.stringify({
16163
+ device,
16164
+ clients: store.clients(device),
16165
+ tables: tables.filter((t) => enabled2(t) && ["yes", "true"].includes(t.fib)).map((t) => t.name)
16166
+ });
16167
+ }
16168
+ }),
16169
+ defineTool2({
16170
+ name: "name_home_device",
16171
+ title: "Name a Household Device",
16172
+ annotations: WRITE,
16173
+ description: "Save a friendly device name and person locally and acknowledge its new-device notice. Does not modify router DHCP, reserve an IP or change access.",
16174
+ inputSchema: {
16175
+ mac: macInput,
16176
+ name: string().trim().max(80),
16177
+ person: string().trim().max(80).default("")
16178
+ },
16179
+ async handler(a, ctx) {
16180
+ const device = resolveDeviceName2(ctx.device);
16181
+ assertDeviceAccess([device], "name_home_device", "WRITE");
16182
+ const store = await homeStore(), client = store.clients(device).find((c) => c.mac === a.mac.toUpperCase());
16183
+ if (!client)
16184
+ throw new Error("Refresh household devices first.");
16185
+ const result = { ...client, name: a.name, person: a.person, acknowledged: true };
16186
+ store.saveClient(device, result);
16187
+ return JSON.stringify(result);
16188
+ }
16189
+ }),
16190
+ defineTool2({
16191
+ name: "preview_home_policy",
16192
+ title: "Preview a Temporary Household Policy",
16193
+ annotations: WRITE,
16194
+ description: "Prepare a device-bound five-minute consent preview for a reserved IPv4 DHCP client: pause routed access, raise an existing child queue to meeting priority, or select an existing route table. Duration 5\u2013120 minutes; optional start delay up to 24h. Local preview only, no router changes. Fails closed on FastTrack, ambiguous leases, conflicting route marks or missing QoS. Pause refuses IPv6 forwarding. Review exact commands, limitations and expiry with the user before applying.",
16195
+ inputSchema: policyInput.shape,
16196
+ handler: async (a, ctx) => JSON.stringify(await previewPolicy(a, ctx))
16197
+ }),
16198
+ defineTool2({
16199
+ name: "apply_home_policy",
16200
+ title: "Apply an Approved Household Policy",
16201
+ annotations: WRITE,
16202
+ description: "Only after explicit user approval of preview_home_policy: consume its one-use ID, recheck unchanged router state, save a local snapshot, apply in a NEW Safe Mode session, install router-side expiry and commit. No direct-write fallback. Scheduled policies expire even if MCP stops; priority restoration requires scheduler permission. Existing sessions may disconnect. Uncertain results must be inspected/undone, never blindly retried.",
16203
+ inputSchema: { id: uuid2(), confirm: boolean().default(false) },
16204
+ handler: async (a, ctx) => JSON.stringify(await applyPolicy(a.id, a.confirm, ctx))
16205
+ }),
16206
+ defineTool2({
16207
+ name: "undo_home_policy",
16208
+ title: "Undo a Household Policy",
16209
+ annotations: WRITE,
16210
+ description: "With user confirmation remove only this policy's tagged rules/timers and restore its previous queue priority when the queue still matches. Works from durable history after an MCP restart. Does not restore an entire config or touch unrelated rules. Use to reconcile expired or uncertain policies too.",
16211
+ inputSchema: { id: uuid2(), confirm: boolean().default(false) },
16212
+ handler: async (a, ctx) => JSON.stringify(await undoPolicy(a.id, a.confirm, ctx))
16213
+ })
16214
+ ];
16215
+
16216
+ // src/tools/service-contracts.ts
16217
+ import { randomUUID as randomUUID4 } from "crypto";
16218
+
16219
+ // src/service-contracts/store.ts
16220
+ import { mkdirSync as mkdirSync6 } from "fs";
16221
+ import { dirname as dirname6 } from "path";
15307
16222
  class ContractStore {
15308
16223
  db;
15309
16224
  constructor(db) {
@@ -15329,23 +16244,23 @@ class ContractStore {
15329
16244
  return this.db.query("SELECT body FROM service_contract_runs WHERE contract_id = ? ORDER BY started_at DESC LIMIT 100").all(id).map((r) => JSON.parse(r.body));
15330
16245
  }
15331
16246
  }
15332
- var pending2;
16247
+ var pending3;
15333
16248
  function contractStore() {
15334
- pending2 ??= (async () => {
15335
- mkdirSync4(dirname4(DEFAULT_SNAPSHOT_DB), { recursive: true });
16249
+ pending3 ??= (async () => {
16250
+ mkdirSync6(dirname6(DEFAULT_SNAPSHOT_DB), { recursive: true });
15336
16251
  const { Database } = await import("bun:sqlite");
15337
16252
  const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
15338
16253
  db.run("PRAGMA journal_mode = WAL");
15339
16254
  return new ContractStore(db);
15340
16255
  })().catch((e) => {
15341
- pending2 = undefined;
16256
+ pending3 = undefined;
15342
16257
  throw e;
15343
16258
  });
15344
- return pending2;
16259
+ return pending3;
15345
16260
  }
15346
16261
 
15347
16262
  // src/service-contracts/run.ts
15348
- import { randomUUID as randomUUID2 } from "crypto";
16263
+ import { randomUUID as randomUUID3 } from "crypto";
15349
16264
 
15350
16265
  // src/policy/parse.ts
15351
16266
  function normalizeSection(path) {
@@ -16652,8 +17567,8 @@ function diffTraces(before, after) {
16652
17567
  }
16653
17568
 
16654
17569
  // src/sim/suites.ts
16655
- import { mkdirSync as mkdirSync5 } from "fs";
16656
- import { dirname as dirname5 } from "path";
17570
+ import { mkdirSync as mkdirSync7 } from "fs";
17571
+ import { dirname as dirname7 } from "path";
16657
17572
  var SCHEMA = [
16658
17573
  `CREATE TABLE IF NOT EXISTS sim_suites (
16659
17574
  id TEXT PRIMARY KEY,
@@ -16699,16 +17614,16 @@ class SqliteSuiteStore {
16699
17614
  });
16700
17615
  }
16701
17616
  }
16702
- var storePromise3 = null;
17617
+ var storePromise4 = null;
16703
17618
  async function store2() {
16704
- storePromise3 ??= (async () => {
17619
+ storePromise4 ??= (async () => {
16705
17620
  try {
16706
- mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
17621
+ mkdirSync7(dirname7(DEFAULT_SNAPSHOT_DB), { recursive: true });
16707
17622
  } catch {}
16708
17623
  const { Database } = await import("bun:sqlite");
16709
17624
  return new SqliteSuiteStore(new Database(DEFAULT_SNAPSHOT_DB, { create: true }));
16710
17625
  })();
16711
- return storePromise3;
17626
+ return storePromise4;
16712
17627
  }
16713
17628
  async function getSuite(id) {
16714
17629
  try {
@@ -16718,30 +17633,6 @@ async function getSuite(id) {
16718
17633
  }
16719
17634
  }
16720
17635
 
16721
- // src/snapshots/format.ts
16722
- import { createHash } from "crypto";
16723
- var TIMESTAMP_HEADER = /^#\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b.*by RouterOS/i;
16724
- function parseExportMeta(body) {
16725
- const head = body.slice(0, 600);
16726
- const version = head.match(/by RouterOS ([^\s#]+)/i)?.[1];
16727
- const exportedAt = head.match(/#\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1];
16728
- return { rosVersion: version, exportedAt };
16729
- }
16730
- function normalizeExport(body) {
16731
- return body.replace(/\r\n/g, `
16732
- `).split(`
16733
- `).filter((line) => !TIMESTAMP_HEADER.test(line)).join(`
16734
- `).replace(/\n+$/, "");
16735
- }
16736
- function contentSha(normalizedBody) {
16737
- return createHash("sha256").update(normalizedBody, "utf8").digest("hex").slice(0, 16);
16738
- }
16739
- function countLines(body) {
16740
- const trimmed = body.replace(/\n+$/, "");
16741
- return trimmed === "" ? 0 : trimmed.split(`
16742
- `).length;
16743
- }
16744
-
16745
17636
  // src/service-contracts/probe.ts
16746
17637
  import { Resolver } from "dns/promises";
16747
17638
  import { connect, isIP } from "net";
@@ -16904,7 +17795,7 @@ async function evaluateContract(contract, io, simulationExport) {
16904
17795
  }
16905
17796
  }
16906
17797
  return {
16907
- id: randomUUID2(),
17798
+ id: randomUUID3(),
16908
17799
  contractId: contract.id,
16909
17800
  device: contract.device,
16910
17801
  startedAt,
@@ -17029,7 +17920,7 @@ var serviceContractTools = [
17029
17920
  const args = contractInput.parse(a);
17030
17921
  if (args.checks.some((c) => !getConfig2().serviceProbes.targets[c.target]))
17031
17922
  throw new Error("Contract references an unapproved target. Ask the administrator to configure it.");
17032
- const contract = { ...args, id: randomUUID3(), device, createdAt: Date.now() };
17923
+ const contract = { ...args, id: randomUUID4(), device, createdAt: Date.now() };
17033
17924
  (await contractStore()).save(contract);
17034
17925
  return JSON.stringify(contract);
17035
17926
  }
@@ -17073,146 +17964,6 @@ var serviceContractTools = [
17073
17964
  })
17074
17965
  ];
17075
17966
 
17076
- // src/snapshots/store.ts
17077
- import { mkdirSync as mkdirSync6 } from "fs";
17078
- import { dirname as dirname6 } from "path";
17079
- function rowToBaseline(r) {
17080
- return {
17081
- device: r.device,
17082
- snapshotId: r.snapshot_id,
17083
- setAt: r.set_at,
17084
- setBy: r.set_by,
17085
- label: r.label ?? undefined,
17086
- notes: r.notes ?? undefined
17087
- };
17088
- }
17089
- function rowToSnapshot(r, body) {
17090
- return {
17091
- id: r.id,
17092
- device: r.device,
17093
- ts: r.ts,
17094
- label: r.label ?? undefined,
17095
- rosVersion: r.ros_version ?? undefined,
17096
- body,
17097
- bytes: r.bytes,
17098
- lines: r.lines,
17099
- sha: r.sha
17100
- };
17101
- }
17102
- var SCHEMA_STATEMENTS3 = [
17103
- `CREATE TABLE IF NOT EXISTS snapshots (
17104
- id TEXT PRIMARY KEY,
17105
- device TEXT NOT NULL,
17106
- ts INTEGER NOT NULL,
17107
- label TEXT,
17108
- ros_version TEXT,
17109
- body TEXT NOT NULL,
17110
- bytes INTEGER NOT NULL,
17111
- lines INTEGER NOT NULL,
17112
- sha TEXT NOT NULL
17113
- )`,
17114
- "CREATE INDEX IF NOT EXISTS idx_snapshots_device_ts ON snapshots(device, ts)",
17115
- `CREATE TABLE IF NOT EXISTS baselines (
17116
- device TEXT PRIMARY KEY,
17117
- snapshot_id TEXT NOT NULL,
17118
- set_at INTEGER NOT NULL,
17119
- set_by TEXT NOT NULL DEFAULT 'agent',
17120
- label TEXT,
17121
- notes TEXT
17122
- )`
17123
- ];
17124
-
17125
- class SqliteSnapshotStore {
17126
- db;
17127
- constructor(db) {
17128
- this.db = db;
17129
- db.run("PRAGMA journal_mode = WAL");
17130
- db.run("PRAGMA synchronous = NORMAL");
17131
- for (const stmt of SCHEMA_STATEMENTS3)
17132
- db.run(stmt);
17133
- }
17134
- insert(s) {
17135
- this.db.query(`INSERT OR REPLACE INTO snapshots
17136
- (id, device, ts, label, ros_version, body, bytes, lines, sha)
17137
- VALUES ($id,$device,$ts,$label,$ver,$body,$bytes,$lines,$sha)`).run({
17138
- $id: s.id,
17139
- $device: s.device,
17140
- $ts: s.ts,
17141
- $label: s.label ?? null,
17142
- $ver: s.rosVersion ?? null,
17143
- $body: s.body,
17144
- $bytes: s.bytes,
17145
- $lines: s.lines,
17146
- $sha: s.sha
17147
- });
17148
- }
17149
- get(id) {
17150
- const row = this.db.query("SELECT * FROM snapshots WHERE id = $id").get({ $id: id });
17151
- return row ? rowToSnapshot(row, row.body) : null;
17152
- }
17153
- latest(device) {
17154
- const row = this.db.query("SELECT * FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT 1").get({ $d: device });
17155
- return row ? rowToSnapshot(row, row.body) : null;
17156
- }
17157
- list(device, limit = 50, withBody = false) {
17158
- const cols = withBody ? "*" : "id, device, ts, label, ros_version, bytes, lines, sha";
17159
- const n = Math.min(Math.max(limit, 1), 500);
17160
- const rows = this.db.query(`SELECT ${cols} FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT $n`).all({ $d: device, $n: n });
17161
- return rows.map((r) => rowToSnapshot(r, withBody ? r.body : ""));
17162
- }
17163
- count(device) {
17164
- const r = this.db.query("SELECT COUNT(*) AS n FROM snapshots WHERE device = $d").get({ $d: device });
17165
- return r.n;
17166
- }
17167
- delete(ids) {
17168
- if (ids.length === 0)
17169
- return 0;
17170
- const placeholders = ids.map((_, j) => `$id${j}`).join(",");
17171
- const params = {};
17172
- ids.forEach((id, j) => {
17173
- params[`$id${j}`] = id;
17174
- });
17175
- const res = this.db.query(`DELETE FROM snapshots WHERE id IN (${placeholders})`).run(params);
17176
- return Number(res.changes ?? 0);
17177
- }
17178
- setBaseline(device, snapshotId, setBy = "agent", label, notes) {
17179
- this.db.query(`INSERT OR REPLACE INTO baselines (device, snapshot_id, set_at, set_by, label, notes)
17180
- VALUES ($device, $snapId, $setAt, $setBy, $label, $notes)`).run({
17181
- $device: device,
17182
- $snapId: snapshotId,
17183
- $setAt: Date.now(),
17184
- $setBy: setBy,
17185
- $label: label ?? null,
17186
- $notes: notes ?? null
17187
- });
17188
- }
17189
- getBaseline(device) {
17190
- const row = this.db.query("SELECT * FROM baselines WHERE device = $d").get({ $d: device });
17191
- return row ? rowToBaseline(row) : null;
17192
- }
17193
- removeBaseline(device) {
17194
- const res = this.db.query("DELETE FROM baselines WHERE device = $d").run({ $d: device });
17195
- return (res.changes ?? 0) > 0;
17196
- }
17197
- listBaselines() {
17198
- const rows = this.db.query("SELECT * FROM baselines ORDER BY set_at DESC").all();
17199
- return rows.map(rowToBaseline);
17200
- }
17201
- close() {
17202
- this.db.close();
17203
- }
17204
- }
17205
- async function openSnapshotStore(path) {
17206
- if (path !== ":memory:") {
17207
- try {
17208
- mkdirSync6(dirname6(path), { recursive: true });
17209
- } catch {}
17210
- }
17211
- const { Database } = await import("bun:sqlite");
17212
- const db = new Database(path, { create: true });
17213
- return new SqliteSnapshotStore(db);
17214
- }
17215
-
17216
17967
  // src/paths/round-trip.ts
17217
17968
  var hop = object({
17218
17969
  device: string().min(1).max(128),
@@ -17423,21 +18174,21 @@ import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
17423
18174
 
17424
18175
  // src/paths.ts
17425
18176
  import { existsSync } from "fs";
17426
- import { join as join2, dirname as dirname7 } from "path";
18177
+ import { join as join2, dirname as dirname8 } from "path";
17427
18178
  import { fileURLToPath } from "url";
17428
18179
  var meta3 = import.meta;
17429
- var HERE = meta3.dir ?? meta3.dirname ?? dirname7(fileURLToPath(import.meta.url));
18180
+ var HERE = meta3.dir ?? meta3.dirname ?? dirname8(fileURLToPath(import.meta.url));
17430
18181
  function findRoot(start) {
17431
18182
  let dir = start;
17432
18183
  for (let i = 0;i < 12; i++) {
17433
18184
  if (existsSync(join2(dir, "package.json")))
17434
18185
  return dir;
17435
- const parent = dirname7(dir);
18186
+ const parent = dirname8(dir);
17436
18187
  if (parent === dir)
17437
18188
  break;
17438
18189
  dir = parent;
17439
18190
  }
17440
- return dirname7(start);
18191
+ return dirname8(start);
17441
18192
  }
17442
18193
  var ROOT = findRoot(HERE);
17443
18194
  var PROMPTS_DIR = join2(ROOT, "prompts");
@@ -17694,7 +18445,7 @@ async function checkDiskSpace(ctx) {
17694
18445
  // src/backups/vault.ts
17695
18446
  import {
17696
18447
  existsSync as existsSync2,
17697
- mkdirSync as mkdirSync7,
18448
+ mkdirSync as mkdirSync8,
17698
18449
  readFileSync as readFileSync4,
17699
18450
  readdirSync,
17700
18451
  renameSync,
@@ -17741,7 +18492,7 @@ function readBackup(name) {
17741
18492
  }
17742
18493
  function writeBackup(name, content) {
17743
18494
  const dir = backupDir();
17744
- mkdirSync7(dir, { recursive: true });
18495
+ mkdirSync8(dir, { recursive: true });
17745
18496
  let final = safeName(name);
17746
18497
  if (existsSync2(join4(dir, final))) {
17747
18498
  const dot = final.lastIndexOf(".");
@@ -17757,7 +18508,7 @@ function writeBackup(name, content) {
17757
18508
  }
17758
18509
  function writeBinaryBackup(name, data) {
17759
18510
  const dir = backupDir();
17760
- mkdirSync7(dir, { recursive: true });
18511
+ mkdirSync8(dir, { recursive: true });
17761
18512
  let final = safeName(name);
17762
18513
  if (existsSync2(join4(dir, final))) {
17763
18514
  const dot = final.lastIndexOf(".");
@@ -20984,11 +21735,11 @@ No differences \u2014 the live configuration matches the golden baseline.`);
20984
21735
  }
20985
21736
 
20986
21737
  // src/tools/config-drift.ts
20987
- var storePromise4 = null;
21738
+ var storePromise5 = null;
20988
21739
  function store3() {
20989
- if (!storePromise4)
20990
- storePromise4 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
20991
- return storePromise4;
21740
+ if (!storePromise5)
21741
+ storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
21742
+ return storePromise5;
20992
21743
  }
20993
21744
  function buildExport(opts) {
20994
21745
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -21196,11 +21947,11 @@ New: ${describeBaseline(snap)}${notesLine}`;
21196
21947
  ];
21197
21948
 
21198
21949
  // src/tools/config-snapshot.ts
21199
- var storePromise5 = null;
21200
- function snapshots() {
21201
- if (!storePromise5)
21202
- storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
21203
- return storePromise5;
21950
+ var storePromise6 = null;
21951
+ function snapshots2() {
21952
+ if (!storePromise6)
21953
+ storePromise6 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
21954
+ return storePromise6;
21204
21955
  }
21205
21956
  function exportCommand(opts) {
21206
21957
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -21257,7 +22008,7 @@ var configSnapshotTools = [
21257
22008
  });
21258
22009
  const meta = parseExportMeta(body);
21259
22010
  const sha = contentSha(normalizeExport(body));
21260
- const store = await snapshots();
22011
+ const store = await snapshots2();
21261
22012
  const prev = store.latest(device);
21262
22013
  if (prev && prev.sha === sha && !a.force) {
21263
22014
  return `No configuration change since the last snapshot \u2014 nothing stored.
@@ -21293,7 +22044,7 @@ ${drift}`;
21293
22044
  },
21294
22045
  async handler(a, ctx) {
21295
22046
  const device = resolveDeviceName2(ctx.device);
21296
- const store = await snapshots();
22047
+ const store = await snapshots2();
21297
22048
  const rows = store.list(device, a.limit, false);
21298
22049
  if (rows.length === 0) {
21299
22050
  return `No configuration snapshots stored for '${device}'. Capture one with capture_config_snapshot.`;
@@ -21316,7 +22067,7 @@ ${lines}`;
21316
22067
  include_body: boolean().default(true)
21317
22068
  },
21318
22069
  async handler(a, ctx) {
21319
- const store = await snapshots();
22070
+ const store = await snapshots2();
21320
22071
  const snap = store.get(a.id);
21321
22072
  if (!snap)
21322
22073
  return `Snapshot '${a.id}' not found.`;
@@ -21344,7 +22095,7 @@ ${snap.body}
21344
22095
  },
21345
22096
  async handler(a, ctx) {
21346
22097
  const device = resolveDeviceName2(ctx.device);
21347
- const store = await snapshots();
22098
+ const store = await snapshots2();
21348
22099
  const from = await resolveRef(store, a.from, device, ctx);
21349
22100
  const to = await resolveRef(store, a.to, device, ctx);
21350
22101
  const result = diffLines(normalizeExport(from.body), normalizeExport(to.body), {
@@ -21384,7 +22135,7 @@ ${result.unified}`;
21384
22135
  ids: array(string()).min(1)
21385
22136
  },
21386
22137
  async handler(a) {
21387
- const store = await snapshots();
22138
+ const store = await snapshots2();
21388
22139
  const removed = store.delete(a.ids);
21389
22140
  if (removed === 0)
21390
22141
  return `No snapshots removed (none of the given ids matched).`;
@@ -21695,10 +22446,10 @@ ${created.join(`
21695
22446
  import * as ipaddr2 from "ipaddr.js";
21696
22447
 
21697
22448
  // src/schedule/identity.ts
21698
- import { createHash as createHash2 } from "crypto";
22449
+ import { createHash as createHash3 } from "crypto";
21699
22450
  function stableId(prefix, parts) {
21700
22451
  const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
21701
- const digest = createHash2("sha256").update(material, "utf8").digest("hex").slice(0, 12);
22452
+ const digest = createHash3("sha256").update(material, "utf8").digest("hex").slice(0, 12);
21702
22453
  return `${prefix}:${digest}`;
21703
22454
  }
21704
22455
  function ruleFingerprint(rule) {
@@ -23024,7 +23775,7 @@ var cache2 = null;
23024
23775
  async function gateway() {
23025
23776
  if (cache2)
23026
23777
  return cache2;
23027
- const { moduleCatalog } = await import("./library-drn9gmjm.js");
23778
+ const { moduleCatalog } = await import("./library-pj8kwdeg.js");
23028
23779
  const forIndex = [];
23029
23780
  const byName = new Map;
23030
23781
  for (const mod of moduleCatalog) {
@@ -25252,34 +26003,6 @@ No findings \u2014 the device passes every hardening check. \u2713`;
25252
26003
  ${body}`;
25253
26004
  }
25254
26005
 
25255
- // src/snapshots/capture.ts
25256
- var storePromise6 = null;
25257
- function snapshots2() {
25258
- if (!storePromise6)
25259
- storePromise6 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
25260
- return storePromise6;
25261
- }
25262
- async function captureSnapshot(ctx, label) {
25263
- const device = resolveDeviceName2(ctx.device);
25264
- const body = await executeMikrotikCommand2("/export terse", ctx);
25265
- const meta = parseExportMeta(body);
25266
- const sha = contentSha(normalizeExport(body));
25267
- const ts = Date.now();
25268
- const snap = {
25269
- id: `snap_${ts}_${sha.slice(0, 8)}`,
25270
- device,
25271
- ts,
25272
- label,
25273
- rosVersion: meta.rosVersion,
25274
- body,
25275
- bytes: Buffer.byteLength(body, "utf8"),
25276
- lines: countLines(body),
25277
- sha
25278
- };
25279
- (await snapshots2()).insert(snap);
25280
- return snap.id;
25281
- }
25282
-
25283
26006
  // src/tools/security-hardening.ts
25284
26007
  async function fetchSecurityState(ctx) {
25285
26008
  const [
@@ -26012,7 +26735,7 @@ function evaluatePolicies(policies, model, opts = {}) {
26012
26735
 
26013
26736
  // src/policy/load.ts
26014
26737
  import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
26015
- import { dirname as dirname8, isAbsolute, join as join5, resolve as resolve3 } from "path";
26738
+ import { dirname as dirname9, isAbsolute, join as join5, resolve as resolve3 } from "path";
26016
26739
 
26017
26740
  // src/policy/schema.ts
26018
26741
  var MAX_REGEX_LENGTH = 200;
@@ -26135,7 +26858,7 @@ function validatePolicyText(text) {
26135
26858
  var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
26136
26859
  function expand(pattern, cwd) {
26137
26860
  const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
26138
- const base = dirname8(absolute);
26861
+ const base = dirname9(absolute);
26139
26862
  const leaf = absolute.slice(base.length + 1);
26140
26863
  if (!leaf.includes("*")) {
26141
26864
  try {
@@ -42843,8 +43566,8 @@ function publishTxn(update) {
42843
43566
  }
42844
43567
 
42845
43568
  // src/txn/store.ts
42846
- import { mkdirSync as mkdirSync8 } from "fs";
42847
- import { dirname as dirname9 } from "path";
43569
+ import { mkdirSync as mkdirSync9 } from "fs";
43570
+ import { dirname as dirname10 } from "path";
42848
43571
  function toRecord(txn, ts, label) {
42849
43572
  return {
42850
43573
  id: txn.id,
@@ -42980,7 +43703,7 @@ class SqliteTxnStore {
42980
43703
  async function openTxnStore(path) {
42981
43704
  if (path !== ":memory:") {
42982
43705
  try {
42983
- mkdirSync8(dirname9(path), { recursive: true });
43706
+ mkdirSync9(dirname10(path), { recursive: true });
42984
43707
  } catch {}
42985
43708
  }
42986
43709
  const { Database } = await import("bun:sqlite");
@@ -43847,8 +44570,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
43847
44570
  }
43848
44571
 
43849
44572
  // src/rollout/store.ts
43850
- import { mkdirSync as mkdirSync9 } from "fs";
43851
- import { dirname as dirname10 } from "path";
44573
+ import { mkdirSync as mkdirSync10 } from "fs";
44574
+ import { dirname as dirname11 } from "path";
43852
44575
  function toRecord2(rollout, ts, opts = {}) {
43853
44576
  return {
43854
44577
  id: rollout.id,
@@ -43981,7 +44704,7 @@ class SqliteRolloutStore {
43981
44704
  async function openRolloutStore(path) {
43982
44705
  if (path !== ":memory:") {
43983
44706
  try {
43984
- mkdirSync9(dirname10(path), { recursive: true });
44707
+ mkdirSync10(dirname11(path), { recursive: true });
43985
44708
  } catch {}
43986
44709
  }
43987
44710
  const { Database } = await import("bun:sqlite");
@@ -44697,8 +45420,8 @@ var JobSchema = object({
44697
45420
  });
44698
45421
 
44699
45422
  // src/schedule/store.ts
44700
- import { mkdirSync as mkdirSync10 } from "fs";
44701
- import { dirname as dirname11 } from "path";
45423
+ import { mkdirSync as mkdirSync11 } from "fs";
45424
+ import { dirname as dirname12 } from "path";
44702
45425
  var SCHEMA2 = [
44703
45426
  `CREATE TABLE IF NOT EXISTS schedule_jobs (
44704
45427
  id TEXT PRIMARY KEY,
@@ -44840,7 +45563,7 @@ class SqliteScheduleStore {
44840
45563
  async function openScheduleStore(path) {
44841
45564
  if (path !== ":memory:") {
44842
45565
  try {
44843
- mkdirSync10(dirname11(path), { recursive: true });
45566
+ mkdirSync11(dirname12(path), { recursive: true });
44844
45567
  } catch {}
44845
45568
  }
44846
45569
  const { Database } = await import("bun:sqlite");
@@ -45002,7 +45725,7 @@ var riskByTool = null;
45002
45725
  async function riskIndex() {
45003
45726
  if (riskByTool)
45004
45727
  return riskByTool;
45005
- const { moduleCatalog } = await import("./library-drn9gmjm.js");
45728
+ const { moduleCatalog } = await import("./library-pj8kwdeg.js");
45006
45729
  const index = new Map;
45007
45730
  for (const mod of moduleCatalog) {
45008
45731
  for (const tool of mod.tools)
@@ -47166,7 +47889,7 @@ async function readScanList(ctx, list = "port-scanners") {
47166
47889
  }
47167
47890
 
47168
47891
  // src/attack/correlate.ts
47169
- import { createHash as createHash3 } from "crypto";
47892
+ import { createHash as createHash4 } from "crypto";
47170
47893
  var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
47171
47894
  var STAGE_OF = {
47172
47895
  "port-scan": "recon",
@@ -47196,7 +47919,7 @@ var SEVERITY_RANK = {
47196
47919
  info: 4
47197
47920
  };
47198
47921
  function incidentId(source, dayBucket) {
47199
- const digest = createHash3("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
47922
+ const digest = createHash4("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
47200
47923
  return `atk_${digest}`;
47201
47924
  }
47202
47925
  function worst(values) {
@@ -47418,8 +48141,8 @@ function dedupe(events, seen) {
47418
48141
  }
47419
48142
 
47420
48143
  // src/attack/store.ts
47421
- import { mkdirSync as mkdirSync11 } from "fs";
47422
- import { dirname as dirname12 } from "path";
48144
+ import { mkdirSync as mkdirSync12 } from "fs";
48145
+ import { dirname as dirname13 } from "path";
47423
48146
  var SCHEMA3 = [
47424
48147
  `CREATE TABLE IF NOT EXISTS attack_incidents (
47425
48148
  id TEXT PRIMARY KEY,
@@ -47610,7 +48333,7 @@ class SqliteAttackStore {
47610
48333
  async function openAttackStore(path) {
47611
48334
  if (path !== ":memory:") {
47612
48335
  try {
47613
- mkdirSync11(dirname12(path), { recursive: true });
48336
+ mkdirSync12(dirname13(path), { recursive: true });
47614
48337
  } catch {}
47615
48338
  }
47616
48339
  const { Database } = await import("bun:sqlite");
@@ -48284,9 +49007,9 @@ ${result}`;
48284
49007
  ];
48285
49008
 
48286
49009
  // src/core/update-check.ts
48287
- import { existsSync as existsSync3, mkdirSync as mkdirSync12, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
49010
+ import { existsSync as existsSync3, mkdirSync as mkdirSync13, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
48288
49011
  import { homedir as homedir2 } from "os";
48289
- import { dirname as dirname13, join as join8 } from "path";
49012
+ import { dirname as dirname14, join as join8 } from "path";
48290
49013
 
48291
49014
  // src/version.ts
48292
49015
  import { readFileSync as readFileSync7 } from "fs";
@@ -48333,9 +49056,9 @@ function loadFileCacheSync() {
48333
49056
  }
48334
49057
  function saveFileCache(data) {
48335
49058
  try {
48336
- const dir = dirname13(CACHE_PATH);
49059
+ const dir = dirname14(CACHE_PATH);
48337
49060
  if (!existsSync3(dir))
48338
- mkdirSync12(dir, { recursive: true });
49061
+ mkdirSync13(dir, { recursive: true });
48339
49062
  writeFileSync2(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
48340
49063
  } catch {}
48341
49064
  }
@@ -53929,6 +54652,13 @@ ${lines.join(`
53929
54652
 
53930
54653
  // src/tools/index.ts
53931
54654
  var moduleCatalog2 = [
54655
+ {
54656
+ label: "Home Internet",
54657
+ slug: "home-internet",
54658
+ group: "System & Ops",
54659
+ description: "Plain-language internet diagnosis, household inventory and approved temporary client policies with bounded path comparisons.",
54660
+ tools: homeInternetTools
54661
+ },
53932
54662
  {
53933
54663
  label: "Multi-Router Round Trip",
53934
54664
  slug: "round-trip",