@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.
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();
@@ -17704,6 +17731,14 @@ var REPORT_VIEW_TOOLS = {
17704
17731
  "packet_capture_status"
17705
17732
  ],
17706
17733
  reports: [
17734
+ "diagnose_home_internet",
17735
+ "compare_home_paths",
17736
+ "get_home_internet",
17737
+ "refresh_home_devices",
17738
+ "name_home_device",
17739
+ "preview_home_policy",
17740
+ "apply_home_policy",
17741
+ "undo_home_policy",
17707
17742
  "diagnose",
17708
17743
  "trace_path",
17709
17744
  "correlate_events",
@@ -22475,12 +22510,892 @@ var investigationTools = [
22475
22510
  })
22476
22511
  ];
22477
22512
 
22478
- // src/tools/service-contracts.ts
22479
- import { randomUUID as randomUUID3 } from "crypto";
22513
+ // src/home/model.ts
22514
+ var macInput = string2().regex(/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i);
22515
+ var diagnosisInput = object({
22516
+ client: ipv42(),
22517
+ target: string2().max(253).regex(/^[a-z\d](?:[a-z\d.-]*[a-z\d])?$/i).default("example.com")
22518
+ });
22519
+ var compareInput = object({
22520
+ target: ipv42(),
22521
+ tables: array(string2().min(1).max(64)).min(1).max(3),
22522
+ goal: _enum(["calls", "gaming", "download"]).default("calls")
22523
+ });
22524
+ var policyInput = object({
22525
+ mac: macInput,
22526
+ action: _enum(["pause", "priority", "route"]),
22527
+ minutes: number2().int().min(5).max(120).default(30),
22528
+ startInMinutes: number2().int().min(0).max(1440).default(0),
22529
+ table: string2().min(1).max(64).optional()
22530
+ });
22531
+ function enabled2(row) {
22532
+ return !isYes(row.disabled) && !/[XI]/.test(row.flags ?? "");
22533
+ }
22534
+ function activeRoute(row) {
22535
+ return enabled2(row) && (isYes(row.active) || /A/.test(row.flags ?? ""));
22536
+ }
22537
+ function milliseconds(text) {
22538
+ if (!text)
22539
+ return null;
22540
+ const units = [...text.matchAll(/(\d+(?:\.\d+)?)(us|ms|s)/g)];
22541
+ if (!units.length || units.map((m) => m[0]).join("") !== text)
22542
+ return null;
22543
+ return units.reduce((sum, m) => sum + Number(m[1]) * (m[2] === "s" ? 1000 : m[2] === "us" ? 0.001 : 1), 0);
22544
+ }
22545
+ function pingSample(table, raw) {
22546
+ const sent = Number(raw.match(/sent=(\d+)/)?.[1]);
22547
+ const received = Number(raw.match(/received=(\d+)/)?.[1]);
22548
+ const rtt = (key) => milliseconds(raw.match(new RegExp(`${key}-rtt=([^\\s]+)`))?.[1]);
22549
+ const min = rtt("min"), max = rtt("max");
22550
+ if (!Number.isFinite(sent) || sent < 1 || !Number.isFinite(received) || received > sent)
22551
+ return {
22552
+ table,
22553
+ state: "unknown",
22554
+ loss: null,
22555
+ latency: null,
22556
+ spread: null,
22557
+ note: "No usable ICMP summary. This RouterOS version may not support table-scoped ping."
22558
+ };
22559
+ return {
22560
+ table,
22561
+ state: "observed",
22562
+ loss: (sent - received) * 100 / sent,
22563
+ latency: rtt("avg"),
22564
+ spread: min === null || max === null ? null : Math.max(0, max - min),
22565
+ note: "Five router-originated ICMP probes; RTT range is not a client jitter or throughput measurement."
22566
+ };
22567
+ }
22568
+ function recommendPath(paths, goal) {
22569
+ if (goal === "download")
22570
+ return null;
22571
+ const usable = paths.filter((p) => p.state === "observed" && p.loss !== null && p.loss < 100 && p.latency !== null && p.spread !== null);
22572
+ const score = (p) => p.loss * 1000 + p.latency + p.spread * (goal === "calls" ? 2 : 1);
22573
+ return usable.sort((a, b) => score(a) - score(b))[0]?.table ?? null;
22574
+ }
22575
+ function tagSelector(tag) {
22576
+ return `[find where comment=${quoteValue(tag)}]`;
22577
+ }
22578
+ function temporaryCommands(id, input, ip, setup, activate, revert) {
22579
+ const tag = `mcp-home-${id}`;
22580
+ const clearMarkers = new Cmd(`/ip firewall address-list remove ${tagSelector(tag)}`).build();
22581
+ const clearScheduler = new Cmd(`/system scheduler remove ${tagSelector(tag)}`).build();
22582
+ const undo = [...revert, clearMarkers, clearScheduler];
22583
+ const leaseMatch = `[/ip dhcp-server lease find where mac-address=${quoteValue(input.mac)} address=${quoteValue(ip)} dynamic=no status=bound]`;
22584
+ const expired = `([:len [/ip firewall address-list find where list=${quoteValue(`${tag}-end`)}]] = 0 || [:len ${leaseMatch}] != 1)`;
22585
+ const waiting = `[:len [/ip firewall address-list find where list=${quoteValue(`${tag}-start`)}]] = 0`;
22586
+ const tick = `:if (${expired}) do={ ${undo.join("; ")} } else={ :if (${waiting}) do={ ${activate.join("; ")} } }`;
22587
+ const commands = [
22588
+ ...setup,
22589
+ 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(),
22590
+ ...input.startInMinutes ? [
22591
+ new Cmd("/ip firewall address-list add").set("list", `${tag}-start`).set("address", ip).set("timeout", `${input.startInMinutes}m`).set("comment", tag).build()
22592
+ ] : [],
22593
+ 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(),
22594
+ 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(),
22595
+ ...!input.startInMinutes ? activate : []
22596
+ ];
22597
+ return { commands, undo };
22598
+ }
22599
+
22600
+ // src/home/read.ts
22601
+ async function checkedRead(command, ctx, read = executeMikrotikCommand) {
22602
+ const raw = await read(command, ctx, { maxMs: 8000 });
22603
+ if (looksLikeError(raw) || raw.length > 512000)
22604
+ throw new Error("Router rejected the command or returned too much data; its outcome was not confirmed.");
22605
+ return raw;
22606
+ }
22607
+ async function rows(path, fields, ctx, read = executeMikrotikCommand) {
22608
+ const raw = await checkedRead(new Cmd(`${path} print detail without-paging`).build(), ctx, read);
22609
+ const result = parseRecords(raw).rows;
22610
+ if (!result.length && !isEmpty(raw) && !/^\s*(?:Flags:.*)?\s*$/.test(raw) || result.length > 1000)
22611
+ throw new Error(`Cannot safely interpret ${path}.`);
22612
+ const keys = new Set(["#", "flags", ...fields.split(",")]);
22613
+ return result.map((row) => Object.fromEntries(Object.entries(row).filter(([key]) => keys.has(key))));
22614
+ }
22615
+ async function diagnoseInternet(input, ctx, read = executeMikrotikCommand) {
22616
+ const a = diagnosisInput.parse(input), device = resolveDeviceName(ctx.device);
22617
+ assertDeviceAccess([device], "diagnose_home_internet", "READ");
22618
+ const findings = [];
22619
+ const capture = async (area, work) => {
22620
+ try {
22621
+ findings.push(await work());
22622
+ } catch {
22623
+ findings.push({
22624
+ area,
22625
+ state: "unknown",
22626
+ title: `${area} could not be measured`,
22627
+ detail: "The router query failed or is unsupported. Missing evidence is not a healthy result.",
22628
+ next: "Check permissions and device support, then retry."
22629
+ });
22630
+ }
22631
+ };
22632
+ await capture("Router", async () => {
22633
+ const resource = parseKeyValues(await checkedRead("/system resource print", ctx, read));
22634
+ const cpu = Number(resource["cpu-load"]?.replace("%", ""));
22635
+ const free = parseSize(resource["free-memory"]), total = parseSize(resource["total-memory"]);
22636
+ if (!Number.isFinite(cpu) || !total || free === undefined)
22637
+ throw new Error("No resources");
22638
+ const memory = Math.round((1 - free / total) * 100), hot = cpu >= 85 || memory >= 90;
22639
+ return {
22640
+ area: "Router",
22641
+ state: hot ? "suspected" : "observed",
22642
+ title: hot ? "The router may be under pressure" : "Router resources have headroom in this sample",
22643
+ detail: `CPU ${cpu}% \xB7 memory ${memory}%. One sample does not establish a bottleneck.`,
22644
+ next: "Repeat while the slow download is running; compare with the Devices page."
22645
+ };
22646
+ });
22647
+ await capture("DNS", async () => {
22648
+ const start = Date.now();
22649
+ const resolved = (await checkedRead(`:put [:resolve ${new Cmd("").set("domain-name", a.target).build().trim()}]`, ctx, read)).trim();
22650
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(resolved))
22651
+ throw new Error("Not an IPv4 result");
22652
+ return {
22653
+ area: "DNS",
22654
+ state: "observed",
22655
+ title: "The router resolved this destination",
22656
+ detail: `${a.target} \u2192 ${resolved}. Query plus SSH round trip: ${Date.now() - start} ms (not pure DNS latency).`,
22657
+ next: "If only one device is affected, compare its DNS and secure-DNS settings."
22658
+ };
22659
+ });
22660
+ await capture("Internet", async () => {
22661
+ const result = pingSample("main", await checkedRead(new Cmd("/ping").set("address", a.target).set("count", 5).set("interval", "200ms").build(), ctx, read));
22662
+ if (result.state === "unknown")
22663
+ throw new Error("No ping");
22664
+ return {
22665
+ area: "Internet",
22666
+ state: result.loss > 0 ? "suspected" : "observed",
22667
+ title: result.loss > 0 ? "Some router probes did not return" : "All router probes returned",
22668
+ detail: `${result.loss}% loss \xB7 average RTT ${result.latency ?? "unknown"} ms. ICMP can be deprioritized; this does not locate a failing hop.`,
22669
+ next: "Compare paths below. Router probes do not test the client's firewall path or application."
22670
+ };
22671
+ });
22672
+ await capture("Wi-Fi", async () => {
22673
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,active-address", ctx, read);
22674
+ const mac = leases.find((r) => r.address === a.client || r["active-address"] === a.client)?.["mac-address"];
22675
+ if (!mac)
22676
+ throw new Error("No attachment");
22677
+ let registrations;
22678
+ try {
22679
+ registrations = await rows("/interface wifi registration-table", "mac-address,signal,tx-rate,rx-rate", ctx, read);
22680
+ } catch {
22681
+ registrations = await rows("/interface wireless registration-table", "mac-address,signal-strength,tx-rate,rx-rate", ctx, read);
22682
+ }
22683
+ const entry = registrations.find((r) => r["mac-address"]?.toUpperCase() === mac.toUpperCase());
22684
+ const signal = Number.parseFloat(entry?.signal ?? entry?.["signal-strength"] ?? "");
22685
+ if (!entry || !Number.isFinite(signal))
22686
+ throw new Error("No Wi-Fi measurement");
22687
+ return {
22688
+ area: "Wi-Fi",
22689
+ state: signal < -70 ? "suspected" : "observed",
22690
+ title: signal < -70 ? "Weak Wi-Fi signal may be slowing this device" : "Wi-Fi signal is not weak in this sample",
22691
+ detail: `${signal} dBm \xB7 PHY transmit rate ${entry["tx-rate"] ?? "unknown"}. PHY rate is not download speed.`,
22692
+ next: "Move closer to the access point and compare; interference and airtime remain unmeasured."
22693
+ };
22694
+ });
22695
+ await capture("Bandwidth", async () => {
22696
+ const queues = await rows("/queue simple", "name,target,max-limit,disabled", ctx, read);
22697
+ const matches = queues.filter((q) => enabled2(q) && q.target?.split(",").some((t) => t === a.client || t === `${a.client}/32`));
22698
+ return {
22699
+ area: "Bandwidth",
22700
+ state: matches.length ? "observed" : "unknown",
22701
+ title: matches.length ? "A per-device bandwidth policy exists" : "Available bandwidth has not been measured",
22702
+ 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.",
22703
+ next: "Run an endpoint speed test before and during the problem. These checks do not download test files or change MTU."
22704
+ };
22705
+ });
22706
+ return {
22707
+ device,
22708
+ client: a.client,
22709
+ target: a.target,
22710
+ at: Date.now(),
22711
+ applicationHealth: "unverified",
22712
+ findings
22713
+ };
22714
+ }
22715
+ async function comparePaths(input, ctx, read = executeMikrotikCommand) {
22716
+ const a = compareInput.parse(input), device = resolveDeviceName(ctx.device);
22717
+ assertDeviceAccess([device], "compare_home_paths", "READ");
22718
+ const tables = await rows("/routing table", "name,fib,disabled", ctx, read);
22719
+ const names = [...new Set(a.tables)];
22720
+ if (names.some((name) => !tables.some((t) => t.name === name && enabled2(t) && (t.fib === "yes" || t.fib === "true"))))
22721
+ throw new Error("Choose an existing enabled FIB routing table.");
22722
+ const paths = [];
22723
+ for (const table of names) {
22724
+ try {
22725
+ 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)));
22726
+ } catch {
22727
+ paths.push(pingSample(table, ""));
22728
+ }
22729
+ }
22730
+ return {
22731
+ device,
22732
+ at: Date.now(),
22733
+ target: a.target,
22734
+ goal: a.goal,
22735
+ paths,
22736
+ recommended: recommendPath(paths, a.goal),
22737
+ 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."
22738
+ };
22739
+ }
22480
22740
 
22481
- // src/service-contracts/store.ts
22741
+ // src/home/policies.ts
22742
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
22743
+
22744
+ // src/snapshots/format.ts
22745
+ import { createHash } from "crypto";
22746
+ var TIMESTAMP_HEADER = /^#\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b.*by RouterOS/i;
22747
+ function parseExportMeta(body) {
22748
+ const head = body.slice(0, 600);
22749
+ const version = head.match(/by RouterOS ([^\s#]+)/i)?.[1];
22750
+ const exportedAt = head.match(/#\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1];
22751
+ return { rosVersion: version, exportedAt };
22752
+ }
22753
+ function normalizeExport(body) {
22754
+ return body.replace(/\r\n/g, `
22755
+ `).split(`
22756
+ `).filter((line) => !TIMESTAMP_HEADER.test(line)).join(`
22757
+ `).replace(/\n+$/, "");
22758
+ }
22759
+ function contentSha(normalizedBody) {
22760
+ return createHash("sha256").update(normalizedBody, "utf8").digest("hex").slice(0, 16);
22761
+ }
22762
+ function countLines(body) {
22763
+ const trimmed = body.replace(/\n+$/, "");
22764
+ return trimmed === "" ? 0 : trimmed.split(`
22765
+ `).length;
22766
+ }
22767
+
22768
+ // src/snapshots/store.ts
22482
22769
  import { mkdirSync as mkdirSync4 } from "fs";
22483
22770
  import { dirname as dirname4 } from "path";
22771
+ function rowToBaseline(r) {
22772
+ return {
22773
+ device: r.device,
22774
+ snapshotId: r.snapshot_id,
22775
+ setAt: r.set_at,
22776
+ setBy: r.set_by,
22777
+ label: r.label ?? undefined,
22778
+ notes: r.notes ?? undefined
22779
+ };
22780
+ }
22781
+ function rowToSnapshot(r, body) {
22782
+ return {
22783
+ id: r.id,
22784
+ device: r.device,
22785
+ ts: r.ts,
22786
+ label: r.label ?? undefined,
22787
+ rosVersion: r.ros_version ?? undefined,
22788
+ body,
22789
+ bytes: r.bytes,
22790
+ lines: r.lines,
22791
+ sha: r.sha
22792
+ };
22793
+ }
22794
+ var SCHEMA_STATEMENTS3 = [
22795
+ `CREATE TABLE IF NOT EXISTS snapshots (
22796
+ id TEXT PRIMARY KEY,
22797
+ device TEXT NOT NULL,
22798
+ ts INTEGER NOT NULL,
22799
+ label TEXT,
22800
+ ros_version TEXT,
22801
+ body TEXT NOT NULL,
22802
+ bytes INTEGER NOT NULL,
22803
+ lines INTEGER NOT NULL,
22804
+ sha TEXT NOT NULL
22805
+ )`,
22806
+ "CREATE INDEX IF NOT EXISTS idx_snapshots_device_ts ON snapshots(device, ts)",
22807
+ `CREATE TABLE IF NOT EXISTS baselines (
22808
+ device TEXT PRIMARY KEY,
22809
+ snapshot_id TEXT NOT NULL,
22810
+ set_at INTEGER NOT NULL,
22811
+ set_by TEXT NOT NULL DEFAULT 'agent',
22812
+ label TEXT,
22813
+ notes TEXT
22814
+ )`
22815
+ ];
22816
+
22817
+ class SqliteSnapshotStore {
22818
+ db;
22819
+ constructor(db) {
22820
+ this.db = db;
22821
+ db.run("PRAGMA journal_mode = WAL");
22822
+ db.run("PRAGMA synchronous = NORMAL");
22823
+ for (const stmt of SCHEMA_STATEMENTS3)
22824
+ db.run(stmt);
22825
+ }
22826
+ insert(s) {
22827
+ this.db.query(`INSERT OR REPLACE INTO snapshots
22828
+ (id, device, ts, label, ros_version, body, bytes, lines, sha)
22829
+ VALUES ($id,$device,$ts,$label,$ver,$body,$bytes,$lines,$sha)`).run({
22830
+ $id: s.id,
22831
+ $device: s.device,
22832
+ $ts: s.ts,
22833
+ $label: s.label ?? null,
22834
+ $ver: s.rosVersion ?? null,
22835
+ $body: s.body,
22836
+ $bytes: s.bytes,
22837
+ $lines: s.lines,
22838
+ $sha: s.sha
22839
+ });
22840
+ }
22841
+ get(id) {
22842
+ const row = this.db.query("SELECT * FROM snapshots WHERE id = $id").get({ $id: id });
22843
+ return row ? rowToSnapshot(row, row.body) : null;
22844
+ }
22845
+ latest(device) {
22846
+ const row = this.db.query("SELECT * FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT 1").get({ $d: device });
22847
+ return row ? rowToSnapshot(row, row.body) : null;
22848
+ }
22849
+ list(device, limit = 50, withBody = false) {
22850
+ const cols = withBody ? "*" : "id, device, ts, label, ros_version, bytes, lines, sha";
22851
+ const n = Math.min(Math.max(limit, 1), 500);
22852
+ const rows = this.db.query(`SELECT ${cols} FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT $n`).all({ $d: device, $n: n });
22853
+ return rows.map((r) => rowToSnapshot(r, withBody ? r.body : ""));
22854
+ }
22855
+ count(device) {
22856
+ const r = this.db.query("SELECT COUNT(*) AS n FROM snapshots WHERE device = $d").get({ $d: device });
22857
+ return r.n;
22858
+ }
22859
+ delete(ids) {
22860
+ if (ids.length === 0)
22861
+ return 0;
22862
+ const placeholders = ids.map((_, j) => `$id${j}`).join(",");
22863
+ const params = {};
22864
+ ids.forEach((id, j) => {
22865
+ params[`$id${j}`] = id;
22866
+ });
22867
+ const res = this.db.query(`DELETE FROM snapshots WHERE id IN (${placeholders})`).run(params);
22868
+ return Number(res.changes ?? 0);
22869
+ }
22870
+ setBaseline(device, snapshotId, setBy = "agent", label, notes) {
22871
+ this.db.query(`INSERT OR REPLACE INTO baselines (device, snapshot_id, set_at, set_by, label, notes)
22872
+ VALUES ($device, $snapId, $setAt, $setBy, $label, $notes)`).run({
22873
+ $device: device,
22874
+ $snapId: snapshotId,
22875
+ $setAt: Date.now(),
22876
+ $setBy: setBy,
22877
+ $label: label ?? null,
22878
+ $notes: notes ?? null
22879
+ });
22880
+ }
22881
+ getBaseline(device) {
22882
+ const row = this.db.query("SELECT * FROM baselines WHERE device = $d").get({ $d: device });
22883
+ return row ? rowToBaseline(row) : null;
22884
+ }
22885
+ removeBaseline(device) {
22886
+ const res = this.db.query("DELETE FROM baselines WHERE device = $d").run({ $d: device });
22887
+ return (res.changes ?? 0) > 0;
22888
+ }
22889
+ listBaselines() {
22890
+ const rows = this.db.query("SELECT * FROM baselines ORDER BY set_at DESC").all();
22891
+ return rows.map(rowToBaseline);
22892
+ }
22893
+ close() {
22894
+ this.db.close();
22895
+ }
22896
+ }
22897
+ async function openSnapshotStore(path) {
22898
+ if (path !== ":memory:") {
22899
+ try {
22900
+ mkdirSync4(dirname4(path), { recursive: true });
22901
+ } catch {}
22902
+ }
22903
+ const { Database } = await import("bun:sqlite");
22904
+ const db = new Database(path, { create: true });
22905
+ return new SqliteSnapshotStore(db);
22906
+ }
22907
+
22908
+ // src/snapshots/capture.ts
22909
+ var storePromise3 = null;
22910
+ function snapshots() {
22911
+ if (!storePromise3)
22912
+ storePromise3 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
22913
+ return storePromise3;
22914
+ }
22915
+ async function captureSnapshot(ctx, label, requireExport = false) {
22916
+ const device = resolveDeviceName(ctx.device);
22917
+ const body = await executeMikrotikCommand("/export terse", ctx);
22918
+ if (requireExport && (looksLikeError(body) || !/^\/[a-z]/m.test(body) || /#\s*error exporting/i.test(body)))
22919
+ throw new Error("A complete pre-change configuration export could not be captured; no policy was applied.");
22920
+ const meta = parseExportMeta(body);
22921
+ const sha = contentSha(normalizeExport(body));
22922
+ const ts = Date.now();
22923
+ const snap = {
22924
+ id: `snap_${ts}_${sha.slice(0, 8)}`,
22925
+ device,
22926
+ ts,
22927
+ label,
22928
+ rosVersion: meta.rosVersion,
22929
+ body,
22930
+ bytes: Buffer.byteLength(body, "utf8"),
22931
+ lines: countLines(body),
22932
+ sha
22933
+ };
22934
+ (await snapshots()).insert(snap);
22935
+ return snap.id;
22936
+ }
22937
+
22938
+ // src/home/store.ts
22939
+ import { mkdirSync as mkdirSync5 } from "fs";
22940
+ import { dirname as dirname5 } from "path";
22941
+ class HomeStore {
22942
+ db;
22943
+ constructor(db) {
22944
+ this.db = db;
22945
+ 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))");
22946
+ 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)");
22947
+ 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')");
22948
+ }
22949
+ clients(device) {
22950
+ return this.db.query("SELECT body FROM home_clients WHERE device=?").all(device).map((r) => JSON.parse(r.body));
22951
+ }
22952
+ saveClient(device, client) {
22953
+ 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));
22954
+ }
22955
+ savePlan(plan) {
22956
+ 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));
22957
+ }
22958
+ plan(id, device) {
22959
+ const row = this.db.query("SELECT body FROM home_plans WHERE id=? AND device=?").get(id, device);
22960
+ return row ? JSON.parse(row.body) : undefined;
22961
+ }
22962
+ claim(plan) {
22963
+ 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());
22964
+ if (result.changes !== 1)
22965
+ throw new Error("Preview expired or was already claimed by another process.");
22966
+ }
22967
+ unresolved(device) {
22968
+ 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));
22969
+ }
22970
+ plans(device) {
22971
+ 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));
22972
+ return [
22973
+ ...new Map([...recent, ...this.unresolved(device)].map((p) => [p.id, p])).values()
22974
+ ].sort((a, b) => b.createdAt - a.createdAt);
22975
+ }
22976
+ }
22977
+ var pending2;
22978
+ function homeStore() {
22979
+ return pending2 ??= (async () => {
22980
+ mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
22981
+ const { Database } = await import("bun:sqlite");
22982
+ const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
22983
+ db.run("PRAGMA journal_mode=WAL");
22984
+ db.run("PRAGMA busy_timeout=5000");
22985
+ return new HomeStore(db);
22986
+ })().catch((e) => {
22987
+ pending2 = undefined;
22988
+ throw e;
22989
+ });
22990
+ }
22991
+
22992
+ // src/home/policies.ts
22993
+ function buildPolicy(id, input, facts) {
22994
+ input = { ...input, mac: input.mac.toUpperCase() };
22995
+ if (!isYes(facts.deviceMode.scheduler))
22996
+ throw new Error("Router device-mode must explicitly allow scheduler execution for automatic expiry.");
22997
+ const candidates = facts.leases.filter((l) => l["mac-address"]?.toUpperCase() === input.mac);
22998
+ const lease = candidates[0];
22999
+ if (candidates.length !== 1 || !lease || isYes(lease.dynamic) || /D/.test(lease.flags ?? "") || !enabled2(lease) || lease.status !== "bound" || !lease.address)
23000
+ throw new Error("This control requires exactly one bound, static DHCP lease. Pin the client's IP in Clients first.");
23001
+ if (facts.leases.some((l) => l !== lease && (l.address === lease.address || l["active-address"] === lease.address)))
23002
+ throw new Error("The client IP is ambiguous.");
23003
+ if (lease["active-address"] && lease["active-address"] !== lease.address)
23004
+ throw new Error("The client lease changed; reconnect it before continuing.");
23005
+ if (lease["active-mac-address"] && lease["active-mac-address"].toUpperCase() !== input.mac)
23006
+ throw new Error("The active client MAC does not match its reservation.");
23007
+ if (facts.addresses.some((r) => r.address?.split("/")[0] === lease.address))
23008
+ throw new Error("Cannot target a router address.");
23009
+ if (facts.filters.some((r) => enabled2(r) && r.action === "fasttrack-connection") || facts.connections.some((r) => isYes(r.fasttrack) || /F/.test(r.flags ?? "")))
23010
+ 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.");
23011
+ if (input.action === "pause" && !isYes(facts.ipv6["disable-ipv6"]) && facts.ipv6.forward !== "no" && facts.ipv6.forward !== "false")
23012
+ throw new Error("IPv6 forwarding is enabled or unknown. An IPv4-only pause could be bypassed; use a dual-stack policy instead.");
23013
+ const tag = `mcp-home-${id}`, ip = lease.address;
23014
+ const setup = [], activate = [], revert = [];
23015
+ let queueBefore;
23016
+ const warnings = [
23017
+ "Only this reserved IPv4 client is targeted. Other configuration is left in place.",
23018
+ "The router expires this policy even when the dashboard is closed. Scheduler cleanup can take up to 30 seconds. Reboot ends the policy.",
23019
+ "Existing connections may disconnect. Review before applying; this is not a speed guarantee."
23020
+ ];
23021
+ const manage = (path) => {
23022
+ activate.push(new Cmd(`${path} enable ${tagSelector(tag)}`).build());
23023
+ revert.push(new Cmd(`${path} remove ${tagSelector(tag)}`).build());
23024
+ };
23025
+ if (input.action === "pause") {
23026
+ for (const direction of ["src", "dst"])
23027
+ 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());
23028
+ manage("/ip firewall filter");
23029
+ warnings.push("Pauses all routed traffic for this IP, including routed LAN traffic; router management and same-bridge traffic are not blocked.");
23030
+ } else if (input.action === "route") {
23031
+ 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)))
23032
+ throw new Error("Select an enabled FIB table with an active default route. This feature does not create WANs or VPNs.");
23033
+ if (facts.mangle.some((r) => enabled2(r) && r.action === "mark-routing"))
23034
+ throw new Error("Existing routing marks require an administrator review; this control will not override them.");
23035
+ const exclusions = new Set([
23036
+ "10.0.0.0/8",
23037
+ "172.16.0.0/12",
23038
+ "192.168.0.0/16",
23039
+ "100.64.0.0/10",
23040
+ "127.0.0.0/8",
23041
+ "169.254.0.0/16",
23042
+ "224.0.0.0/4",
23043
+ "255.255.255.255"
23044
+ ]);
23045
+ for (const a of facts.addresses)
23046
+ if (a.address)
23047
+ exclusions.add(a.address);
23048
+ for (const prefix of exclusions)
23049
+ setup.push(new Cmd("/ip firewall address-list add").set("list", `${tag}-local`).set("address", prefix).set("comment", tag).build());
23050
+ 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());
23051
+ manage("/ip firewall mangle");
23052
+ 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.");
23053
+ } else {
23054
+ const queues = facts.queues.filter((q) => q.target === `${ip}/32` && enabled2(q));
23055
+ const q = queues[0], parent = facts.queues.find((r) => r.name === q?.parent && enabled2(r));
23056
+ 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 ?? ""))
23057
+ 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.");
23058
+ if (facts.queues.some((r) => r.parent === q.name))
23059
+ throw new Error("Only leaf queues can receive meeting priority.");
23060
+ if (q.priority === "1/1")
23061
+ throw new Error("This client already has the highest queue priority.");
23062
+ queueBefore = { name: q.name, target: q.target, parent: q.parent, priority: q.priority };
23063
+ const selector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority=${quoteValue(q.priority)}]`;
23064
+ activate.push(new Cmd(`/queue simple set ${selector}`).set("priority", "1/1").build());
23065
+ const restoreSelector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority="1/1"]`;
23066
+ revert.push(new Cmd(`/queue simple set ${restoreSelector}`).set("priority", q.priority).build());
23067
+ 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.");
23068
+ }
23069
+ const generated = temporaryCommands(id, input, ip, setup, activate, revert);
23070
+ if (generated.commands.length > 40)
23071
+ throw new Error("This router needs too many policy objects for a bounded Safe Mode change. Ask an administrator to review it.");
23072
+ const stable = JSON.stringify(facts, (key, value) => key === "#" ? undefined : value);
23073
+ return {
23074
+ ip,
23075
+ ...generated,
23076
+ warnings,
23077
+ queueBefore,
23078
+ fingerprint: createHash2("sha256").update(stable).digest("hex")
23079
+ };
23080
+ }
23081
+ async function policyFacts(ctx, read = executeMikrotikCommand) {
23082
+ const fasttrackCount = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx, read)).trim();
23083
+ if (!/^\d+$/.test(fasttrackCount))
23084
+ throw new Error("Cannot establish whether FastTrack connections remain active.");
23085
+ return {
23086
+ leases: await rows("/ip dhcp-server lease", "address,active-address,mac-address,active-mac-address,dynamic,disabled,status", ctx, read),
23087
+ filters: await rows("/ip firewall filter", "chain,action,disabled,comment", ctx, read),
23088
+ connections: Number(fasttrackCount) > 0 ? [{ fasttrack: "yes" }] : [],
23089
+ mangle: await rows("/ip firewall mangle", "chain,action,disabled,comment", ctx, read),
23090
+ queues: await rows("/queue simple", "name,target,parent,priority,max-limit,packet-marks,disabled", ctx, read),
23091
+ tables: await rows("/routing table", "name,fib,disabled", ctx, read),
23092
+ routes: await rows("/ip route", "dst-address,routing-table,active,disabled,gateway", ctx, read),
23093
+ addresses: await rows("/ip address", "address,interface", ctx, read),
23094
+ ipv6: parseKeyValues(await checkedRead("/ipv6 settings print", ctx, read)),
23095
+ deviceMode: parseKeyValues(await checkedRead("/system device-mode print", ctx, read))
23096
+ };
23097
+ }
23098
+ var busy3 = new Set;
23099
+ async function exclusive(device, work) {
23100
+ if (busy3.has(device))
23101
+ throw new Error("Another Home Internet operation is in progress for this router.");
23102
+ busy3.add(device);
23103
+ try {
23104
+ return await work();
23105
+ } finally {
23106
+ busy3.delete(device);
23107
+ }
23108
+ }
23109
+ async function previewPolicy(input, ctx) {
23110
+ const a = policyInput.parse(input), device = resolveDeviceName(ctx.device);
23111
+ a.mac = a.mac.toUpperCase();
23112
+ assertDeviceAccess([device], "preview_home_policy", "WRITE");
23113
+ return exclusive(device, async () => {
23114
+ const id = randomUUID2();
23115
+ const plan = {
23116
+ id,
23117
+ device,
23118
+ input: a,
23119
+ createdAt: Date.now(),
23120
+ previewExpiresAt: Date.now() + 300000,
23121
+ status: "preview",
23122
+ ...buildPolicy(id, a, await policyFacts(ctx))
23123
+ };
23124
+ (await homeStore()).savePlan(plan);
23125
+ return plan;
23126
+ });
23127
+ }
23128
+ async function applyPolicy(id, confirm, ctx) {
23129
+ const device = resolveDeviceName(ctx.device);
23130
+ assertDeviceAccess([device], "apply_home_policy", "WRITE");
23131
+ if (!confirm)
23132
+ throw new Error("Review the preview and explicitly confirm before applying.");
23133
+ return exclusive(device, async () => {
23134
+ const store = await homeStore(), plan = store.plan(id, device);
23135
+ if (!plan || plan.status !== "preview" || plan.previewExpiresAt < Date.now())
23136
+ throw new Error("Preview expired, already used, or belongs to another router.");
23137
+ if (store.unresolved(device).some((p) => p.input.mac === plan.input.mac && ["applying", "scheduled", "active", "uncertain"].includes(p.status)))
23138
+ throw new Error("Undo or reconcile the previous policy for this device first.");
23139
+ const fresh = buildPolicy(id, plan.input, await policyFacts(ctx));
23140
+ if (fresh.fingerprint !== plan.fingerprint)
23141
+ throw new Error("Router state changed after the preview. Create a fresh preview.");
23142
+ const safe = getSafeModeManager(device);
23143
+ if (safe.isActive)
23144
+ throw new Error("An existing Safe Mode session is active; finish it before applying a Home Internet policy.");
23145
+ plan.snapshot = await captureSnapshot(ctx, `Before Home Internet ${plan.input.action}`, true);
23146
+ plan.status = "applying";
23147
+ store.claim(plan);
23148
+ let owned = false;
23149
+ try {
23150
+ const status = await safe.enable();
23151
+ if (!status.startsWith("Safe mode ENABLED"))
23152
+ throw new Error("Could not acquire a new Safe Mode session.");
23153
+ owned = true;
23154
+ const lockedFacts = await policyFacts(ctx);
23155
+ if (buildPolicy(id, plan.input, lockedFacts).fingerprint !== plan.fingerprint)
23156
+ throw new Error("Configuration changed while acquiring Safe Mode; create a new preview.");
23157
+ const started = Date.now();
23158
+ for (const command of plan.commands) {
23159
+ if (Date.now() - started > 120000)
23160
+ throw new Error("Policy apply exceeded its time budget.");
23161
+ await checkedRead(command, ctx);
23162
+ }
23163
+ const tag = `mcp-home-${id}`;
23164
+ const count = (await checkedRead(new Cmd("/system scheduler print count-only").raw(`where comment=${quoteValue(tag)}`).build(), ctx)).trim();
23165
+ if (count !== "2")
23166
+ throw new Error("Router-side expiry could not be verified.");
23167
+ const parsed = (await checkedRead(`:put [:typeof [:parse [/system scheduler get [find where name=${quoteValue(tag)}] on-event]]]`, ctx)).trim();
23168
+ if (parsed !== "code")
23169
+ throw new Error("Router could not compile the expiry script.");
23170
+ await verifyPolicyObjects(plan, lockedFacts, ctx);
23171
+ await checkedRead("/system identity print", ctx);
23172
+ const outcome = await safe.commit();
23173
+ if (!outcome.ok)
23174
+ throw new Error("Commit outcome is uncertain; inspect the router before retrying.");
23175
+ owned = false;
23176
+ plan.startsAt = started + plan.input.startInMinutes * 60000;
23177
+ plan.endsAt = plan.startsAt + plan.input.minutes * 60000;
23178
+ plan.status = plan.input.startInMinutes ? "scheduled" : "active";
23179
+ store.savePlan(plan);
23180
+ return plan;
23181
+ } catch (error) {
23182
+ if (owned)
23183
+ await safe.rollback().catch(() => {});
23184
+ plan.status = "uncertain";
23185
+ plan.error = error instanceof Error ? error.message : "Policy operation failed";
23186
+ store.savePlan(plan);
23187
+ throw new Error(`Policy not confirmed: ${plan.error}. Inspect/undo policy ${id}; do not blindly retry.`);
23188
+ }
23189
+ });
23190
+ }
23191
+ async function undoPolicy(id, confirm, ctx) {
23192
+ const device = resolveDeviceName(ctx.device);
23193
+ assertDeviceAccess([device], "undo_home_policy", "WRITE");
23194
+ if (!confirm)
23195
+ throw new Error("Explicit confirmation is required to undo a policy.");
23196
+ return exclusive(device, async () => {
23197
+ const store = await homeStore(), plan = store.plan(id, device);
23198
+ if (!plan || plan.status === "preview")
23199
+ throw new Error("No applied policy on this router.");
23200
+ if (plan.status === "undone")
23201
+ return plan;
23202
+ const safe = getSafeModeManager(device);
23203
+ if (safe.isActive)
23204
+ throw new Error("Finish the active Safe Mode session first.");
23205
+ const status = await safe.enable();
23206
+ if (!status.startsWith("Safe mode ENABLED"))
23207
+ throw new Error("Could not acquire Safe Mode.");
23208
+ try {
23209
+ await checkedRead(new Cmd(`/system scheduler disable ${tagSelector(`mcp-home-${id}`)}`).build(), ctx);
23210
+ for (const cmd of plan.undo)
23211
+ await checkedRead(cmd, ctx);
23212
+ if (plan.input.action === "priority") {
23213
+ const expected = plan.queueBefore;
23214
+ if (!expected)
23215
+ throw new Error("Missing queue restoration evidence; reconcile this policy manually.");
23216
+ const current = await rows("/queue simple", "name,target,parent,priority", ctx);
23217
+ const matching = current.filter((q) => q.name === expected.name && q.target === expected.target && q.parent === expected.parent);
23218
+ if (matching.length !== 1 || matching[0].priority !== expected.priority)
23219
+ throw new Error("Queue restoration was not verified. External queue changes require manual reconciliation.");
23220
+ }
23221
+ for (const path of [
23222
+ "/system scheduler",
23223
+ "/ip firewall address-list",
23224
+ "/ip firewall filter",
23225
+ "/ip firewall mangle"
23226
+ ]) {
23227
+ const remaining = (await checkedRead(new Cmd(`${path} print count-only`).raw(`where comment=${quoteValue(`mcp-home-${id}`)}`).build(), ctx)).trim();
23228
+ if (remaining !== "0")
23229
+ throw new Error("Policy cleanup could not be verified; the undo was not committed.");
23230
+ }
23231
+ const committed = await safe.commit();
23232
+ if (!committed.ok)
23233
+ throw new Error("Undo commit could not be confirmed");
23234
+ plan.status = "undone";
23235
+ store.savePlan(plan);
23236
+ return plan;
23237
+ } catch (e) {
23238
+ await safe.rollback().catch(() => {});
23239
+ throw e;
23240
+ }
23241
+ });
23242
+ }
23243
+ async function verifyPolicyObjects(plan, before, ctx) {
23244
+ const tag = `mcp-home-${plan.id}`;
23245
+ const marker = (await checkedRead(new Cmd("/ip firewall address-list print count-only").raw(`where list=${quoteValue(`${tag}-end`)}`).build(), ctx)).trim();
23246
+ if (marker !== "1")
23247
+ throw new Error("Expiry marker could not be verified.");
23248
+ if (plan.input.action === "priority") {
23249
+ const old = before.queues.find((q) => q.target === `${plan.ip}/32` && enabled2(q));
23250
+ const current = await rows("/queue simple", "name,target,parent,priority,max-limit,disabled", ctx);
23251
+ const q = current.find((r) => r.name === old.name && r.target === old.target && r.parent === old.parent);
23252
+ if (!q || q.priority !== (plan.input.startInMinutes ? old.priority : "1/1"))
23253
+ throw new Error("Meeting queue priority was not verified.");
23254
+ } else {
23255
+ const path = plan.input.action === "pause" ? "/ip firewall filter" : "/ip firewall mangle";
23256
+ 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);
23257
+ const owned = current.filter((r) => r.comment === tag);
23258
+ if (owned.length !== (plan.input.action === "pause" ? 2 : 1) || owned.some((r) => enabled2(r) === plan.input.startInMinutes > 0))
23259
+ throw new Error("Policy rules were not verified in their expected state.");
23260
+ if (plan.input.action === "pause") {
23261
+ 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)
23262
+ throw new Error("Pause rule targeting could not be verified.");
23263
+ } 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`)) {
23264
+ throw new Error("Path selection targeting could not be verified.");
23265
+ }
23266
+ }
23267
+ }
23268
+
23269
+ // src/tools/home-internet.ts
23270
+ var homeInternetTools = [
23271
+ defineTool({
23272
+ name: "diagnose_home_internet",
23273
+ title: "Why Is My Internet Slow?",
23274
+ annotations: READ,
23275
+ 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.",
23276
+ inputSchema: diagnosisInput.shape,
23277
+ handler: async (a, ctx) => JSON.stringify(await diagnoseInternet(a, ctx))
23278
+ }),
23279
+ defineTool({
23280
+ name: "compare_home_paths",
23281
+ title: "Compare Internet Paths",
23282
+ annotations: READ,
23283
+ 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.",
23284
+ inputSchema: compareInput.shape,
23285
+ handler: async (a, ctx) => JSON.stringify(await comparePaths(a, ctx))
23286
+ }),
23287
+ defineTool({
23288
+ name: "get_home_internet",
23289
+ title: "Read Household Internet Workspace",
23290
+ annotations: READ,
23291
+ 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.",
23292
+ inputSchema: {},
23293
+ async handler(_a, ctx) {
23294
+ const device = resolveDeviceName(ctx.device);
23295
+ assertDeviceAccess([device], "get_home_internet", "READ");
23296
+ const store = await homeStore();
23297
+ return JSON.stringify({
23298
+ device,
23299
+ clients: store.clients(device),
23300
+ policies: store.plans(device),
23301
+ statusNote: "Saved status only. A passed expiry time is not a verified cleanup result; Undo can reconcile owned objects."
23302
+ });
23303
+ }
23304
+ }),
23305
+ defineTool({
23306
+ name: "refresh_home_devices",
23307
+ title: "Discover Household Devices",
23308
+ annotations: WRITE,
23309
+ 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.",
23310
+ inputSchema: {},
23311
+ async handler(_a, ctx) {
23312
+ const device = resolveDeviceName(ctx.device);
23313
+ assertDeviceAccess([device], "refresh_home_devices", "WRITE");
23314
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,host-name,status", ctx);
23315
+ const tables = await rows("/routing table", "name,fib,disabled", ctx);
23316
+ const store = await homeStore(), old = store.clients(device), now = Date.now();
23317
+ const seen = new Set;
23318
+ for (const r of leases) {
23319
+ const parsed = macInput.safeParse(r["mac-address"]);
23320
+ if (!parsed.success)
23321
+ continue;
23322
+ const mac = parsed.data.toUpperCase(), prior = old.find((c) => c.mac === mac);
23323
+ seen.add(mac);
23324
+ store.saveClient(device, {
23325
+ mac,
23326
+ ip: r.address ?? "",
23327
+ hostname: r["host-name"] ?? "",
23328
+ name: prior?.name ?? "",
23329
+ person: prior?.person ?? "",
23330
+ firstSeen: prior?.firstSeen ?? now,
23331
+ lastSeen: now,
23332
+ acknowledged: prior?.acknowledged ?? old.length === 0,
23333
+ present: r.status === "bound"
23334
+ });
23335
+ }
23336
+ for (const client of old)
23337
+ if (!seen.has(client.mac))
23338
+ store.saveClient(device, { ...client, present: false });
23339
+ return JSON.stringify({
23340
+ device,
23341
+ clients: store.clients(device),
23342
+ tables: tables.filter((t) => enabled2(t) && ["yes", "true"].includes(t.fib)).map((t) => t.name)
23343
+ });
23344
+ }
23345
+ }),
23346
+ defineTool({
23347
+ name: "name_home_device",
23348
+ title: "Name a Household Device",
23349
+ annotations: WRITE,
23350
+ 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.",
23351
+ inputSchema: {
23352
+ mac: macInput,
23353
+ name: string2().trim().max(80),
23354
+ person: string2().trim().max(80).default("")
23355
+ },
23356
+ async handler(a, ctx) {
23357
+ const device = resolveDeviceName(ctx.device);
23358
+ assertDeviceAccess([device], "name_home_device", "WRITE");
23359
+ const store = await homeStore(), client = store.clients(device).find((c) => c.mac === a.mac.toUpperCase());
23360
+ if (!client)
23361
+ throw new Error("Refresh household devices first.");
23362
+ const result = { ...client, name: a.name, person: a.person, acknowledged: true };
23363
+ store.saveClient(device, result);
23364
+ return JSON.stringify(result);
23365
+ }
23366
+ }),
23367
+ defineTool({
23368
+ name: "preview_home_policy",
23369
+ title: "Preview a Temporary Household Policy",
23370
+ annotations: WRITE,
23371
+ 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.",
23372
+ inputSchema: policyInput.shape,
23373
+ handler: async (a, ctx) => JSON.stringify(await previewPolicy(a, ctx))
23374
+ }),
23375
+ defineTool({
23376
+ name: "apply_home_policy",
23377
+ title: "Apply an Approved Household Policy",
23378
+ annotations: WRITE,
23379
+ 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.",
23380
+ inputSchema: { id: uuid2(), confirm: boolean2().default(false) },
23381
+ handler: async (a, ctx) => JSON.stringify(await applyPolicy(a.id, a.confirm, ctx))
23382
+ }),
23383
+ defineTool({
23384
+ name: "undo_home_policy",
23385
+ title: "Undo a Household Policy",
23386
+ annotations: WRITE,
23387
+ 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.",
23388
+ inputSchema: { id: uuid2(), confirm: boolean2().default(false) },
23389
+ handler: async (a, ctx) => JSON.stringify(await undoPolicy(a.id, a.confirm, ctx))
23390
+ })
23391
+ ];
23392
+
23393
+ // src/tools/service-contracts.ts
23394
+ import { randomUUID as randomUUID4 } from "crypto";
23395
+
23396
+ // src/service-contracts/store.ts
23397
+ import { mkdirSync as mkdirSync6 } from "fs";
23398
+ import { dirname as dirname6 } from "path";
22484
23399
  class ContractStore {
22485
23400
  db;
22486
23401
  constructor(db) {
@@ -22506,23 +23421,23 @@ class ContractStore {
22506
23421
  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));
22507
23422
  }
22508
23423
  }
22509
- var pending2;
23424
+ var pending3;
22510
23425
  function contractStore() {
22511
- pending2 ??= (async () => {
22512
- mkdirSync4(dirname4(DEFAULT_SNAPSHOT_DB), { recursive: true });
23426
+ pending3 ??= (async () => {
23427
+ mkdirSync6(dirname6(DEFAULT_SNAPSHOT_DB), { recursive: true });
22513
23428
  const { Database } = await import("bun:sqlite");
22514
23429
  const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
22515
23430
  db.run("PRAGMA journal_mode = WAL");
22516
23431
  return new ContractStore(db);
22517
23432
  })().catch((e) => {
22518
- pending2 = undefined;
23433
+ pending3 = undefined;
22519
23434
  throw e;
22520
23435
  });
22521
- return pending2;
23436
+ return pending3;
22522
23437
  }
22523
23438
 
22524
23439
  // src/service-contracts/run.ts
22525
- import { randomUUID as randomUUID2 } from "crypto";
23440
+ import { randomUUID as randomUUID3 } from "crypto";
22526
23441
 
22527
23442
  // src/policy/parse.ts
22528
23443
  function normalizeSection(path) {
@@ -23829,8 +24744,8 @@ function diffTraces(before, after) {
23829
24744
  }
23830
24745
 
23831
24746
  // src/sim/suites.ts
23832
- import { mkdirSync as mkdirSync5 } from "fs";
23833
- import { dirname as dirname5 } from "path";
24747
+ import { mkdirSync as mkdirSync7 } from "fs";
24748
+ import { dirname as dirname7 } from "path";
23834
24749
  var SCHEMA2 = [
23835
24750
  `CREATE TABLE IF NOT EXISTS sim_suites (
23836
24751
  id TEXT PRIMARY KEY,
@@ -23876,16 +24791,16 @@ class SqliteSuiteStore {
23876
24791
  });
23877
24792
  }
23878
24793
  }
23879
- var storePromise3 = null;
24794
+ var storePromise4 = null;
23880
24795
  async function store2() {
23881
- storePromise3 ??= (async () => {
24796
+ storePromise4 ??= (async () => {
23882
24797
  try {
23883
- mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
24798
+ mkdirSync7(dirname7(DEFAULT_SNAPSHOT_DB), { recursive: true });
23884
24799
  } catch {}
23885
24800
  const { Database } = await import("bun:sqlite");
23886
24801
  return new SqliteSuiteStore(new Database(DEFAULT_SNAPSHOT_DB, { create: true }));
23887
24802
  })();
23888
- return storePromise3;
24803
+ return storePromise4;
23889
24804
  }
23890
24805
  async function listSuites() {
23891
24806
  try {
@@ -23917,30 +24832,6 @@ async function saveSuite(input) {
23917
24832
  return suite;
23918
24833
  }
23919
24834
 
23920
- // src/snapshots/format.ts
23921
- import { createHash } from "crypto";
23922
- var TIMESTAMP_HEADER = /^#\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b.*by RouterOS/i;
23923
- function parseExportMeta(body) {
23924
- const head = body.slice(0, 600);
23925
- const version = head.match(/by RouterOS ([^\s#]+)/i)?.[1];
23926
- const exportedAt = head.match(/#\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1];
23927
- return { rosVersion: version, exportedAt };
23928
- }
23929
- function normalizeExport(body) {
23930
- return body.replace(/\r\n/g, `
23931
- `).split(`
23932
- `).filter((line) => !TIMESTAMP_HEADER.test(line)).join(`
23933
- `).replace(/\n+$/, "");
23934
- }
23935
- function contentSha(normalizedBody) {
23936
- return createHash("sha256").update(normalizedBody, "utf8").digest("hex").slice(0, 16);
23937
- }
23938
- function countLines(body) {
23939
- const trimmed = body.replace(/\n+$/, "");
23940
- return trimmed === "" ? 0 : trimmed.split(`
23941
- `).length;
23942
- }
23943
-
23944
24835
  // src/service-contracts/probe.ts
23945
24836
  import { Resolver } from "dns/promises";
23946
24837
  import { connect, isIP } from "net";
@@ -24103,7 +24994,7 @@ async function evaluateContract(contract, io, simulationExport) {
24103
24994
  }
24104
24995
  }
24105
24996
  return {
24106
- id: randomUUID2(),
24997
+ id: randomUUID3(),
24107
24998
  contractId: contract.id,
24108
24999
  device: contract.device,
24109
25000
  startedAt,
@@ -24228,7 +25119,7 @@ var serviceContractTools = [
24228
25119
  const args = contractInput.parse(a);
24229
25120
  if (args.checks.some((c) => !getConfig().serviceProbes.targets[c.target]))
24230
25121
  throw new Error("Contract references an unapproved target. Ask the administrator to configure it.");
24231
- const contract = { ...args, id: randomUUID3(), device, createdAt: Date.now() };
25122
+ const contract = { ...args, id: randomUUID4(), device, createdAt: Date.now() };
24232
25123
  (await contractStore()).save(contract);
24233
25124
  return JSON.stringify(contract);
24234
25125
  }
@@ -24272,146 +25163,6 @@ var serviceContractTools = [
24272
25163
  })
24273
25164
  ];
24274
25165
 
24275
- // src/snapshots/store.ts
24276
- import { mkdirSync as mkdirSync6 } from "fs";
24277
- import { dirname as dirname6 } from "path";
24278
- function rowToBaseline(r) {
24279
- return {
24280
- device: r.device,
24281
- snapshotId: r.snapshot_id,
24282
- setAt: r.set_at,
24283
- setBy: r.set_by,
24284
- label: r.label ?? undefined,
24285
- notes: r.notes ?? undefined
24286
- };
24287
- }
24288
- function rowToSnapshot(r, body) {
24289
- return {
24290
- id: r.id,
24291
- device: r.device,
24292
- ts: r.ts,
24293
- label: r.label ?? undefined,
24294
- rosVersion: r.ros_version ?? undefined,
24295
- body,
24296
- bytes: r.bytes,
24297
- lines: r.lines,
24298
- sha: r.sha
24299
- };
24300
- }
24301
- var SCHEMA_STATEMENTS3 = [
24302
- `CREATE TABLE IF NOT EXISTS snapshots (
24303
- id TEXT PRIMARY KEY,
24304
- device TEXT NOT NULL,
24305
- ts INTEGER NOT NULL,
24306
- label TEXT,
24307
- ros_version TEXT,
24308
- body TEXT NOT NULL,
24309
- bytes INTEGER NOT NULL,
24310
- lines INTEGER NOT NULL,
24311
- sha TEXT NOT NULL
24312
- )`,
24313
- "CREATE INDEX IF NOT EXISTS idx_snapshots_device_ts ON snapshots(device, ts)",
24314
- `CREATE TABLE IF NOT EXISTS baselines (
24315
- device TEXT PRIMARY KEY,
24316
- snapshot_id TEXT NOT NULL,
24317
- set_at INTEGER NOT NULL,
24318
- set_by TEXT NOT NULL DEFAULT 'agent',
24319
- label TEXT,
24320
- notes TEXT
24321
- )`
24322
- ];
24323
-
24324
- class SqliteSnapshotStore {
24325
- db;
24326
- constructor(db) {
24327
- this.db = db;
24328
- db.run("PRAGMA journal_mode = WAL");
24329
- db.run("PRAGMA synchronous = NORMAL");
24330
- for (const stmt of SCHEMA_STATEMENTS3)
24331
- db.run(stmt);
24332
- }
24333
- insert(s) {
24334
- this.db.query(`INSERT OR REPLACE INTO snapshots
24335
- (id, device, ts, label, ros_version, body, bytes, lines, sha)
24336
- VALUES ($id,$device,$ts,$label,$ver,$body,$bytes,$lines,$sha)`).run({
24337
- $id: s.id,
24338
- $device: s.device,
24339
- $ts: s.ts,
24340
- $label: s.label ?? null,
24341
- $ver: s.rosVersion ?? null,
24342
- $body: s.body,
24343
- $bytes: s.bytes,
24344
- $lines: s.lines,
24345
- $sha: s.sha
24346
- });
24347
- }
24348
- get(id) {
24349
- const row = this.db.query("SELECT * FROM snapshots WHERE id = $id").get({ $id: id });
24350
- return row ? rowToSnapshot(row, row.body) : null;
24351
- }
24352
- latest(device) {
24353
- const row = this.db.query("SELECT * FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT 1").get({ $d: device });
24354
- return row ? rowToSnapshot(row, row.body) : null;
24355
- }
24356
- list(device, limit = 50, withBody = false) {
24357
- const cols = withBody ? "*" : "id, device, ts, label, ros_version, bytes, lines, sha";
24358
- const n = Math.min(Math.max(limit, 1), 500);
24359
- const rows = this.db.query(`SELECT ${cols} FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT $n`).all({ $d: device, $n: n });
24360
- return rows.map((r) => rowToSnapshot(r, withBody ? r.body : ""));
24361
- }
24362
- count(device) {
24363
- const r = this.db.query("SELECT COUNT(*) AS n FROM snapshots WHERE device = $d").get({ $d: device });
24364
- return r.n;
24365
- }
24366
- delete(ids) {
24367
- if (ids.length === 0)
24368
- return 0;
24369
- const placeholders = ids.map((_, j) => `$id${j}`).join(",");
24370
- const params = {};
24371
- ids.forEach((id, j) => {
24372
- params[`$id${j}`] = id;
24373
- });
24374
- const res = this.db.query(`DELETE FROM snapshots WHERE id IN (${placeholders})`).run(params);
24375
- return Number(res.changes ?? 0);
24376
- }
24377
- setBaseline(device, snapshotId, setBy = "agent", label, notes) {
24378
- this.db.query(`INSERT OR REPLACE INTO baselines (device, snapshot_id, set_at, set_by, label, notes)
24379
- VALUES ($device, $snapId, $setAt, $setBy, $label, $notes)`).run({
24380
- $device: device,
24381
- $snapId: snapshotId,
24382
- $setAt: Date.now(),
24383
- $setBy: setBy,
24384
- $label: label ?? null,
24385
- $notes: notes ?? null
24386
- });
24387
- }
24388
- getBaseline(device) {
24389
- const row = this.db.query("SELECT * FROM baselines WHERE device = $d").get({ $d: device });
24390
- return row ? rowToBaseline(row) : null;
24391
- }
24392
- removeBaseline(device) {
24393
- const res = this.db.query("DELETE FROM baselines WHERE device = $d").run({ $d: device });
24394
- return (res.changes ?? 0) > 0;
24395
- }
24396
- listBaselines() {
24397
- const rows = this.db.query("SELECT * FROM baselines ORDER BY set_at DESC").all();
24398
- return rows.map(rowToBaseline);
24399
- }
24400
- close() {
24401
- this.db.close();
24402
- }
24403
- }
24404
- async function openSnapshotStore(path) {
24405
- if (path !== ":memory:") {
24406
- try {
24407
- mkdirSync6(dirname6(path), { recursive: true });
24408
- } catch {}
24409
- }
24410
- const { Database } = await import("bun:sqlite");
24411
- const db = new Database(path, { create: true });
24412
- return new SqliteSnapshotStore(db);
24413
- }
24414
-
24415
25166
  // src/paths/round-trip.ts
24416
25167
  var hop = object({
24417
25168
  device: string2().min(1).max(128),
@@ -24622,21 +25373,21 @@ import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
24622
25373
 
24623
25374
  // src/paths.ts
24624
25375
  import { existsSync } from "fs";
24625
- import { join as join2, dirname as dirname7 } from "path";
25376
+ import { join as join2, dirname as dirname8 } from "path";
24626
25377
  import { fileURLToPath } from "url";
24627
25378
  var meta3 = import.meta;
24628
- var HERE = meta3.dir ?? meta3.dirname ?? dirname7(fileURLToPath(import.meta.url));
25379
+ var HERE = meta3.dir ?? meta3.dirname ?? dirname8(fileURLToPath(import.meta.url));
24629
25380
  function findRoot(start) {
24630
25381
  let dir = start;
24631
25382
  for (let i = 0;i < 12; i++) {
24632
25383
  if (existsSync(join2(dir, "package.json")))
24633
25384
  return dir;
24634
- const parent = dirname7(dir);
25385
+ const parent = dirname8(dir);
24635
25386
  if (parent === dir)
24636
25387
  break;
24637
25388
  dir = parent;
24638
25389
  }
24639
- return dirname7(start);
25390
+ return dirname8(start);
24640
25391
  }
24641
25392
  var ROOT = findRoot(HERE);
24642
25393
  var PROMPTS_DIR = join2(ROOT, "prompts");
@@ -24893,7 +25644,7 @@ async function checkDiskSpace(ctx) {
24893
25644
  // src/backups/vault.ts
24894
25645
  import {
24895
25646
  existsSync as existsSync2,
24896
- mkdirSync as mkdirSync7,
25647
+ mkdirSync as mkdirSync8,
24897
25648
  readFileSync as readFileSync4,
24898
25649
  readdirSync,
24899
25650
  renameSync,
@@ -24940,7 +25691,7 @@ function readBackup(name) {
24940
25691
  }
24941
25692
  function writeBackup(name, content) {
24942
25693
  const dir = backupDir();
24943
- mkdirSync7(dir, { recursive: true });
25694
+ mkdirSync8(dir, { recursive: true });
24944
25695
  let final = safeName(name);
24945
25696
  if (existsSync2(join4(dir, final))) {
24946
25697
  const dot = final.lastIndexOf(".");
@@ -24956,7 +25707,7 @@ function writeBackup(name, content) {
24956
25707
  }
24957
25708
  function writeBinaryBackup(name, data) {
24958
25709
  const dir = backupDir();
24959
- mkdirSync7(dir, { recursive: true });
25710
+ mkdirSync8(dir, { recursive: true });
24960
25711
  let final = safeName(name);
24961
25712
  if (existsSync2(join4(dir, final))) {
24962
25713
  const dot = final.lastIndexOf(".");
@@ -28183,11 +28934,11 @@ No differences \u2014 the live configuration matches the golden baseline.`);
28183
28934
  }
28184
28935
 
28185
28936
  // src/tools/config-drift.ts
28186
- var storePromise4 = null;
28937
+ var storePromise5 = null;
28187
28938
  function store3() {
28188
- if (!storePromise4)
28189
- storePromise4 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
28190
- return storePromise4;
28939
+ if (!storePromise5)
28940
+ storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
28941
+ return storePromise5;
28191
28942
  }
28192
28943
  function buildExport(opts) {
28193
28944
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -28395,11 +29146,11 @@ New: ${describeBaseline(snap)}${notesLine}`;
28395
29146
  ];
28396
29147
 
28397
29148
  // src/tools/config-snapshot.ts
28398
- var storePromise5 = null;
28399
- function snapshots() {
28400
- if (!storePromise5)
28401
- storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
28402
- return storePromise5;
29149
+ var storePromise6 = null;
29150
+ function snapshots2() {
29151
+ if (!storePromise6)
29152
+ storePromise6 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
29153
+ return storePromise6;
28403
29154
  }
28404
29155
  function exportCommand(opts) {
28405
29156
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -28456,7 +29207,7 @@ var configSnapshotTools = [
28456
29207
  });
28457
29208
  const meta = parseExportMeta(body);
28458
29209
  const sha = contentSha(normalizeExport(body));
28459
- const store = await snapshots();
29210
+ const store = await snapshots2();
28460
29211
  const prev = store.latest(device);
28461
29212
  if (prev && prev.sha === sha && !a.force) {
28462
29213
  return `No configuration change since the last snapshot \u2014 nothing stored.
@@ -28492,7 +29243,7 @@ ${drift}`;
28492
29243
  },
28493
29244
  async handler(a, ctx) {
28494
29245
  const device = resolveDeviceName(ctx.device);
28495
- const store = await snapshots();
29246
+ const store = await snapshots2();
28496
29247
  const rows = store.list(device, a.limit, false);
28497
29248
  if (rows.length === 0) {
28498
29249
  return `No configuration snapshots stored for '${device}'. Capture one with capture_config_snapshot.`;
@@ -28515,7 +29266,7 @@ ${lines}`;
28515
29266
  include_body: boolean2().default(true)
28516
29267
  },
28517
29268
  async handler(a, ctx) {
28518
- const store = await snapshots();
29269
+ const store = await snapshots2();
28519
29270
  const snap = store.get(a.id);
28520
29271
  if (!snap)
28521
29272
  return `Snapshot '${a.id}' not found.`;
@@ -28543,7 +29294,7 @@ ${snap.body}
28543
29294
  },
28544
29295
  async handler(a, ctx) {
28545
29296
  const device = resolveDeviceName(ctx.device);
28546
- const store = await snapshots();
29297
+ const store = await snapshots2();
28547
29298
  const from = await resolveRef(store, a.from, device, ctx);
28548
29299
  const to = await resolveRef(store, a.to, device, ctx);
28549
29300
  const result = diffLines(normalizeExport(from.body), normalizeExport(to.body), {
@@ -28583,7 +29334,7 @@ ${result.unified}`;
28583
29334
  ids: array(string2()).min(1)
28584
29335
  },
28585
29336
  async handler(a) {
28586
- const store = await snapshots();
29337
+ const store = await snapshots2();
28587
29338
  const removed = store.delete(a.ids);
28588
29339
  if (removed === 0)
28589
29340
  return `No snapshots removed (none of the given ids matched).`;
@@ -28894,10 +29645,10 @@ ${created.join(`
28894
29645
  import * as ipaddr2 from "ipaddr.js";
28895
29646
 
28896
29647
  // src/schedule/identity.ts
28897
- import { createHash as createHash2 } from "crypto";
29648
+ import { createHash as createHash3 } from "crypto";
28898
29649
  function stableId(prefix, parts) {
28899
29650
  const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
28900
- const digest = createHash2("sha256").update(material, "utf8").digest("hex").slice(0, 12);
29651
+ const digest = createHash3("sha256").update(material, "utf8").digest("hex").slice(0, 12);
28901
29652
  return `${prefix}:${digest}`;
28902
29653
  }
28903
29654
  function ruleFingerprint(rule) {
@@ -30223,7 +30974,7 @@ var cache2 = null;
30223
30974
  async function gateway() {
30224
30975
  if (cache2)
30225
30976
  return cache2;
30226
- const { moduleCatalog } = await import("./shared/cli-e879nc0x.js");
30977
+ const { moduleCatalog } = await import("./shared/cli-28qevt9d.js");
30227
30978
  const forIndex = [];
30228
30979
  const byName = new Map;
30229
30980
  for (const mod of moduleCatalog) {
@@ -32451,34 +33202,6 @@ No findings \u2014 the device passes every hardening check. \u2713`;
32451
33202
  ${body}`;
32452
33203
  }
32453
33204
 
32454
- // src/snapshots/capture.ts
32455
- var storePromise6 = null;
32456
- function snapshots2() {
32457
- if (!storePromise6)
32458
- storePromise6 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
32459
- return storePromise6;
32460
- }
32461
- async function captureSnapshot(ctx, label) {
32462
- const device = resolveDeviceName(ctx.device);
32463
- const body = await executeMikrotikCommand("/export terse", ctx);
32464
- const meta = parseExportMeta(body);
32465
- const sha = contentSha(normalizeExport(body));
32466
- const ts = Date.now();
32467
- const snap = {
32468
- id: `snap_${ts}_${sha.slice(0, 8)}`,
32469
- device,
32470
- ts,
32471
- label,
32472
- rosVersion: meta.rosVersion,
32473
- body,
32474
- bytes: Buffer.byteLength(body, "utf8"),
32475
- lines: countLines(body),
32476
- sha
32477
- };
32478
- (await snapshots2()).insert(snap);
32479
- return snap.id;
32480
- }
32481
-
32482
33205
  // src/tools/security-hardening.ts
32483
33206
  async function fetchSecurityState(ctx) {
32484
33207
  const [
@@ -33211,7 +33934,7 @@ function evaluatePolicies(policies, model, opts = {}) {
33211
33934
 
33212
33935
  // src/policy/load.ts
33213
33936
  import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
33214
- import { dirname as dirname8, isAbsolute, join as join5, resolve as resolve3 } from "path";
33937
+ import { dirname as dirname9, isAbsolute, join as join5, resolve as resolve3 } from "path";
33215
33938
 
33216
33939
  // src/policy/schema.ts
33217
33940
  var MAX_REGEX_LENGTH = 200;
@@ -33334,7 +34057,7 @@ function validatePolicyText(text) {
33334
34057
  var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
33335
34058
  function expand(pattern, cwd) {
33336
34059
  const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
33337
- const base = dirname8(absolute);
34060
+ const base = dirname9(absolute);
33338
34061
  const leaf = absolute.slice(base.length + 1);
33339
34062
  if (!leaf.includes("*")) {
33340
34063
  try {
@@ -50054,8 +50777,8 @@ function liveTxnUpdates() {
50054
50777
  }
50055
50778
 
50056
50779
  // src/txn/store.ts
50057
- import { mkdirSync as mkdirSync8 } from "fs";
50058
- import { dirname as dirname9 } from "path";
50780
+ import { mkdirSync as mkdirSync9 } from "fs";
50781
+ import { dirname as dirname10 } from "path";
50059
50782
  function toRecord2(txn, ts, label) {
50060
50783
  return {
50061
50784
  id: txn.id,
@@ -50191,7 +50914,7 @@ class SqliteTxnStore {
50191
50914
  async function openTxnStore(path) {
50192
50915
  if (path !== ":memory:") {
50193
50916
  try {
50194
- mkdirSync8(dirname9(path), { recursive: true });
50917
+ mkdirSync9(dirname10(path), { recursive: true });
50195
50918
  } catch {}
50196
50919
  }
50197
50920
  const { Database } = await import("bun:sqlite");
@@ -51254,8 +51977,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
51254
51977
  }
51255
51978
 
51256
51979
  // src/rollout/store.ts
51257
- import { mkdirSync as mkdirSync9 } from "fs";
51258
- import { dirname as dirname10 } from "path";
51980
+ import { mkdirSync as mkdirSync10 } from "fs";
51981
+ import { dirname as dirname11 } from "path";
51259
51982
  function toRecord3(rollout, ts, opts = {}) {
51260
51983
  return {
51261
51984
  id: rollout.id,
@@ -51388,7 +52111,7 @@ class SqliteRolloutStore {
51388
52111
  async function openRolloutStore(path) {
51389
52112
  if (path !== ":memory:") {
51390
52113
  try {
51391
- mkdirSync9(dirname10(path), { recursive: true });
52114
+ mkdirSync10(dirname11(path), { recursive: true });
51392
52115
  } catch {}
51393
52116
  }
51394
52117
  const { Database } = await import("bun:sqlite");
@@ -52104,8 +52827,8 @@ var JobSchema = object({
52104
52827
  });
52105
52828
 
52106
52829
  // src/schedule/store.ts
52107
- import { mkdirSync as mkdirSync10 } from "fs";
52108
- import { dirname as dirname11 } from "path";
52830
+ import { mkdirSync as mkdirSync11 } from "fs";
52831
+ import { dirname as dirname12 } from "path";
52109
52832
  var SCHEMA3 = [
52110
52833
  `CREATE TABLE IF NOT EXISTS schedule_jobs (
52111
52834
  id TEXT PRIMARY KEY,
@@ -52247,7 +52970,7 @@ class SqliteScheduleStore {
52247
52970
  async function openScheduleStore(path) {
52248
52971
  if (path !== ":memory:") {
52249
52972
  try {
52250
- mkdirSync10(dirname11(path), { recursive: true });
52973
+ mkdirSync11(dirname12(path), { recursive: true });
52251
52974
  } catch {}
52252
52975
  }
52253
52976
  const { Database } = await import("bun:sqlite");
@@ -52449,7 +53172,7 @@ var riskByTool = null;
52449
53172
  async function riskIndex() {
52450
53173
  if (riskByTool)
52451
53174
  return riskByTool;
52452
- const { moduleCatalog } = await import("./shared/cli-e879nc0x.js");
53175
+ const { moduleCatalog } = await import("./shared/cli-28qevt9d.js");
52453
53176
  const index = new Map;
52454
53177
  for (const mod of moduleCatalog) {
52455
53178
  for (const tool of mod.tools)
@@ -54671,7 +55394,7 @@ async function readScanList(ctx, list = "port-scanners") {
54671
55394
  }
54672
55395
 
54673
55396
  // src/attack/correlate.ts
54674
- import { createHash as createHash3 } from "crypto";
55397
+ import { createHash as createHash4 } from "crypto";
54675
55398
  var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
54676
55399
  var STAGE_OF = {
54677
55400
  "port-scan": "recon",
@@ -54701,7 +55424,7 @@ var SEVERITY_RANK = {
54701
55424
  info: 4
54702
55425
  };
54703
55426
  function incidentId(source, dayBucket) {
54704
- const digest = createHash3("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
55427
+ const digest = createHash4("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
54705
55428
  return `atk_${digest}`;
54706
55429
  }
54707
55430
  function worst(values) {
@@ -54923,8 +55646,8 @@ function dedupe(events, seen) {
54923
55646
  }
54924
55647
 
54925
55648
  // src/attack/store.ts
54926
- import { mkdirSync as mkdirSync11 } from "fs";
54927
- import { dirname as dirname12 } from "path";
55649
+ import { mkdirSync as mkdirSync12 } from "fs";
55650
+ import { dirname as dirname13 } from "path";
54928
55651
  var SCHEMA4 = [
54929
55652
  `CREATE TABLE IF NOT EXISTS attack_incidents (
54930
55653
  id TEXT PRIMARY KEY,
@@ -55115,7 +55838,7 @@ class SqliteAttackStore {
55115
55838
  async function openAttackStore(path) {
55116
55839
  if (path !== ":memory:") {
55117
55840
  try {
55118
- mkdirSync11(dirname12(path), { recursive: true });
55841
+ mkdirSync12(dirname13(path), { recursive: true });
55119
55842
  } catch {}
55120
55843
  }
55121
55844
  const { Database } = await import("bun:sqlite");
@@ -55816,9 +56539,9 @@ ${result}`;
55816
56539
  ];
55817
56540
 
55818
56541
  // src/core/update-check.ts
55819
- import { existsSync as existsSync3, mkdirSync as mkdirSync12, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
56542
+ import { existsSync as existsSync3, mkdirSync as mkdirSync13, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
55820
56543
  import { homedir as homedir2 } from "os";
55821
- import { dirname as dirname13, join as join8 } from "path";
56544
+ import { dirname as dirname14, join as join8 } from "path";
55822
56545
 
55823
56546
  // src/version.ts
55824
56547
  import { readFileSync as readFileSync7 } from "fs";
@@ -55866,9 +56589,9 @@ function loadFileCacheSync() {
55866
56589
  }
55867
56590
  function saveFileCache(data) {
55868
56591
  try {
55869
- const dir = dirname13(CACHE_PATH);
56592
+ const dir = dirname14(CACHE_PATH);
55870
56593
  if (!existsSync3(dir))
55871
- mkdirSync12(dir, { recursive: true });
56594
+ mkdirSync13(dir, { recursive: true });
55872
56595
  writeFileSync2(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
55873
56596
  } catch {}
55874
56597
  }
@@ -61540,6 +62263,13 @@ ${lines.join(`
61540
62263
 
61541
62264
  // src/tools/index.ts
61542
62265
  var moduleCatalog2 = [
62266
+ {
62267
+ label: "Home Internet",
62268
+ slug: "home-internet",
62269
+ group: "System & Ops",
62270
+ description: "Plain-language internet diagnosis, household inventory and approved temporary client policies with bounded path comparisons.",
62271
+ tools: homeInternetTools
62272
+ },
61543
62273
  {
61544
62274
  label: "Multi-Router Round Trip",
61545
62275
  slug: "round-trip",
@@ -62571,7 +63301,7 @@ import { existsSync as existsSync5 } from "fs";
62571
63301
  import { spawn } from "child_process";
62572
63302
  import { readFileSync as readFileSync11 } from "fs";
62573
63303
  import { homedir as homedir5, networkInterfaces } from "os";
62574
- import { dirname as dirname19, join as join12 } from "path";
63304
+ import { dirname as dirname20, join as join12 } from "path";
62575
63305
  var {serve } = globalThis.Bun;
62576
63306
 
62577
63307
  // src/observability/modules.ts
@@ -62648,8 +63378,8 @@ function applyModuleToggle(filter, slug, enabled) {
62648
63378
  }
62649
63379
 
62650
63380
  // src/config-write.ts
62651
- import { mkdirSync as mkdirSync13, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
62652
- import { dirname as dirname14 } from "path";
63381
+ import { mkdirSync as mkdirSync14, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
63382
+ import { dirname as dirname15 } from "path";
62653
63383
  var SCHEMA_REF = "./schemas/config.schema.json";
62654
63384
  function mergeSecrets(incoming, current) {
62655
63385
  if (incoming === REDACTED) {
@@ -62681,7 +63411,7 @@ function backupName(path, ts) {
62681
63411
  return `${path}.bak-${ts}`;
62682
63412
  }
62683
63413
  function atomicWrite(path, text) {
62684
- mkdirSync13(dirname14(path), { recursive: true });
63414
+ mkdirSync14(dirname15(path), { recursive: true });
62685
63415
  const tmp = `${path}.tmp-${process.pid}`;
62686
63416
  writeFileSync3(tmp, text, "utf8");
62687
63417
  renameSync2(tmp, path);
@@ -62755,6 +63485,42 @@ async function investigationRoutes(req, url) {
62755
63485
  }
62756
63486
  }
62757
63487
 
63488
+ // src/observability/home-routes.ts
63489
+ var routes = {
63490
+ "GET /api/home-internet": "get_home_internet",
63491
+ "POST /api/home-internet/refresh": "refresh_home_devices",
63492
+ "POST /api/home-internet/name": "name_home_device",
63493
+ "POST /api/home-internet/diagnose": "diagnose_home_internet",
63494
+ "POST /api/home-internet/compare": "compare_home_paths",
63495
+ "POST /api/home-internet/preview": "preview_home_policy",
63496
+ "POST /api/home-internet/apply": "apply_home_policy",
63497
+ "POST /api/home-internet/undo": "undo_home_policy"
63498
+ };
63499
+ async function homeRoutes(req, url) {
63500
+ if (!url.pathname.startsWith("/api/home-internet"))
63501
+ return null;
63502
+ const tool = homeInternetTools.find((t) => t.name === routes[`${req.method} ${url.pathname}`]);
63503
+ if (!tool)
63504
+ return Response.json({ error: "Unsupported Home Internet route" }, { status: 405 });
63505
+ try {
63506
+ const device = url.searchParams.get("device");
63507
+ if (!device)
63508
+ throw new Error("Choose a router explicitly.");
63509
+ const input = req.method === "POST" ? JSON.parse(await readOperationBody(req)) : {};
63510
+ const result = await tool.handler(object(tool.inputSchema).strict().parse(input), createContext(undefined, device));
63511
+ return new Response(result, {
63512
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
63513
+ });
63514
+ } catch (e) {
63515
+ return Response.json({
63516
+ error: e instanceof ZodError ? "Invalid input. Check IP/MAC addresses, duration and required fields." : e instanceof Error ? e.message : "Home Internet operation failed."
63517
+ }, {
63518
+ status: e instanceof DashboardInputError ? e.status : 400,
63519
+ headers: { "cache-control": "no-store" }
63520
+ });
63521
+ }
63522
+ }
63523
+
62758
63524
  // src/observability/service-contract-routes.ts
62759
63525
  async function serviceContractRoutes(req, url) {
62760
63526
  if (!url.pathname.startsWith("/api/service-contracts"))
@@ -62910,7 +63676,7 @@ function createConfigAdmin(deps) {
62910
63676
  // src/observability/config-history.ts
62911
63677
  import {
62912
63678
  existsSync as existsSync4,
62913
- mkdirSync as mkdirSync14,
63679
+ mkdirSync as mkdirSync15,
62914
63680
  readFileSync as readFileSync9,
62915
63681
  readdirSync as readdirSync3,
62916
63682
  rmSync as rmSync2,
@@ -62962,7 +63728,7 @@ function deleteVersion(id) {
62962
63728
  }
62963
63729
  function recordVersion(config, kind, now, label) {
62964
63730
  const dir = historyDir();
62965
- mkdirSync14(dir, { recursive: true });
63731
+ mkdirSync15(dir, { recursive: true });
62966
63732
  let ts = now;
62967
63733
  while (existsSync4(join9(dir, `v${ts}.json`)))
62968
63734
  ts++;
@@ -63399,8 +64165,8 @@ function subscribeTraffic(device, fn) {
63399
64165
  }
63400
64166
 
63401
64167
  // src/observability/store.ts
63402
- import { mkdirSync as mkdirSync15 } from "fs";
63403
- import { dirname as dirname15 } from "path";
64168
+ import { mkdirSync as mkdirSync16 } from "fs";
64169
+ import { dirname as dirname16 } from "path";
63404
64170
  function rowToEvent2(r) {
63405
64171
  return {
63406
64172
  id: r.id,
@@ -63578,7 +64344,7 @@ class SqliteEventStore {
63578
64344
  async function openSqliteStore(path) {
63579
64345
  if (path !== ":memory:") {
63580
64346
  try {
63581
- mkdirSync15(dirname15(path), { recursive: true });
64347
+ mkdirSync16(dirname16(path), { recursive: true });
63582
64348
  } catch {}
63583
64349
  }
63584
64350
  const { Database } = await import("bun:sqlite");
@@ -63587,8 +64353,8 @@ async function openSqliteStore(path) {
63587
64353
  }
63588
64354
 
63589
64355
  // src/observability/capsman-store.ts
63590
- import { mkdirSync as mkdirSync16 } from "fs";
63591
- import { dirname as dirname16 } from "path";
64356
+ import { mkdirSync as mkdirSync17 } from "fs";
64357
+ import { dirname as dirname17 } from "path";
63592
64358
  function summariseRadioSamples(rows) {
63593
64359
  const byRadio = new Map;
63594
64360
  for (const r of rows) {
@@ -63675,7 +64441,7 @@ class SqliteCapsmanStore {
63675
64441
  async function openCapsmanStore(path) {
63676
64442
  if (path !== ":memory:") {
63677
64443
  try {
63678
- mkdirSync16(dirname16(path), { recursive: true });
64444
+ mkdirSync17(dirname17(path), { recursive: true });
63679
64445
  } catch {}
63680
64446
  }
63681
64447
  const { Database } = await import("bun:sqlite");
@@ -63750,8 +64516,8 @@ function stopCapsmanSampler() {
63750
64516
  }
63751
64517
 
63752
64518
  // src/observability/usage-store.ts
63753
- import { mkdirSync as mkdirSync17 } from "fs";
63754
- import { dirname as dirname17 } from "path";
64519
+ import { mkdirSync as mkdirSync18 } from "fs";
64520
+ import { dirname as dirname18 } from "path";
63755
64521
  function dayOf(ts) {
63756
64522
  return new Date(ts).toISOString().slice(0, 10);
63757
64523
  }
@@ -63874,7 +64640,7 @@ class SqliteUsageStore {
63874
64640
  async function openUsageStore(path) {
63875
64641
  if (path !== ":memory:") {
63876
64642
  try {
63877
- mkdirSync17(dirname17(path), { recursive: true });
64643
+ mkdirSync18(dirname18(path), { recursive: true });
63878
64644
  } catch {}
63879
64645
  }
63880
64646
  const { Database } = await import("bun:sqlite");
@@ -64316,7 +65082,7 @@ async function postureRoutes(req, url) {
64316
65082
  }
64317
65083
 
64318
65084
  // src/observability/access-settings.ts
64319
- import { createHash as createHash4 } from "crypto";
65085
+ import { createHash as createHash5 } from "crypto";
64320
65086
  var list2 = array(string2().trim().min(1).max(200)).max(200);
64321
65087
  var accessSchema = AccessConfigSchema.extend({
64322
65088
  devices: list2,
@@ -64346,7 +65112,7 @@ function createAccessSettingsRoutes(admin, deps = {
64346
65112
  }) {
64347
65113
  let pending = null;
64348
65114
  const tools = moduleCatalog2.flatMap((m) => m.tools.map((t) => ({ name: t.name, risk: riskOf(t.annotations), noDevice: !!t.noDevice })));
64349
- const revision = () => createHash4("sha256").update(JSON.stringify([deps.getConfig(), deps.getAccessPolicy()])).digest("hex");
65115
+ const revision = () => createHash5("sha256").update(JSON.stringify([deps.getConfig(), deps.getAccessPolicy()])).digest("hex");
64350
65116
  const payload = () => {
64351
65117
  const cfg = deps.getConfig();
64352
65118
  const id = admin.pendingId();
@@ -64729,8 +65495,8 @@ async function rolloutRoutes(req, url) {
64729
65495
  }
64730
65496
 
64731
65497
  // src/policy/results.ts
64732
- import { mkdirSync as mkdirSync18 } from "fs";
64733
- import { dirname as dirname18 } from "path";
65498
+ import { mkdirSync as mkdirSync19 } from "fs";
65499
+ import { dirname as dirname19 } from "path";
64734
65500
  var SCHEMA_STATEMENTS9 = [
64735
65501
  `CREATE TABLE IF NOT EXISTS policy_results (
64736
65502
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -64790,7 +65556,7 @@ class SqlitePolicyResultStore {
64790
65556
  async function openPolicyResultStore(path) {
64791
65557
  if (path !== ":memory:") {
64792
65558
  try {
64793
- mkdirSync18(dirname18(path), { recursive: true });
65559
+ mkdirSync19(dirname19(path), { recursive: true });
64794
65560
  } catch {}
64795
65561
  }
64796
65562
  const { Database } = await import("bun:sqlite");
@@ -66802,13 +67568,13 @@ async function runDashboard(cfg, transportLabel) {
66802
67568
  startHealthChecks(30000);
66803
67569
  startGeoLookups();
66804
67570
  try {
66805
- usageStore = await openUsageStore(join12(dirname19(cfg.dbPath), "usage.db"));
67571
+ usageStore = await openUsageStore(join12(dirname20(cfg.dbPath), "usage.db"));
66806
67572
  startUsageSampler(usageStore);
66807
67573
  } catch (e) {
66808
67574
  logger.warn(`[${SERVER_TAG3}] usage history disabled: ${String(e)}`);
66809
67575
  }
66810
67576
  try {
66811
- capsmanStore = await openCapsmanStore(join12(dirname19(cfg.dbPath), "capsman.db"));
67577
+ capsmanStore = await openCapsmanStore(join12(dirname20(cfg.dbPath), "capsman.db"));
66812
67578
  startCapsmanSampler(capsmanStore);
66813
67579
  } catch (e) {
66814
67580
  logger.warn(`[${SERVER_TAG3}] capsman trends disabled: ${String(e)}`);
@@ -66877,6 +67643,9 @@ async function runDashboard(cfg, transportLabel) {
66877
67643
  const investigationResp = await investigationRoutes(req, url);
66878
67644
  if (investigationResp)
66879
67645
  return investigationResp;
67646
+ const homeResp = await homeRoutes(req, url);
67647
+ if (homeResp)
67648
+ return homeResp;
66880
67649
  const serviceContractResp = await serviceContractRoutes(req, url);
66881
67650
  if (serviceContractResp)
66882
67651
  return serviceContractResp;
@@ -67230,7 +67999,7 @@ async function runDashboard(cfg, transportLabel) {
67230
67999
  }
67231
68000
 
67232
68001
  // src/transport/http.ts
67233
- import { randomUUID as randomUUID4 } from "crypto";
68002
+ import { randomUUID as randomUUID5 } from "crypto";
67234
68003
  var {serve: serve2 } = globalThis.Bun;
67235
68004
 
67236
68005
  // node_modules/content-type/index.js
@@ -76600,7 +77369,7 @@ async function runHttp(mcp) {
76600
77369
  if (existing)
76601
77370
  return existing;
76602
77371
  const transport = new WebStandardStreamableHTTPServerTransport({
76603
- sessionIdGenerator: () => randomUUID4(),
77372
+ sessionIdGenerator: () => randomUUID5(),
76604
77373
  enableJsonResponse: true,
76605
77374
  ...security,
76606
77375
  onsessioninitialized: (id) => {