@usex/mikrotik-mcp 5.11.0 → 5.13.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
@@ -17704,6 +17704,14 @@ var REPORT_VIEW_TOOLS = {
17704
17704
  "packet_capture_status"
17705
17705
  ],
17706
17706
  reports: [
17707
+ "diagnose_home_internet",
17708
+ "compare_home_paths",
17709
+ "get_home_internet",
17710
+ "refresh_home_devices",
17711
+ "name_home_device",
17712
+ "preview_home_policy",
17713
+ "apply_home_policy",
17714
+ "undo_home_policy",
17707
17715
  "diagnose",
17708
17716
  "trace_path",
17709
17717
  "correlate_events",
@@ -22475,12 +22483,892 @@ var investigationTools = [
22475
22483
  })
22476
22484
  ];
22477
22485
 
22478
- // src/tools/service-contracts.ts
22479
- import { randomUUID as randomUUID3 } from "crypto";
22486
+ // src/home/model.ts
22487
+ var macInput = string2().regex(/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i);
22488
+ var diagnosisInput = object({
22489
+ client: ipv42(),
22490
+ target: string2().max(253).regex(/^[a-z\d](?:[a-z\d.-]*[a-z\d])?$/i).default("example.com")
22491
+ });
22492
+ var compareInput = object({
22493
+ target: ipv42(),
22494
+ tables: array(string2().min(1).max(64)).min(1).max(3),
22495
+ goal: _enum(["calls", "gaming", "download"]).default("calls")
22496
+ });
22497
+ var policyInput = object({
22498
+ mac: macInput,
22499
+ action: _enum(["pause", "priority", "route"]),
22500
+ minutes: number2().int().min(5).max(120).default(30),
22501
+ startInMinutes: number2().int().min(0).max(1440).default(0),
22502
+ table: string2().min(1).max(64).optional()
22503
+ });
22504
+ function enabled2(row) {
22505
+ return !isYes(row.disabled) && !/[XI]/.test(row.flags ?? "");
22506
+ }
22507
+ function activeRoute(row) {
22508
+ return enabled2(row) && (isYes(row.active) || /A/.test(row.flags ?? ""));
22509
+ }
22510
+ function milliseconds(text) {
22511
+ if (!text)
22512
+ return null;
22513
+ const units = [...text.matchAll(/(\d+(?:\.\d+)?)(us|ms|s)/g)];
22514
+ if (!units.length || units.map((m) => m[0]).join("") !== text)
22515
+ return null;
22516
+ return units.reduce((sum, m) => sum + Number(m[1]) * (m[2] === "s" ? 1000 : m[2] === "us" ? 0.001 : 1), 0);
22517
+ }
22518
+ function pingSample(table, raw) {
22519
+ const sent = Number(raw.match(/sent=(\d+)/)?.[1]);
22520
+ const received = Number(raw.match(/received=(\d+)/)?.[1]);
22521
+ const rtt = (key) => milliseconds(raw.match(new RegExp(`${key}-rtt=([^\\s]+)`))?.[1]);
22522
+ const min = rtt("min"), max = rtt("max");
22523
+ if (!Number.isFinite(sent) || sent < 1 || !Number.isFinite(received) || received > sent)
22524
+ return {
22525
+ table,
22526
+ state: "unknown",
22527
+ loss: null,
22528
+ latency: null,
22529
+ spread: null,
22530
+ note: "No usable ICMP summary. This RouterOS version may not support table-scoped ping."
22531
+ };
22532
+ return {
22533
+ table,
22534
+ state: "observed",
22535
+ loss: (sent - received) * 100 / sent,
22536
+ latency: rtt("avg"),
22537
+ spread: min === null || max === null ? null : Math.max(0, max - min),
22538
+ note: "Five router-originated ICMP probes; RTT range is not a client jitter or throughput measurement."
22539
+ };
22540
+ }
22541
+ function recommendPath(paths, goal) {
22542
+ if (goal === "download")
22543
+ return null;
22544
+ const usable = paths.filter((p) => p.state === "observed" && p.loss !== null && p.loss < 100 && p.latency !== null && p.spread !== null);
22545
+ const score = (p) => p.loss * 1000 + p.latency + p.spread * (goal === "calls" ? 2 : 1);
22546
+ return usable.sort((a, b) => score(a) - score(b))[0]?.table ?? null;
22547
+ }
22548
+ function tagSelector(tag) {
22549
+ return `[find where comment=${quoteValue(tag)}]`;
22550
+ }
22551
+ function temporaryCommands(id, input, ip, setup, activate, revert) {
22552
+ const tag = `mcp-home-${id}`;
22553
+ const clearMarkers = new Cmd(`/ip firewall address-list remove ${tagSelector(tag)}`).build();
22554
+ const clearScheduler = new Cmd(`/system scheduler remove ${tagSelector(tag)}`).build();
22555
+ const undo = [...revert, clearMarkers, clearScheduler];
22556
+ const leaseMatch = `[/ip dhcp-server lease find where mac-address=${quoteValue(input.mac)} address=${quoteValue(ip)} dynamic=no status=bound]`;
22557
+ const expired = `([:len [/ip firewall address-list find where list=${quoteValue(`${tag}-end`)}]] = 0 || [:len ${leaseMatch}] != 1)`;
22558
+ const waiting = `[:len [/ip firewall address-list find where list=${quoteValue(`${tag}-start`)}]] = 0`;
22559
+ const tick = `:if (${expired}) do={ ${undo.join("; ")} } else={ :if (${waiting}) do={ ${activate.join("; ")} } }`;
22560
+ const commands = [
22561
+ ...setup,
22562
+ 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(),
22563
+ ...input.startInMinutes ? [
22564
+ new Cmd("/ip firewall address-list add").set("list", `${tag}-start`).set("address", ip).set("timeout", `${input.startInMinutes}m`).set("comment", tag).build()
22565
+ ] : [],
22566
+ 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(),
22567
+ 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(),
22568
+ ...!input.startInMinutes ? activate : []
22569
+ ];
22570
+ return { commands, undo };
22571
+ }
22572
+
22573
+ // src/home/read.ts
22574
+ async function checkedRead(command, ctx, read = executeMikrotikCommand) {
22575
+ const raw = await read(command, ctx, { maxMs: 8000 });
22576
+ if (looksLikeError(raw) || raw.length > 512000)
22577
+ throw new Error("Router rejected the command or returned too much data; its outcome was not confirmed.");
22578
+ return raw;
22579
+ }
22580
+ async function rows(path, fields, ctx, read = executeMikrotikCommand) {
22581
+ const raw = await checkedRead(new Cmd(`${path} print detail without-paging`).build(), ctx, read);
22582
+ const result = parseRecords(raw).rows;
22583
+ if (!result.length && !isEmpty(raw) && !/^\s*(?:Flags:.*)?\s*$/.test(raw) || result.length > 1000)
22584
+ throw new Error(`Cannot safely interpret ${path}.`);
22585
+ const keys = new Set(["#", "flags", ...fields.split(",")]);
22586
+ return result.map((row) => Object.fromEntries(Object.entries(row).filter(([key]) => keys.has(key))));
22587
+ }
22588
+ async function diagnoseInternet(input, ctx, read = executeMikrotikCommand) {
22589
+ const a = diagnosisInput.parse(input), device = resolveDeviceName(ctx.device);
22590
+ assertDeviceAccess([device], "diagnose_home_internet", "READ");
22591
+ const findings = [];
22592
+ const capture = async (area, work) => {
22593
+ try {
22594
+ findings.push(await work());
22595
+ } catch {
22596
+ findings.push({
22597
+ area,
22598
+ state: "unknown",
22599
+ title: `${area} could not be measured`,
22600
+ detail: "The router query failed or is unsupported. Missing evidence is not a healthy result.",
22601
+ next: "Check permissions and device support, then retry."
22602
+ });
22603
+ }
22604
+ };
22605
+ await capture("Router", async () => {
22606
+ const resource = parseKeyValues(await checkedRead("/system resource print", ctx, read));
22607
+ const cpu = Number(resource["cpu-load"]?.replace("%", ""));
22608
+ const free = parseSize(resource["free-memory"]), total = parseSize(resource["total-memory"]);
22609
+ if (!Number.isFinite(cpu) || !total || free === undefined)
22610
+ throw new Error("No resources");
22611
+ const memory = Math.round((1 - free / total) * 100), hot = cpu >= 85 || memory >= 90;
22612
+ return {
22613
+ area: "Router",
22614
+ state: hot ? "suspected" : "observed",
22615
+ title: hot ? "The router may be under pressure" : "Router resources have headroom in this sample",
22616
+ detail: `CPU ${cpu}% \xB7 memory ${memory}%. One sample does not establish a bottleneck.`,
22617
+ next: "Repeat while the slow download is running; compare with the Devices page."
22618
+ };
22619
+ });
22620
+ await capture("DNS", async () => {
22621
+ const start = Date.now();
22622
+ const resolved = (await checkedRead(`:put [:resolve ${new Cmd("").set("domain-name", a.target).build().trim()}]`, ctx, read)).trim();
22623
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(resolved))
22624
+ throw new Error("Not an IPv4 result");
22625
+ return {
22626
+ area: "DNS",
22627
+ state: "observed",
22628
+ title: "The router resolved this destination",
22629
+ detail: `${a.target} \u2192 ${resolved}. Query plus SSH round trip: ${Date.now() - start} ms (not pure DNS latency).`,
22630
+ next: "If only one device is affected, compare its DNS and secure-DNS settings."
22631
+ };
22632
+ });
22633
+ await capture("Internet", async () => {
22634
+ const result = pingSample("main", await checkedRead(new Cmd("/ping").set("address", a.target).set("count", 5).set("interval", "200ms").build(), ctx, read));
22635
+ if (result.state === "unknown")
22636
+ throw new Error("No ping");
22637
+ return {
22638
+ area: "Internet",
22639
+ state: result.loss > 0 ? "suspected" : "observed",
22640
+ title: result.loss > 0 ? "Some router probes did not return" : "All router probes returned",
22641
+ detail: `${result.loss}% loss \xB7 average RTT ${result.latency ?? "unknown"} ms. ICMP can be deprioritized; this does not locate a failing hop.`,
22642
+ next: "Compare paths below. Router probes do not test the client's firewall path or application."
22643
+ };
22644
+ });
22645
+ await capture("Wi-Fi", async () => {
22646
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,active-address", ctx, read);
22647
+ const mac = leases.find((r) => r.address === a.client || r["active-address"] === a.client)?.["mac-address"];
22648
+ if (!mac)
22649
+ throw new Error("No attachment");
22650
+ let registrations;
22651
+ try {
22652
+ registrations = await rows("/interface wifi registration-table", "mac-address,signal,tx-rate,rx-rate", ctx, read);
22653
+ } catch {
22654
+ registrations = await rows("/interface wireless registration-table", "mac-address,signal-strength,tx-rate,rx-rate", ctx, read);
22655
+ }
22656
+ const entry = registrations.find((r) => r["mac-address"]?.toUpperCase() === mac.toUpperCase());
22657
+ const signal = Number.parseFloat(entry?.signal ?? entry?.["signal-strength"] ?? "");
22658
+ if (!entry || !Number.isFinite(signal))
22659
+ throw new Error("No Wi-Fi measurement");
22660
+ return {
22661
+ area: "Wi-Fi",
22662
+ state: signal < -70 ? "suspected" : "observed",
22663
+ title: signal < -70 ? "Weak Wi-Fi signal may be slowing this device" : "Wi-Fi signal is not weak in this sample",
22664
+ detail: `${signal} dBm \xB7 PHY transmit rate ${entry["tx-rate"] ?? "unknown"}. PHY rate is not download speed.`,
22665
+ next: "Move closer to the access point and compare; interference and airtime remain unmeasured."
22666
+ };
22667
+ });
22668
+ await capture("Bandwidth", async () => {
22669
+ const queues = await rows("/queue simple", "name,target,max-limit,disabled", ctx, read);
22670
+ const matches = queues.filter((q) => enabled2(q) && q.target?.split(",").some((t) => t === a.client || t === `${a.client}/32`));
22671
+ return {
22672
+ area: "Bandwidth",
22673
+ state: matches.length ? "observed" : "unknown",
22674
+ title: matches.length ? "A per-device bandwidth policy exists" : "Available bandwidth has not been measured",
22675
+ 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.",
22676
+ next: "Run an endpoint speed test before and during the problem. These checks do not download test files or change MTU."
22677
+ };
22678
+ });
22679
+ return {
22680
+ device,
22681
+ client: a.client,
22682
+ target: a.target,
22683
+ at: Date.now(),
22684
+ applicationHealth: "unverified",
22685
+ findings
22686
+ };
22687
+ }
22688
+ async function comparePaths(input, ctx, read = executeMikrotikCommand) {
22689
+ const a = compareInput.parse(input), device = resolveDeviceName(ctx.device);
22690
+ assertDeviceAccess([device], "compare_home_paths", "READ");
22691
+ const tables = await rows("/routing table", "name,fib,disabled", ctx, read);
22692
+ const names = [...new Set(a.tables)];
22693
+ if (names.some((name) => !tables.some((t) => t.name === name && enabled2(t) && (t.fib === "yes" || t.fib === "true"))))
22694
+ throw new Error("Choose an existing enabled FIB routing table.");
22695
+ const paths = [];
22696
+ for (const table of names) {
22697
+ try {
22698
+ 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)));
22699
+ } catch {
22700
+ paths.push(pingSample(table, ""));
22701
+ }
22702
+ }
22703
+ return {
22704
+ device,
22705
+ at: Date.now(),
22706
+ target: a.target,
22707
+ goal: a.goal,
22708
+ paths,
22709
+ recommended: recommendPath(paths, a.goal),
22710
+ 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."
22711
+ };
22712
+ }
22480
22713
 
22481
- // src/service-contracts/store.ts
22714
+ // src/home/policies.ts
22715
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
22716
+
22717
+ // src/snapshots/format.ts
22718
+ import { createHash } from "crypto";
22719
+ var TIMESTAMP_HEADER = /^#\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b.*by RouterOS/i;
22720
+ function parseExportMeta(body) {
22721
+ const head = body.slice(0, 600);
22722
+ const version = head.match(/by RouterOS ([^\s#]+)/i)?.[1];
22723
+ const exportedAt = head.match(/#\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1];
22724
+ return { rosVersion: version, exportedAt };
22725
+ }
22726
+ function normalizeExport(body) {
22727
+ return body.replace(/\r\n/g, `
22728
+ `).split(`
22729
+ `).filter((line) => !TIMESTAMP_HEADER.test(line)).join(`
22730
+ `).replace(/\n+$/, "");
22731
+ }
22732
+ function contentSha(normalizedBody) {
22733
+ return createHash("sha256").update(normalizedBody, "utf8").digest("hex").slice(0, 16);
22734
+ }
22735
+ function countLines(body) {
22736
+ const trimmed = body.replace(/\n+$/, "");
22737
+ return trimmed === "" ? 0 : trimmed.split(`
22738
+ `).length;
22739
+ }
22740
+
22741
+ // src/snapshots/store.ts
22482
22742
  import { mkdirSync as mkdirSync4 } from "fs";
22483
22743
  import { dirname as dirname4 } from "path";
22744
+ function rowToBaseline(r) {
22745
+ return {
22746
+ device: r.device,
22747
+ snapshotId: r.snapshot_id,
22748
+ setAt: r.set_at,
22749
+ setBy: r.set_by,
22750
+ label: r.label ?? undefined,
22751
+ notes: r.notes ?? undefined
22752
+ };
22753
+ }
22754
+ function rowToSnapshot(r, body) {
22755
+ return {
22756
+ id: r.id,
22757
+ device: r.device,
22758
+ ts: r.ts,
22759
+ label: r.label ?? undefined,
22760
+ rosVersion: r.ros_version ?? undefined,
22761
+ body,
22762
+ bytes: r.bytes,
22763
+ lines: r.lines,
22764
+ sha: r.sha
22765
+ };
22766
+ }
22767
+ var SCHEMA_STATEMENTS3 = [
22768
+ `CREATE TABLE IF NOT EXISTS snapshots (
22769
+ id TEXT PRIMARY KEY,
22770
+ device TEXT NOT NULL,
22771
+ ts INTEGER NOT NULL,
22772
+ label TEXT,
22773
+ ros_version TEXT,
22774
+ body TEXT NOT NULL,
22775
+ bytes INTEGER NOT NULL,
22776
+ lines INTEGER NOT NULL,
22777
+ sha TEXT NOT NULL
22778
+ )`,
22779
+ "CREATE INDEX IF NOT EXISTS idx_snapshots_device_ts ON snapshots(device, ts)",
22780
+ `CREATE TABLE IF NOT EXISTS baselines (
22781
+ device TEXT PRIMARY KEY,
22782
+ snapshot_id TEXT NOT NULL,
22783
+ set_at INTEGER NOT NULL,
22784
+ set_by TEXT NOT NULL DEFAULT 'agent',
22785
+ label TEXT,
22786
+ notes TEXT
22787
+ )`
22788
+ ];
22789
+
22790
+ class SqliteSnapshotStore {
22791
+ db;
22792
+ constructor(db) {
22793
+ this.db = db;
22794
+ db.run("PRAGMA journal_mode = WAL");
22795
+ db.run("PRAGMA synchronous = NORMAL");
22796
+ for (const stmt of SCHEMA_STATEMENTS3)
22797
+ db.run(stmt);
22798
+ }
22799
+ insert(s) {
22800
+ this.db.query(`INSERT OR REPLACE INTO snapshots
22801
+ (id, device, ts, label, ros_version, body, bytes, lines, sha)
22802
+ VALUES ($id,$device,$ts,$label,$ver,$body,$bytes,$lines,$sha)`).run({
22803
+ $id: s.id,
22804
+ $device: s.device,
22805
+ $ts: s.ts,
22806
+ $label: s.label ?? null,
22807
+ $ver: s.rosVersion ?? null,
22808
+ $body: s.body,
22809
+ $bytes: s.bytes,
22810
+ $lines: s.lines,
22811
+ $sha: s.sha
22812
+ });
22813
+ }
22814
+ get(id) {
22815
+ const row = this.db.query("SELECT * FROM snapshots WHERE id = $id").get({ $id: id });
22816
+ return row ? rowToSnapshot(row, row.body) : null;
22817
+ }
22818
+ latest(device) {
22819
+ const row = this.db.query("SELECT * FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT 1").get({ $d: device });
22820
+ return row ? rowToSnapshot(row, row.body) : null;
22821
+ }
22822
+ list(device, limit = 50, withBody = false) {
22823
+ const cols = withBody ? "*" : "id, device, ts, label, ros_version, bytes, lines, sha";
22824
+ const n = Math.min(Math.max(limit, 1), 500);
22825
+ const rows = this.db.query(`SELECT ${cols} FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT $n`).all({ $d: device, $n: n });
22826
+ return rows.map((r) => rowToSnapshot(r, withBody ? r.body : ""));
22827
+ }
22828
+ count(device) {
22829
+ const r = this.db.query("SELECT COUNT(*) AS n FROM snapshots WHERE device = $d").get({ $d: device });
22830
+ return r.n;
22831
+ }
22832
+ delete(ids) {
22833
+ if (ids.length === 0)
22834
+ return 0;
22835
+ const placeholders = ids.map((_, j) => `$id${j}`).join(",");
22836
+ const params = {};
22837
+ ids.forEach((id, j) => {
22838
+ params[`$id${j}`] = id;
22839
+ });
22840
+ const res = this.db.query(`DELETE FROM snapshots WHERE id IN (${placeholders})`).run(params);
22841
+ return Number(res.changes ?? 0);
22842
+ }
22843
+ setBaseline(device, snapshotId, setBy = "agent", label, notes) {
22844
+ this.db.query(`INSERT OR REPLACE INTO baselines (device, snapshot_id, set_at, set_by, label, notes)
22845
+ VALUES ($device, $snapId, $setAt, $setBy, $label, $notes)`).run({
22846
+ $device: device,
22847
+ $snapId: snapshotId,
22848
+ $setAt: Date.now(),
22849
+ $setBy: setBy,
22850
+ $label: label ?? null,
22851
+ $notes: notes ?? null
22852
+ });
22853
+ }
22854
+ getBaseline(device) {
22855
+ const row = this.db.query("SELECT * FROM baselines WHERE device = $d").get({ $d: device });
22856
+ return row ? rowToBaseline(row) : null;
22857
+ }
22858
+ removeBaseline(device) {
22859
+ const res = this.db.query("DELETE FROM baselines WHERE device = $d").run({ $d: device });
22860
+ return (res.changes ?? 0) > 0;
22861
+ }
22862
+ listBaselines() {
22863
+ const rows = this.db.query("SELECT * FROM baselines ORDER BY set_at DESC").all();
22864
+ return rows.map(rowToBaseline);
22865
+ }
22866
+ close() {
22867
+ this.db.close();
22868
+ }
22869
+ }
22870
+ async function openSnapshotStore(path) {
22871
+ if (path !== ":memory:") {
22872
+ try {
22873
+ mkdirSync4(dirname4(path), { recursive: true });
22874
+ } catch {}
22875
+ }
22876
+ const { Database } = await import("bun:sqlite");
22877
+ const db = new Database(path, { create: true });
22878
+ return new SqliteSnapshotStore(db);
22879
+ }
22880
+
22881
+ // src/snapshots/capture.ts
22882
+ var storePromise3 = null;
22883
+ function snapshots() {
22884
+ if (!storePromise3)
22885
+ storePromise3 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
22886
+ return storePromise3;
22887
+ }
22888
+ async function captureSnapshot(ctx, label, requireExport = false) {
22889
+ const device = resolveDeviceName(ctx.device);
22890
+ const body = await executeMikrotikCommand("/export terse", ctx);
22891
+ if (requireExport && (looksLikeError(body) || !/^\/[a-z]/m.test(body) || /#\s*error exporting/i.test(body)))
22892
+ throw new Error("A complete pre-change configuration export could not be captured; no policy was applied.");
22893
+ const meta = parseExportMeta(body);
22894
+ const sha = contentSha(normalizeExport(body));
22895
+ const ts = Date.now();
22896
+ const snap = {
22897
+ id: `snap_${ts}_${sha.slice(0, 8)}`,
22898
+ device,
22899
+ ts,
22900
+ label,
22901
+ rosVersion: meta.rosVersion,
22902
+ body,
22903
+ bytes: Buffer.byteLength(body, "utf8"),
22904
+ lines: countLines(body),
22905
+ sha
22906
+ };
22907
+ (await snapshots()).insert(snap);
22908
+ return snap.id;
22909
+ }
22910
+
22911
+ // src/home/store.ts
22912
+ import { mkdirSync as mkdirSync5 } from "fs";
22913
+ import { dirname as dirname5 } from "path";
22914
+ class HomeStore {
22915
+ db;
22916
+ constructor(db) {
22917
+ this.db = db;
22918
+ 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))");
22919
+ 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)");
22920
+ 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')");
22921
+ }
22922
+ clients(device) {
22923
+ return this.db.query("SELECT body FROM home_clients WHERE device=?").all(device).map((r) => JSON.parse(r.body));
22924
+ }
22925
+ saveClient(device, client) {
22926
+ 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));
22927
+ }
22928
+ savePlan(plan) {
22929
+ 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));
22930
+ }
22931
+ plan(id, device) {
22932
+ const row = this.db.query("SELECT body FROM home_plans WHERE id=? AND device=?").get(id, device);
22933
+ return row ? JSON.parse(row.body) : undefined;
22934
+ }
22935
+ claim(plan) {
22936
+ 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());
22937
+ if (result.changes !== 1)
22938
+ throw new Error("Preview expired or was already claimed by another process.");
22939
+ }
22940
+ unresolved(device) {
22941
+ 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));
22942
+ }
22943
+ plans(device) {
22944
+ 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));
22945
+ return [
22946
+ ...new Map([...recent, ...this.unresolved(device)].map((p) => [p.id, p])).values()
22947
+ ].sort((a, b) => b.createdAt - a.createdAt);
22948
+ }
22949
+ }
22950
+ var pending2;
22951
+ function homeStore() {
22952
+ return pending2 ??= (async () => {
22953
+ mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
22954
+ const { Database } = await import("bun:sqlite");
22955
+ const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
22956
+ db.run("PRAGMA journal_mode=WAL");
22957
+ db.run("PRAGMA busy_timeout=5000");
22958
+ return new HomeStore(db);
22959
+ })().catch((e) => {
22960
+ pending2 = undefined;
22961
+ throw e;
22962
+ });
22963
+ }
22964
+
22965
+ // src/home/policies.ts
22966
+ function buildPolicy(id, input, facts) {
22967
+ input = { ...input, mac: input.mac.toUpperCase() };
22968
+ if (!isYes(facts.deviceMode.scheduler))
22969
+ throw new Error("Router device-mode must explicitly allow scheduler execution for automatic expiry.");
22970
+ const candidates = facts.leases.filter((l) => l["mac-address"]?.toUpperCase() === input.mac);
22971
+ const lease = candidates[0];
22972
+ if (candidates.length !== 1 || !lease || isYes(lease.dynamic) || /D/.test(lease.flags ?? "") || !enabled2(lease) || lease.status !== "bound" || !lease.address)
22973
+ throw new Error("This control requires exactly one bound, static DHCP lease. Pin the client's IP in Clients first.");
22974
+ if (facts.leases.some((l) => l !== lease && (l.address === lease.address || l["active-address"] === lease.address)))
22975
+ throw new Error("The client IP is ambiguous.");
22976
+ if (lease["active-address"] && lease["active-address"] !== lease.address)
22977
+ throw new Error("The client lease changed; reconnect it before continuing.");
22978
+ if (lease["active-mac-address"] && lease["active-mac-address"].toUpperCase() !== input.mac)
22979
+ throw new Error("The active client MAC does not match its reservation.");
22980
+ if (facts.addresses.some((r) => r.address?.split("/")[0] === lease.address))
22981
+ throw new Error("Cannot target a router address.");
22982
+ if (facts.filters.some((r) => enabled2(r) && r.action === "fasttrack-connection") || facts.connections.some((r) => isYes(r.fasttrack) || /F/.test(r.flags ?? "")))
22983
+ 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.");
22984
+ if (input.action === "pause" && !isYes(facts.ipv6["disable-ipv6"]) && facts.ipv6.forward !== "no" && facts.ipv6.forward !== "false")
22985
+ throw new Error("IPv6 forwarding is enabled or unknown. An IPv4-only pause could be bypassed; use a dual-stack policy instead.");
22986
+ const tag = `mcp-home-${id}`, ip = lease.address;
22987
+ const setup = [], activate = [], revert = [];
22988
+ let queueBefore;
22989
+ const warnings = [
22990
+ "Only this reserved IPv4 client is targeted. Other configuration is left in place.",
22991
+ "The router expires this policy even when the dashboard is closed. Scheduler cleanup can take up to 30 seconds. Reboot ends the policy.",
22992
+ "Existing connections may disconnect. Review before applying; this is not a speed guarantee."
22993
+ ];
22994
+ const manage = (path) => {
22995
+ activate.push(new Cmd(`${path} enable ${tagSelector(tag)}`).build());
22996
+ revert.push(new Cmd(`${path} remove ${tagSelector(tag)}`).build());
22997
+ };
22998
+ if (input.action === "pause") {
22999
+ for (const direction of ["src", "dst"])
23000
+ 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());
23001
+ manage("/ip firewall filter");
23002
+ warnings.push("Pauses all routed traffic for this IP, including routed LAN traffic; router management and same-bridge traffic are not blocked.");
23003
+ } else if (input.action === "route") {
23004
+ 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)))
23005
+ throw new Error("Select an enabled FIB table with an active default route. This feature does not create WANs or VPNs.");
23006
+ if (facts.mangle.some((r) => enabled2(r) && r.action === "mark-routing"))
23007
+ throw new Error("Existing routing marks require an administrator review; this control will not override them.");
23008
+ const exclusions = new Set([
23009
+ "10.0.0.0/8",
23010
+ "172.16.0.0/12",
23011
+ "192.168.0.0/16",
23012
+ "100.64.0.0/10",
23013
+ "127.0.0.0/8",
23014
+ "169.254.0.0/16",
23015
+ "224.0.0.0/4",
23016
+ "255.255.255.255"
23017
+ ]);
23018
+ for (const a of facts.addresses)
23019
+ if (a.address)
23020
+ exclusions.add(a.address);
23021
+ for (const prefix of exclusions)
23022
+ setup.push(new Cmd("/ip firewall address-list add").set("list", `${tag}-local`).set("address", prefix).set("comment", tag).build());
23023
+ 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());
23024
+ manage("/ip firewall mangle");
23025
+ 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.");
23026
+ } else {
23027
+ const queues = facts.queues.filter((q) => q.target === `${ip}/32` && enabled2(q));
23028
+ const q = queues[0], parent = facts.queues.find((r) => r.name === q?.parent && enabled2(r));
23029
+ 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 ?? ""))
23030
+ 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.");
23031
+ if (facts.queues.some((r) => r.parent === q.name))
23032
+ throw new Error("Only leaf queues can receive meeting priority.");
23033
+ if (q.priority === "1/1")
23034
+ throw new Error("This client already has the highest queue priority.");
23035
+ queueBefore = { name: q.name, target: q.target, parent: q.parent, priority: q.priority };
23036
+ const selector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority=${quoteValue(q.priority)}]`;
23037
+ activate.push(new Cmd(`/queue simple set ${selector}`).set("priority", "1/1").build());
23038
+ const restoreSelector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority="1/1"]`;
23039
+ revert.push(new Cmd(`/queue simple set ${restoreSelector}`).set("priority", q.priority).build());
23040
+ 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.");
23041
+ }
23042
+ const generated = temporaryCommands(id, input, ip, setup, activate, revert);
23043
+ if (generated.commands.length > 40)
23044
+ throw new Error("This router needs too many policy objects for a bounded Safe Mode change. Ask an administrator to review it.");
23045
+ const stable = JSON.stringify(facts, (key, value) => key === "#" ? undefined : value);
23046
+ return {
23047
+ ip,
23048
+ ...generated,
23049
+ warnings,
23050
+ queueBefore,
23051
+ fingerprint: createHash2("sha256").update(stable).digest("hex")
23052
+ };
23053
+ }
23054
+ async function policyFacts(ctx, read = executeMikrotikCommand) {
23055
+ const fasttrackCount = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx, read)).trim();
23056
+ if (!/^\d+$/.test(fasttrackCount))
23057
+ throw new Error("Cannot establish whether FastTrack connections remain active.");
23058
+ return {
23059
+ leases: await rows("/ip dhcp-server lease", "address,active-address,mac-address,active-mac-address,dynamic,disabled,status", ctx, read),
23060
+ filters: await rows("/ip firewall filter", "chain,action,disabled,comment", ctx, read),
23061
+ connections: Number(fasttrackCount) > 0 ? [{ fasttrack: "yes" }] : [],
23062
+ mangle: await rows("/ip firewall mangle", "chain,action,disabled,comment", ctx, read),
23063
+ queues: await rows("/queue simple", "name,target,parent,priority,max-limit,packet-marks,disabled", ctx, read),
23064
+ tables: await rows("/routing table", "name,fib,disabled", ctx, read),
23065
+ routes: await rows("/ip route", "dst-address,routing-table,active,disabled,gateway", ctx, read),
23066
+ addresses: await rows("/ip address", "address,interface", ctx, read),
23067
+ ipv6: parseKeyValues(await checkedRead("/ipv6 settings print", ctx, read)),
23068
+ deviceMode: parseKeyValues(await checkedRead("/system device-mode print", ctx, read))
23069
+ };
23070
+ }
23071
+ var busy3 = new Set;
23072
+ async function exclusive(device, work) {
23073
+ if (busy3.has(device))
23074
+ throw new Error("Another Home Internet operation is in progress for this router.");
23075
+ busy3.add(device);
23076
+ try {
23077
+ return await work();
23078
+ } finally {
23079
+ busy3.delete(device);
23080
+ }
23081
+ }
23082
+ async function previewPolicy(input, ctx) {
23083
+ const a = policyInput.parse(input), device = resolveDeviceName(ctx.device);
23084
+ a.mac = a.mac.toUpperCase();
23085
+ assertDeviceAccess([device], "preview_home_policy", "WRITE");
23086
+ return exclusive(device, async () => {
23087
+ const id = randomUUID2();
23088
+ const plan = {
23089
+ id,
23090
+ device,
23091
+ input: a,
23092
+ createdAt: Date.now(),
23093
+ previewExpiresAt: Date.now() + 300000,
23094
+ status: "preview",
23095
+ ...buildPolicy(id, a, await policyFacts(ctx))
23096
+ };
23097
+ (await homeStore()).savePlan(plan);
23098
+ return plan;
23099
+ });
23100
+ }
23101
+ async function applyPolicy(id, confirm, ctx) {
23102
+ const device = resolveDeviceName(ctx.device);
23103
+ assertDeviceAccess([device], "apply_home_policy", "WRITE");
23104
+ if (!confirm)
23105
+ throw new Error("Review the preview and explicitly confirm before applying.");
23106
+ return exclusive(device, async () => {
23107
+ const store = await homeStore(), plan = store.plan(id, device);
23108
+ if (!plan || plan.status !== "preview" || plan.previewExpiresAt < Date.now())
23109
+ throw new Error("Preview expired, already used, or belongs to another router.");
23110
+ if (store.unresolved(device).some((p) => p.input.mac === plan.input.mac && ["applying", "scheduled", "active", "uncertain"].includes(p.status)))
23111
+ throw new Error("Undo or reconcile the previous policy for this device first.");
23112
+ const fresh = buildPolicy(id, plan.input, await policyFacts(ctx));
23113
+ if (fresh.fingerprint !== plan.fingerprint)
23114
+ throw new Error("Router state changed after the preview. Create a fresh preview.");
23115
+ const safe = getSafeModeManager(device);
23116
+ if (safe.isActive)
23117
+ throw new Error("An existing Safe Mode session is active; finish it before applying a Home Internet policy.");
23118
+ plan.snapshot = await captureSnapshot(ctx, `Before Home Internet ${plan.input.action}`, true);
23119
+ plan.status = "applying";
23120
+ store.claim(plan);
23121
+ let owned = false;
23122
+ try {
23123
+ const status = await safe.enable();
23124
+ if (!status.startsWith("Safe mode ENABLED"))
23125
+ throw new Error("Could not acquire a new Safe Mode session.");
23126
+ owned = true;
23127
+ const lockedFacts = await policyFacts(ctx);
23128
+ if (buildPolicy(id, plan.input, lockedFacts).fingerprint !== plan.fingerprint)
23129
+ throw new Error("Configuration changed while acquiring Safe Mode; create a new preview.");
23130
+ const started = Date.now();
23131
+ for (const command of plan.commands) {
23132
+ if (Date.now() - started > 120000)
23133
+ throw new Error("Policy apply exceeded its time budget.");
23134
+ await checkedRead(command, ctx);
23135
+ }
23136
+ const tag = `mcp-home-${id}`;
23137
+ const count = (await checkedRead(new Cmd("/system scheduler print count-only").raw(`where comment=${quoteValue(tag)}`).build(), ctx)).trim();
23138
+ if (count !== "2")
23139
+ throw new Error("Router-side expiry could not be verified.");
23140
+ const parsed = (await checkedRead(`:put [:typeof [:parse [/system scheduler get [find where name=${quoteValue(tag)}] on-event]]]`, ctx)).trim();
23141
+ if (parsed !== "code")
23142
+ throw new Error("Router could not compile the expiry script.");
23143
+ await verifyPolicyObjects(plan, lockedFacts, ctx);
23144
+ await checkedRead("/system identity print", ctx);
23145
+ const outcome = await safe.commit();
23146
+ if (!outcome.ok)
23147
+ throw new Error("Commit outcome is uncertain; inspect the router before retrying.");
23148
+ owned = false;
23149
+ plan.startsAt = started + plan.input.startInMinutes * 60000;
23150
+ plan.endsAt = plan.startsAt + plan.input.minutes * 60000;
23151
+ plan.status = plan.input.startInMinutes ? "scheduled" : "active";
23152
+ store.savePlan(plan);
23153
+ return plan;
23154
+ } catch (error) {
23155
+ if (owned)
23156
+ await safe.rollback().catch(() => {});
23157
+ plan.status = "uncertain";
23158
+ plan.error = error instanceof Error ? error.message : "Policy operation failed";
23159
+ store.savePlan(plan);
23160
+ throw new Error(`Policy not confirmed: ${plan.error}. Inspect/undo policy ${id}; do not blindly retry.`);
23161
+ }
23162
+ });
23163
+ }
23164
+ async function undoPolicy(id, confirm, ctx) {
23165
+ const device = resolveDeviceName(ctx.device);
23166
+ assertDeviceAccess([device], "undo_home_policy", "WRITE");
23167
+ if (!confirm)
23168
+ throw new Error("Explicit confirmation is required to undo a policy.");
23169
+ return exclusive(device, async () => {
23170
+ const store = await homeStore(), plan = store.plan(id, device);
23171
+ if (!plan || plan.status === "preview")
23172
+ throw new Error("No applied policy on this router.");
23173
+ if (plan.status === "undone")
23174
+ return plan;
23175
+ const safe = getSafeModeManager(device);
23176
+ if (safe.isActive)
23177
+ throw new Error("Finish the active Safe Mode session first.");
23178
+ const status = await safe.enable();
23179
+ if (!status.startsWith("Safe mode ENABLED"))
23180
+ throw new Error("Could not acquire Safe Mode.");
23181
+ try {
23182
+ await checkedRead(new Cmd(`/system scheduler disable ${tagSelector(`mcp-home-${id}`)}`).build(), ctx);
23183
+ for (const cmd of plan.undo)
23184
+ await checkedRead(cmd, ctx);
23185
+ if (plan.input.action === "priority") {
23186
+ const expected = plan.queueBefore;
23187
+ if (!expected)
23188
+ throw new Error("Missing queue restoration evidence; reconcile this policy manually.");
23189
+ const current = await rows("/queue simple", "name,target,parent,priority", ctx);
23190
+ const matching = current.filter((q) => q.name === expected.name && q.target === expected.target && q.parent === expected.parent);
23191
+ if (matching.length !== 1 || matching[0].priority !== expected.priority)
23192
+ throw new Error("Queue restoration was not verified. External queue changes require manual reconciliation.");
23193
+ }
23194
+ for (const path of [
23195
+ "/system scheduler",
23196
+ "/ip firewall address-list",
23197
+ "/ip firewall filter",
23198
+ "/ip firewall mangle"
23199
+ ]) {
23200
+ const remaining = (await checkedRead(new Cmd(`${path} print count-only`).raw(`where comment=${quoteValue(`mcp-home-${id}`)}`).build(), ctx)).trim();
23201
+ if (remaining !== "0")
23202
+ throw new Error("Policy cleanup could not be verified; the undo was not committed.");
23203
+ }
23204
+ const committed = await safe.commit();
23205
+ if (!committed.ok)
23206
+ throw new Error("Undo commit could not be confirmed");
23207
+ plan.status = "undone";
23208
+ store.savePlan(plan);
23209
+ return plan;
23210
+ } catch (e) {
23211
+ await safe.rollback().catch(() => {});
23212
+ throw e;
23213
+ }
23214
+ });
23215
+ }
23216
+ async function verifyPolicyObjects(plan, before, ctx) {
23217
+ const tag = `mcp-home-${plan.id}`;
23218
+ const marker = (await checkedRead(new Cmd("/ip firewall address-list print count-only").raw(`where list=${quoteValue(`${tag}-end`)}`).build(), ctx)).trim();
23219
+ if (marker !== "1")
23220
+ throw new Error("Expiry marker could not be verified.");
23221
+ if (plan.input.action === "priority") {
23222
+ const old = before.queues.find((q) => q.target === `${plan.ip}/32` && enabled2(q));
23223
+ const current = await rows("/queue simple", "name,target,parent,priority,max-limit,disabled", ctx);
23224
+ const q = current.find((r) => r.name === old.name && r.target === old.target && r.parent === old.parent);
23225
+ if (!q || q.priority !== (plan.input.startInMinutes ? old.priority : "1/1"))
23226
+ throw new Error("Meeting queue priority was not verified.");
23227
+ } else {
23228
+ const path = plan.input.action === "pause" ? "/ip firewall filter" : "/ip firewall mangle";
23229
+ 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);
23230
+ const owned = current.filter((r) => r.comment === tag);
23231
+ if (owned.length !== (plan.input.action === "pause" ? 2 : 1) || owned.some((r) => enabled2(r) === plan.input.startInMinutes > 0))
23232
+ throw new Error("Policy rules were not verified in their expected state.");
23233
+ if (plan.input.action === "pause") {
23234
+ 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)
23235
+ throw new Error("Pause rule targeting could not be verified.");
23236
+ } 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`)) {
23237
+ throw new Error("Path selection targeting could not be verified.");
23238
+ }
23239
+ }
23240
+ }
23241
+
23242
+ // src/tools/home-internet.ts
23243
+ var homeInternetTools = [
23244
+ defineTool({
23245
+ name: "diagnose_home_internet",
23246
+ title: "Why Is My Internet Slow?",
23247
+ annotations: READ,
23248
+ 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.",
23249
+ inputSchema: diagnosisInput.shape,
23250
+ handler: async (a, ctx) => JSON.stringify(await diagnoseInternet(a, ctx))
23251
+ }),
23252
+ defineTool({
23253
+ name: "compare_home_paths",
23254
+ title: "Compare Internet Paths",
23255
+ annotations: READ,
23256
+ 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.",
23257
+ inputSchema: compareInput.shape,
23258
+ handler: async (a, ctx) => JSON.stringify(await comparePaths(a, ctx))
23259
+ }),
23260
+ defineTool({
23261
+ name: "get_home_internet",
23262
+ title: "Read Household Internet Workspace",
23263
+ annotations: READ,
23264
+ 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.",
23265
+ inputSchema: {},
23266
+ async handler(_a, ctx) {
23267
+ const device = resolveDeviceName(ctx.device);
23268
+ assertDeviceAccess([device], "get_home_internet", "READ");
23269
+ const store = await homeStore();
23270
+ return JSON.stringify({
23271
+ device,
23272
+ clients: store.clients(device),
23273
+ policies: store.plans(device),
23274
+ statusNote: "Saved status only. A passed expiry time is not a verified cleanup result; Undo can reconcile owned objects."
23275
+ });
23276
+ }
23277
+ }),
23278
+ defineTool({
23279
+ name: "refresh_home_devices",
23280
+ title: "Discover Household Devices",
23281
+ annotations: WRITE,
23282
+ 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.",
23283
+ inputSchema: {},
23284
+ async handler(_a, ctx) {
23285
+ const device = resolveDeviceName(ctx.device);
23286
+ assertDeviceAccess([device], "refresh_home_devices", "WRITE");
23287
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,host-name,status", ctx);
23288
+ const tables = await rows("/routing table", "name,fib,disabled", ctx);
23289
+ const store = await homeStore(), old = store.clients(device), now = Date.now();
23290
+ const seen = new Set;
23291
+ for (const r of leases) {
23292
+ const parsed = macInput.safeParse(r["mac-address"]);
23293
+ if (!parsed.success)
23294
+ continue;
23295
+ const mac = parsed.data.toUpperCase(), prior = old.find((c) => c.mac === mac);
23296
+ seen.add(mac);
23297
+ store.saveClient(device, {
23298
+ mac,
23299
+ ip: r.address ?? "",
23300
+ hostname: r["host-name"] ?? "",
23301
+ name: prior?.name ?? "",
23302
+ person: prior?.person ?? "",
23303
+ firstSeen: prior?.firstSeen ?? now,
23304
+ lastSeen: now,
23305
+ acknowledged: prior?.acknowledged ?? old.length === 0,
23306
+ present: r.status === "bound"
23307
+ });
23308
+ }
23309
+ for (const client of old)
23310
+ if (!seen.has(client.mac))
23311
+ store.saveClient(device, { ...client, present: false });
23312
+ return JSON.stringify({
23313
+ device,
23314
+ clients: store.clients(device),
23315
+ tables: tables.filter((t) => enabled2(t) && ["yes", "true"].includes(t.fib)).map((t) => t.name)
23316
+ });
23317
+ }
23318
+ }),
23319
+ defineTool({
23320
+ name: "name_home_device",
23321
+ title: "Name a Household Device",
23322
+ annotations: WRITE,
23323
+ 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.",
23324
+ inputSchema: {
23325
+ mac: macInput,
23326
+ name: string2().trim().max(80),
23327
+ person: string2().trim().max(80).default("")
23328
+ },
23329
+ async handler(a, ctx) {
23330
+ const device = resolveDeviceName(ctx.device);
23331
+ assertDeviceAccess([device], "name_home_device", "WRITE");
23332
+ const store = await homeStore(), client = store.clients(device).find((c) => c.mac === a.mac.toUpperCase());
23333
+ if (!client)
23334
+ throw new Error("Refresh household devices first.");
23335
+ const result = { ...client, name: a.name, person: a.person, acknowledged: true };
23336
+ store.saveClient(device, result);
23337
+ return JSON.stringify(result);
23338
+ }
23339
+ }),
23340
+ defineTool({
23341
+ name: "preview_home_policy",
23342
+ title: "Preview a Temporary Household Policy",
23343
+ annotations: WRITE,
23344
+ 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.",
23345
+ inputSchema: policyInput.shape,
23346
+ handler: async (a, ctx) => JSON.stringify(await previewPolicy(a, ctx))
23347
+ }),
23348
+ defineTool({
23349
+ name: "apply_home_policy",
23350
+ title: "Apply an Approved Household Policy",
23351
+ annotations: WRITE,
23352
+ 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.",
23353
+ inputSchema: { id: uuid2(), confirm: boolean2().default(false) },
23354
+ handler: async (a, ctx) => JSON.stringify(await applyPolicy(a.id, a.confirm, ctx))
23355
+ }),
23356
+ defineTool({
23357
+ name: "undo_home_policy",
23358
+ title: "Undo a Household Policy",
23359
+ annotations: WRITE,
23360
+ 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.",
23361
+ inputSchema: { id: uuid2(), confirm: boolean2().default(false) },
23362
+ handler: async (a, ctx) => JSON.stringify(await undoPolicy(a.id, a.confirm, ctx))
23363
+ })
23364
+ ];
23365
+
23366
+ // src/tools/service-contracts.ts
23367
+ import { randomUUID as randomUUID4 } from "crypto";
23368
+
23369
+ // src/service-contracts/store.ts
23370
+ import { mkdirSync as mkdirSync6 } from "fs";
23371
+ import { dirname as dirname6 } from "path";
22484
23372
  class ContractStore {
22485
23373
  db;
22486
23374
  constructor(db) {
@@ -22506,23 +23394,23 @@ class ContractStore {
22506
23394
  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
23395
  }
22508
23396
  }
22509
- var pending2;
23397
+ var pending3;
22510
23398
  function contractStore() {
22511
- pending2 ??= (async () => {
22512
- mkdirSync4(dirname4(DEFAULT_SNAPSHOT_DB), { recursive: true });
23399
+ pending3 ??= (async () => {
23400
+ mkdirSync6(dirname6(DEFAULT_SNAPSHOT_DB), { recursive: true });
22513
23401
  const { Database } = await import("bun:sqlite");
22514
23402
  const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
22515
23403
  db.run("PRAGMA journal_mode = WAL");
22516
23404
  return new ContractStore(db);
22517
23405
  })().catch((e) => {
22518
- pending2 = undefined;
23406
+ pending3 = undefined;
22519
23407
  throw e;
22520
23408
  });
22521
- return pending2;
23409
+ return pending3;
22522
23410
  }
22523
23411
 
22524
23412
  // src/service-contracts/run.ts
22525
- import { randomUUID as randomUUID2 } from "crypto";
23413
+ import { randomUUID as randomUUID3 } from "crypto";
22526
23414
 
22527
23415
  // src/policy/parse.ts
22528
23416
  function normalizeSection(path) {
@@ -23829,8 +24717,8 @@ function diffTraces(before, after) {
23829
24717
  }
23830
24718
 
23831
24719
  // src/sim/suites.ts
23832
- import { mkdirSync as mkdirSync5 } from "fs";
23833
- import { dirname as dirname5 } from "path";
24720
+ import { mkdirSync as mkdirSync7 } from "fs";
24721
+ import { dirname as dirname7 } from "path";
23834
24722
  var SCHEMA2 = [
23835
24723
  `CREATE TABLE IF NOT EXISTS sim_suites (
23836
24724
  id TEXT PRIMARY KEY,
@@ -23876,16 +24764,16 @@ class SqliteSuiteStore {
23876
24764
  });
23877
24765
  }
23878
24766
  }
23879
- var storePromise3 = null;
24767
+ var storePromise4 = null;
23880
24768
  async function store2() {
23881
- storePromise3 ??= (async () => {
24769
+ storePromise4 ??= (async () => {
23882
24770
  try {
23883
- mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
24771
+ mkdirSync7(dirname7(DEFAULT_SNAPSHOT_DB), { recursive: true });
23884
24772
  } catch {}
23885
24773
  const { Database } = await import("bun:sqlite");
23886
24774
  return new SqliteSuiteStore(new Database(DEFAULT_SNAPSHOT_DB, { create: true }));
23887
24775
  })();
23888
- return storePromise3;
24776
+ return storePromise4;
23889
24777
  }
23890
24778
  async function listSuites() {
23891
24779
  try {
@@ -23917,30 +24805,6 @@ async function saveSuite(input) {
23917
24805
  return suite;
23918
24806
  }
23919
24807
 
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
24808
  // src/service-contracts/probe.ts
23945
24809
  import { Resolver } from "dns/promises";
23946
24810
  import { connect, isIP } from "net";
@@ -24103,7 +24967,7 @@ async function evaluateContract(contract, io, simulationExport) {
24103
24967
  }
24104
24968
  }
24105
24969
  return {
24106
- id: randomUUID2(),
24970
+ id: randomUUID3(),
24107
24971
  contractId: contract.id,
24108
24972
  device: contract.device,
24109
24973
  startedAt,
@@ -24228,7 +25092,7 @@ var serviceContractTools = [
24228
25092
  const args = contractInput.parse(a);
24229
25093
  if (args.checks.some((c) => !getConfig().serviceProbes.targets[c.target]))
24230
25094
  throw new Error("Contract references an unapproved target. Ask the administrator to configure it.");
24231
- const contract = { ...args, id: randomUUID3(), device, createdAt: Date.now() };
25095
+ const contract = { ...args, id: randomUUID4(), device, createdAt: Date.now() };
24232
25096
  (await contractStore()).save(contract);
24233
25097
  return JSON.stringify(contract);
24234
25098
  }
@@ -24272,146 +25136,6 @@ var serviceContractTools = [
24272
25136
  })
24273
25137
  ];
24274
25138
 
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
25139
  // src/paths/round-trip.ts
24416
25140
  var hop = object({
24417
25141
  device: string2().min(1).max(128),
@@ -24622,21 +25346,21 @@ import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
24622
25346
 
24623
25347
  // src/paths.ts
24624
25348
  import { existsSync } from "fs";
24625
- import { join as join2, dirname as dirname7 } from "path";
25349
+ import { join as join2, dirname as dirname8 } from "path";
24626
25350
  import { fileURLToPath } from "url";
24627
25351
  var meta3 = import.meta;
24628
- var HERE = meta3.dir ?? meta3.dirname ?? dirname7(fileURLToPath(import.meta.url));
25352
+ var HERE = meta3.dir ?? meta3.dirname ?? dirname8(fileURLToPath(import.meta.url));
24629
25353
  function findRoot(start) {
24630
25354
  let dir = start;
24631
25355
  for (let i = 0;i < 12; i++) {
24632
25356
  if (existsSync(join2(dir, "package.json")))
24633
25357
  return dir;
24634
- const parent = dirname7(dir);
25358
+ const parent = dirname8(dir);
24635
25359
  if (parent === dir)
24636
25360
  break;
24637
25361
  dir = parent;
24638
25362
  }
24639
- return dirname7(start);
25363
+ return dirname8(start);
24640
25364
  }
24641
25365
  var ROOT = findRoot(HERE);
24642
25366
  var PROMPTS_DIR = join2(ROOT, "prompts");
@@ -24893,7 +25617,7 @@ async function checkDiskSpace(ctx) {
24893
25617
  // src/backups/vault.ts
24894
25618
  import {
24895
25619
  existsSync as existsSync2,
24896
- mkdirSync as mkdirSync7,
25620
+ mkdirSync as mkdirSync8,
24897
25621
  readFileSync as readFileSync4,
24898
25622
  readdirSync,
24899
25623
  renameSync,
@@ -24940,7 +25664,7 @@ function readBackup(name) {
24940
25664
  }
24941
25665
  function writeBackup(name, content) {
24942
25666
  const dir = backupDir();
24943
- mkdirSync7(dir, { recursive: true });
25667
+ mkdirSync8(dir, { recursive: true });
24944
25668
  let final = safeName(name);
24945
25669
  if (existsSync2(join4(dir, final))) {
24946
25670
  const dot = final.lastIndexOf(".");
@@ -24956,7 +25680,7 @@ function writeBackup(name, content) {
24956
25680
  }
24957
25681
  function writeBinaryBackup(name, data) {
24958
25682
  const dir = backupDir();
24959
- mkdirSync7(dir, { recursive: true });
25683
+ mkdirSync8(dir, { recursive: true });
24960
25684
  let final = safeName(name);
24961
25685
  if (existsSync2(join4(dir, final))) {
24962
25686
  const dot = final.lastIndexOf(".");
@@ -28183,11 +28907,11 @@ No differences \u2014 the live configuration matches the golden baseline.`);
28183
28907
  }
28184
28908
 
28185
28909
  // src/tools/config-drift.ts
28186
- var storePromise4 = null;
28910
+ var storePromise5 = null;
28187
28911
  function store3() {
28188
- if (!storePromise4)
28189
- storePromise4 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
28190
- return storePromise4;
28912
+ if (!storePromise5)
28913
+ storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
28914
+ return storePromise5;
28191
28915
  }
28192
28916
  function buildExport(opts) {
28193
28917
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -28395,11 +29119,11 @@ New: ${describeBaseline(snap)}${notesLine}`;
28395
29119
  ];
28396
29120
 
28397
29121
  // src/tools/config-snapshot.ts
28398
- var storePromise5 = null;
28399
- function snapshots() {
28400
- if (!storePromise5)
28401
- storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
28402
- return storePromise5;
29122
+ var storePromise6 = null;
29123
+ function snapshots2() {
29124
+ if (!storePromise6)
29125
+ storePromise6 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
29126
+ return storePromise6;
28403
29127
  }
28404
29128
  function exportCommand(opts) {
28405
29129
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -28456,7 +29180,7 @@ var configSnapshotTools = [
28456
29180
  });
28457
29181
  const meta = parseExportMeta(body);
28458
29182
  const sha = contentSha(normalizeExport(body));
28459
- const store = await snapshots();
29183
+ const store = await snapshots2();
28460
29184
  const prev = store.latest(device);
28461
29185
  if (prev && prev.sha === sha && !a.force) {
28462
29186
  return `No configuration change since the last snapshot \u2014 nothing stored.
@@ -28492,7 +29216,7 @@ ${drift}`;
28492
29216
  },
28493
29217
  async handler(a, ctx) {
28494
29218
  const device = resolveDeviceName(ctx.device);
28495
- const store = await snapshots();
29219
+ const store = await snapshots2();
28496
29220
  const rows = store.list(device, a.limit, false);
28497
29221
  if (rows.length === 0) {
28498
29222
  return `No configuration snapshots stored for '${device}'. Capture one with capture_config_snapshot.`;
@@ -28515,7 +29239,7 @@ ${lines}`;
28515
29239
  include_body: boolean2().default(true)
28516
29240
  },
28517
29241
  async handler(a, ctx) {
28518
- const store = await snapshots();
29242
+ const store = await snapshots2();
28519
29243
  const snap = store.get(a.id);
28520
29244
  if (!snap)
28521
29245
  return `Snapshot '${a.id}' not found.`;
@@ -28543,7 +29267,7 @@ ${snap.body}
28543
29267
  },
28544
29268
  async handler(a, ctx) {
28545
29269
  const device = resolveDeviceName(ctx.device);
28546
- const store = await snapshots();
29270
+ const store = await snapshots2();
28547
29271
  const from = await resolveRef(store, a.from, device, ctx);
28548
29272
  const to = await resolveRef(store, a.to, device, ctx);
28549
29273
  const result = diffLines(normalizeExport(from.body), normalizeExport(to.body), {
@@ -28583,7 +29307,7 @@ ${result.unified}`;
28583
29307
  ids: array(string2()).min(1)
28584
29308
  },
28585
29309
  async handler(a) {
28586
- const store = await snapshots();
29310
+ const store = await snapshots2();
28587
29311
  const removed = store.delete(a.ids);
28588
29312
  if (removed === 0)
28589
29313
  return `No snapshots removed (none of the given ids matched).`;
@@ -28894,10 +29618,10 @@ ${created.join(`
28894
29618
  import * as ipaddr2 from "ipaddr.js";
28895
29619
 
28896
29620
  // src/schedule/identity.ts
28897
- import { createHash as createHash2 } from "crypto";
29621
+ import { createHash as createHash3 } from "crypto";
28898
29622
  function stableId(prefix, parts) {
28899
29623
  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);
29624
+ const digest = createHash3("sha256").update(material, "utf8").digest("hex").slice(0, 12);
28901
29625
  return `${prefix}:${digest}`;
28902
29626
  }
28903
29627
  function ruleFingerprint(rule) {
@@ -30223,7 +30947,7 @@ var cache2 = null;
30223
30947
  async function gateway() {
30224
30948
  if (cache2)
30225
30949
  return cache2;
30226
- const { moduleCatalog } = await import("./shared/cli-m947aqb2.js");
30950
+ const { moduleCatalog } = await import("./shared/cli-hfeatjkc.js");
30227
30951
  const forIndex = [];
30228
30952
  const byName = new Map;
30229
30953
  for (const mod of moduleCatalog) {
@@ -32451,34 +33175,6 @@ No findings \u2014 the device passes every hardening check. \u2713`;
32451
33175
  ${body}`;
32452
33176
  }
32453
33177
 
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
33178
  // src/tools/security-hardening.ts
32483
33179
  async function fetchSecurityState(ctx) {
32484
33180
  const [
@@ -33211,7 +33907,7 @@ function evaluatePolicies(policies, model, opts = {}) {
33211
33907
 
33212
33908
  // src/policy/load.ts
33213
33909
  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";
33910
+ import { dirname as dirname9, isAbsolute, join as join5, resolve as resolve3 } from "path";
33215
33911
 
33216
33912
  // src/policy/schema.ts
33217
33913
  var MAX_REGEX_LENGTH = 200;
@@ -33334,7 +34030,7 @@ function validatePolicyText(text) {
33334
34030
  var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
33335
34031
  function expand(pattern, cwd) {
33336
34032
  const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
33337
- const base = dirname8(absolute);
34033
+ const base = dirname9(absolute);
33338
34034
  const leaf = absolute.slice(base.length + 1);
33339
34035
  if (!leaf.includes("*")) {
33340
34036
  try {
@@ -50054,8 +50750,8 @@ function liveTxnUpdates() {
50054
50750
  }
50055
50751
 
50056
50752
  // src/txn/store.ts
50057
- import { mkdirSync as mkdirSync8 } from "fs";
50058
- import { dirname as dirname9 } from "path";
50753
+ import { mkdirSync as mkdirSync9 } from "fs";
50754
+ import { dirname as dirname10 } from "path";
50059
50755
  function toRecord2(txn, ts, label) {
50060
50756
  return {
50061
50757
  id: txn.id,
@@ -50191,7 +50887,7 @@ class SqliteTxnStore {
50191
50887
  async function openTxnStore(path) {
50192
50888
  if (path !== ":memory:") {
50193
50889
  try {
50194
- mkdirSync8(dirname9(path), { recursive: true });
50890
+ mkdirSync9(dirname10(path), { recursive: true });
50195
50891
  } catch {}
50196
50892
  }
50197
50893
  const { Database } = await import("bun:sqlite");
@@ -51254,8 +51950,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
51254
51950
  }
51255
51951
 
51256
51952
  // src/rollout/store.ts
51257
- import { mkdirSync as mkdirSync9 } from "fs";
51258
- import { dirname as dirname10 } from "path";
51953
+ import { mkdirSync as mkdirSync10 } from "fs";
51954
+ import { dirname as dirname11 } from "path";
51259
51955
  function toRecord3(rollout, ts, opts = {}) {
51260
51956
  return {
51261
51957
  id: rollout.id,
@@ -51388,7 +52084,7 @@ class SqliteRolloutStore {
51388
52084
  async function openRolloutStore(path) {
51389
52085
  if (path !== ":memory:") {
51390
52086
  try {
51391
- mkdirSync9(dirname10(path), { recursive: true });
52087
+ mkdirSync10(dirname11(path), { recursive: true });
51392
52088
  } catch {}
51393
52089
  }
51394
52090
  const { Database } = await import("bun:sqlite");
@@ -52104,8 +52800,8 @@ var JobSchema = object({
52104
52800
  });
52105
52801
 
52106
52802
  // src/schedule/store.ts
52107
- import { mkdirSync as mkdirSync10 } from "fs";
52108
- import { dirname as dirname11 } from "path";
52803
+ import { mkdirSync as mkdirSync11 } from "fs";
52804
+ import { dirname as dirname12 } from "path";
52109
52805
  var SCHEMA3 = [
52110
52806
  `CREATE TABLE IF NOT EXISTS schedule_jobs (
52111
52807
  id TEXT PRIMARY KEY,
@@ -52247,7 +52943,7 @@ class SqliteScheduleStore {
52247
52943
  async function openScheduleStore(path) {
52248
52944
  if (path !== ":memory:") {
52249
52945
  try {
52250
- mkdirSync10(dirname11(path), { recursive: true });
52946
+ mkdirSync11(dirname12(path), { recursive: true });
52251
52947
  } catch {}
52252
52948
  }
52253
52949
  const { Database } = await import("bun:sqlite");
@@ -52449,7 +53145,7 @@ var riskByTool = null;
52449
53145
  async function riskIndex() {
52450
53146
  if (riskByTool)
52451
53147
  return riskByTool;
52452
- const { moduleCatalog } = await import("./shared/cli-m947aqb2.js");
53148
+ const { moduleCatalog } = await import("./shared/cli-hfeatjkc.js");
52453
53149
  const index = new Map;
52454
53150
  for (const mod of moduleCatalog) {
52455
53151
  for (const tool of mod.tools)
@@ -54671,7 +55367,7 @@ async function readScanList(ctx, list = "port-scanners") {
54671
55367
  }
54672
55368
 
54673
55369
  // src/attack/correlate.ts
54674
- import { createHash as createHash3 } from "crypto";
55370
+ import { createHash as createHash4 } from "crypto";
54675
55371
  var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
54676
55372
  var STAGE_OF = {
54677
55373
  "port-scan": "recon",
@@ -54701,7 +55397,7 @@ var SEVERITY_RANK = {
54701
55397
  info: 4
54702
55398
  };
54703
55399
  function incidentId(source, dayBucket) {
54704
- const digest = createHash3("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
55400
+ const digest = createHash4("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
54705
55401
  return `atk_${digest}`;
54706
55402
  }
54707
55403
  function worst(values) {
@@ -54923,8 +55619,8 @@ function dedupe(events, seen) {
54923
55619
  }
54924
55620
 
54925
55621
  // src/attack/store.ts
54926
- import { mkdirSync as mkdirSync11 } from "fs";
54927
- import { dirname as dirname12 } from "path";
55622
+ import { mkdirSync as mkdirSync12 } from "fs";
55623
+ import { dirname as dirname13 } from "path";
54928
55624
  var SCHEMA4 = [
54929
55625
  `CREATE TABLE IF NOT EXISTS attack_incidents (
54930
55626
  id TEXT PRIMARY KEY,
@@ -55115,7 +55811,7 @@ class SqliteAttackStore {
55115
55811
  async function openAttackStore(path) {
55116
55812
  if (path !== ":memory:") {
55117
55813
  try {
55118
- mkdirSync11(dirname12(path), { recursive: true });
55814
+ mkdirSync12(dirname13(path), { recursive: true });
55119
55815
  } catch {}
55120
55816
  }
55121
55817
  const { Database } = await import("bun:sqlite");
@@ -55816,9 +56512,9 @@ ${result}`;
55816
56512
  ];
55817
56513
 
55818
56514
  // src/core/update-check.ts
55819
- import { existsSync as existsSync3, mkdirSync as mkdirSync12, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
56515
+ import { existsSync as existsSync3, mkdirSync as mkdirSync13, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
55820
56516
  import { homedir as homedir2 } from "os";
55821
- import { dirname as dirname13, join as join8 } from "path";
56517
+ import { dirname as dirname14, join as join8 } from "path";
55822
56518
 
55823
56519
  // src/version.ts
55824
56520
  import { readFileSync as readFileSync7 } from "fs";
@@ -55866,9 +56562,9 @@ function loadFileCacheSync() {
55866
56562
  }
55867
56563
  function saveFileCache(data) {
55868
56564
  try {
55869
- const dir = dirname13(CACHE_PATH);
56565
+ const dir = dirname14(CACHE_PATH);
55870
56566
  if (!existsSync3(dir))
55871
- mkdirSync12(dir, { recursive: true });
56567
+ mkdirSync13(dir, { recursive: true });
55872
56568
  writeFileSync2(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
55873
56569
  } catch {}
55874
56570
  }
@@ -61540,6 +62236,13 @@ ${lines.join(`
61540
62236
 
61541
62237
  // src/tools/index.ts
61542
62238
  var moduleCatalog2 = [
62239
+ {
62240
+ label: "Home Internet",
62241
+ slug: "home-internet",
62242
+ group: "System & Ops",
62243
+ description: "Plain-language internet diagnosis, household inventory and approved temporary client policies with bounded path comparisons.",
62244
+ tools: homeInternetTools
62245
+ },
61543
62246
  {
61544
62247
  label: "Multi-Router Round Trip",
61545
62248
  slug: "round-trip",
@@ -62571,7 +63274,7 @@ import { existsSync as existsSync5 } from "fs";
62571
63274
  import { spawn } from "child_process";
62572
63275
  import { readFileSync as readFileSync11 } from "fs";
62573
63276
  import { homedir as homedir5, networkInterfaces } from "os";
62574
- import { dirname as dirname19, join as join12 } from "path";
63277
+ import { dirname as dirname20, join as join12 } from "path";
62575
63278
  var {serve } = globalThis.Bun;
62576
63279
 
62577
63280
  // src/observability/modules.ts
@@ -62648,8 +63351,8 @@ function applyModuleToggle(filter, slug, enabled) {
62648
63351
  }
62649
63352
 
62650
63353
  // src/config-write.ts
62651
- import { mkdirSync as mkdirSync13, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
62652
- import { dirname as dirname14 } from "path";
63354
+ import { mkdirSync as mkdirSync14, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "fs";
63355
+ import { dirname as dirname15 } from "path";
62653
63356
  var SCHEMA_REF = "./schemas/config.schema.json";
62654
63357
  function mergeSecrets(incoming, current) {
62655
63358
  if (incoming === REDACTED) {
@@ -62681,7 +63384,7 @@ function backupName(path, ts) {
62681
63384
  return `${path}.bak-${ts}`;
62682
63385
  }
62683
63386
  function atomicWrite(path, text) {
62684
- mkdirSync13(dirname14(path), { recursive: true });
63387
+ mkdirSync14(dirname15(path), { recursive: true });
62685
63388
  const tmp = `${path}.tmp-${process.pid}`;
62686
63389
  writeFileSync3(tmp, text, "utf8");
62687
63390
  renameSync2(tmp, path);
@@ -62755,6 +63458,42 @@ async function investigationRoutes(req, url) {
62755
63458
  }
62756
63459
  }
62757
63460
 
63461
+ // src/observability/home-routes.ts
63462
+ var routes = {
63463
+ "GET /api/home-internet": "get_home_internet",
63464
+ "POST /api/home-internet/refresh": "refresh_home_devices",
63465
+ "POST /api/home-internet/name": "name_home_device",
63466
+ "POST /api/home-internet/diagnose": "diagnose_home_internet",
63467
+ "POST /api/home-internet/compare": "compare_home_paths",
63468
+ "POST /api/home-internet/preview": "preview_home_policy",
63469
+ "POST /api/home-internet/apply": "apply_home_policy",
63470
+ "POST /api/home-internet/undo": "undo_home_policy"
63471
+ };
63472
+ async function homeRoutes(req, url) {
63473
+ if (!url.pathname.startsWith("/api/home-internet"))
63474
+ return null;
63475
+ const tool = homeInternetTools.find((t) => t.name === routes[`${req.method} ${url.pathname}`]);
63476
+ if (!tool)
63477
+ return Response.json({ error: "Unsupported Home Internet route" }, { status: 405 });
63478
+ try {
63479
+ const device = url.searchParams.get("device");
63480
+ if (!device)
63481
+ throw new Error("Choose a router explicitly.");
63482
+ const input = req.method === "POST" ? JSON.parse(await readOperationBody(req)) : {};
63483
+ const result = await tool.handler(object(tool.inputSchema).strict().parse(input), createContext(undefined, device));
63484
+ return new Response(result, {
63485
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
63486
+ });
63487
+ } catch (e) {
63488
+ return Response.json({
63489
+ error: e instanceof ZodError ? "Invalid input. Check IP/MAC addresses, duration and required fields." : e instanceof Error ? e.message : "Home Internet operation failed."
63490
+ }, {
63491
+ status: e instanceof DashboardInputError ? e.status : 400,
63492
+ headers: { "cache-control": "no-store" }
63493
+ });
63494
+ }
63495
+ }
63496
+
62758
63497
  // src/observability/service-contract-routes.ts
62759
63498
  async function serviceContractRoutes(req, url) {
62760
63499
  if (!url.pathname.startsWith("/api/service-contracts"))
@@ -62910,7 +63649,7 @@ function createConfigAdmin(deps) {
62910
63649
  // src/observability/config-history.ts
62911
63650
  import {
62912
63651
  existsSync as existsSync4,
62913
- mkdirSync as mkdirSync14,
63652
+ mkdirSync as mkdirSync15,
62914
63653
  readFileSync as readFileSync9,
62915
63654
  readdirSync as readdirSync3,
62916
63655
  rmSync as rmSync2,
@@ -62962,7 +63701,7 @@ function deleteVersion(id) {
62962
63701
  }
62963
63702
  function recordVersion(config, kind, now, label) {
62964
63703
  const dir = historyDir();
62965
- mkdirSync14(dir, { recursive: true });
63704
+ mkdirSync15(dir, { recursive: true });
62966
63705
  let ts = now;
62967
63706
  while (existsSync4(join9(dir, `v${ts}.json`)))
62968
63707
  ts++;
@@ -63399,8 +64138,8 @@ function subscribeTraffic(device, fn) {
63399
64138
  }
63400
64139
 
63401
64140
  // src/observability/store.ts
63402
- import { mkdirSync as mkdirSync15 } from "fs";
63403
- import { dirname as dirname15 } from "path";
64141
+ import { mkdirSync as mkdirSync16 } from "fs";
64142
+ import { dirname as dirname16 } from "path";
63404
64143
  function rowToEvent2(r) {
63405
64144
  return {
63406
64145
  id: r.id,
@@ -63578,7 +64317,7 @@ class SqliteEventStore {
63578
64317
  async function openSqliteStore(path) {
63579
64318
  if (path !== ":memory:") {
63580
64319
  try {
63581
- mkdirSync15(dirname15(path), { recursive: true });
64320
+ mkdirSync16(dirname16(path), { recursive: true });
63582
64321
  } catch {}
63583
64322
  }
63584
64323
  const { Database } = await import("bun:sqlite");
@@ -63587,8 +64326,8 @@ async function openSqliteStore(path) {
63587
64326
  }
63588
64327
 
63589
64328
  // src/observability/capsman-store.ts
63590
- import { mkdirSync as mkdirSync16 } from "fs";
63591
- import { dirname as dirname16 } from "path";
64329
+ import { mkdirSync as mkdirSync17 } from "fs";
64330
+ import { dirname as dirname17 } from "path";
63592
64331
  function summariseRadioSamples(rows) {
63593
64332
  const byRadio = new Map;
63594
64333
  for (const r of rows) {
@@ -63675,7 +64414,7 @@ class SqliteCapsmanStore {
63675
64414
  async function openCapsmanStore(path) {
63676
64415
  if (path !== ":memory:") {
63677
64416
  try {
63678
- mkdirSync16(dirname16(path), { recursive: true });
64417
+ mkdirSync17(dirname17(path), { recursive: true });
63679
64418
  } catch {}
63680
64419
  }
63681
64420
  const { Database } = await import("bun:sqlite");
@@ -63750,8 +64489,8 @@ function stopCapsmanSampler() {
63750
64489
  }
63751
64490
 
63752
64491
  // src/observability/usage-store.ts
63753
- import { mkdirSync as mkdirSync17 } from "fs";
63754
- import { dirname as dirname17 } from "path";
64492
+ import { mkdirSync as mkdirSync18 } from "fs";
64493
+ import { dirname as dirname18 } from "path";
63755
64494
  function dayOf(ts) {
63756
64495
  return new Date(ts).toISOString().slice(0, 10);
63757
64496
  }
@@ -63874,7 +64613,7 @@ class SqliteUsageStore {
63874
64613
  async function openUsageStore(path) {
63875
64614
  if (path !== ":memory:") {
63876
64615
  try {
63877
- mkdirSync17(dirname17(path), { recursive: true });
64616
+ mkdirSync18(dirname18(path), { recursive: true });
63878
64617
  } catch {}
63879
64618
  }
63880
64619
  const { Database } = await import("bun:sqlite");
@@ -64316,7 +65055,7 @@ async function postureRoutes(req, url) {
64316
65055
  }
64317
65056
 
64318
65057
  // src/observability/access-settings.ts
64319
- import { createHash as createHash4 } from "crypto";
65058
+ import { createHash as createHash5 } from "crypto";
64320
65059
  var list2 = array(string2().trim().min(1).max(200)).max(200);
64321
65060
  var accessSchema = AccessConfigSchema.extend({
64322
65061
  devices: list2,
@@ -64346,7 +65085,7 @@ function createAccessSettingsRoutes(admin, deps = {
64346
65085
  }) {
64347
65086
  let pending = null;
64348
65087
  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");
65088
+ const revision = () => createHash5("sha256").update(JSON.stringify([deps.getConfig(), deps.getAccessPolicy()])).digest("hex");
64350
65089
  const payload = () => {
64351
65090
  const cfg = deps.getConfig();
64352
65091
  const id = admin.pendingId();
@@ -64729,8 +65468,8 @@ async function rolloutRoutes(req, url) {
64729
65468
  }
64730
65469
 
64731
65470
  // src/policy/results.ts
64732
- import { mkdirSync as mkdirSync18 } from "fs";
64733
- import { dirname as dirname18 } from "path";
65471
+ import { mkdirSync as mkdirSync19 } from "fs";
65472
+ import { dirname as dirname19 } from "path";
64734
65473
  var SCHEMA_STATEMENTS9 = [
64735
65474
  `CREATE TABLE IF NOT EXISTS policy_results (
64736
65475
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -64790,7 +65529,7 @@ class SqlitePolicyResultStore {
64790
65529
  async function openPolicyResultStore(path) {
64791
65530
  if (path !== ":memory:") {
64792
65531
  try {
64793
- mkdirSync18(dirname18(path), { recursive: true });
65532
+ mkdirSync19(dirname19(path), { recursive: true });
64794
65533
  } catch {}
64795
65534
  }
64796
65535
  const { Database } = await import("bun:sqlite");
@@ -66802,13 +67541,13 @@ async function runDashboard(cfg, transportLabel) {
66802
67541
  startHealthChecks(30000);
66803
67542
  startGeoLookups();
66804
67543
  try {
66805
- usageStore = await openUsageStore(join12(dirname19(cfg.dbPath), "usage.db"));
67544
+ usageStore = await openUsageStore(join12(dirname20(cfg.dbPath), "usage.db"));
66806
67545
  startUsageSampler(usageStore);
66807
67546
  } catch (e) {
66808
67547
  logger.warn(`[${SERVER_TAG3}] usage history disabled: ${String(e)}`);
66809
67548
  }
66810
67549
  try {
66811
- capsmanStore = await openCapsmanStore(join12(dirname19(cfg.dbPath), "capsman.db"));
67550
+ capsmanStore = await openCapsmanStore(join12(dirname20(cfg.dbPath), "capsman.db"));
66812
67551
  startCapsmanSampler(capsmanStore);
66813
67552
  } catch (e) {
66814
67553
  logger.warn(`[${SERVER_TAG3}] capsman trends disabled: ${String(e)}`);
@@ -66877,6 +67616,9 @@ async function runDashboard(cfg, transportLabel) {
66877
67616
  const investigationResp = await investigationRoutes(req, url);
66878
67617
  if (investigationResp)
66879
67618
  return investigationResp;
67619
+ const homeResp = await homeRoutes(req, url);
67620
+ if (homeResp)
67621
+ return homeResp;
66880
67622
  const serviceContractResp = await serviceContractRoutes(req, url);
66881
67623
  if (serviceContractResp)
66882
67624
  return serviceContractResp;
@@ -67230,7 +67972,7 @@ async function runDashboard(cfg, transportLabel) {
67230
67972
  }
67231
67973
 
67232
67974
  // src/transport/http.ts
67233
- import { randomUUID as randomUUID4 } from "crypto";
67975
+ import { randomUUID as randomUUID5 } from "crypto";
67234
67976
  var {serve: serve2 } = globalThis.Bun;
67235
67977
 
67236
67978
  // node_modules/content-type/index.js
@@ -67322,6 +68064,50 @@ function isJsonContentType(header) {
67322
68064
  return mediaTypeEssence(header) === "application/json";
67323
68065
  }
67324
68066
 
68067
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/requestBody.js
68068
+ var DEFAULT_MAX_REQUEST_BODY_SIZE = 4 * 1024 * 1024;
68069
+ var MAX_BATCH_SIZE = 100;
68070
+ function requestBodyTooLargeMessage(maxBytes) {
68071
+ return `Payload Too Large: Request body must not exceed ${maxBytes} bytes`;
68072
+ }
68073
+ function resolveMaxRequestBodySize(value) {
68074
+ if (value === undefined) {
68075
+ return DEFAULT_MAX_REQUEST_BODY_SIZE;
68076
+ }
68077
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
68078
+ throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(value)}`);
68079
+ }
68080
+ return value;
68081
+ }
68082
+ async function readRequestBody(request, maxBytes = DEFAULT_MAX_REQUEST_BODY_SIZE) {
68083
+ if (Number(request.headers.get("content-length")) > maxBytes) {
68084
+ return { tooLarge: true };
68085
+ }
68086
+ if (request.body === null) {
68087
+ return { tooLarge: false, text: "" };
68088
+ }
68089
+ const reader = request.body.getReader();
68090
+ const decoder = new TextDecoder;
68091
+ let received = 0;
68092
+ let text = "";
68093
+ try {
68094
+ for (;; ) {
68095
+ const { done, value } = await reader.read();
68096
+ if (done) {
68097
+ break;
68098
+ }
68099
+ received += value.byteLength;
68100
+ if (received > maxBytes) {
68101
+ return { tooLarge: true };
68102
+ }
68103
+ text += decoder.decode(value, { stream: true });
68104
+ }
68105
+ } finally {
68106
+ reader.releaseLock();
68107
+ }
68108
+ return { tooLarge: false, text: text + decoder.decode() };
68109
+ }
68110
+
67325
68111
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js
67326
68112
  var DEFAULT_SSE_KEEP_ALIVE_MS = 15000;
67327
68113
  var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
@@ -68203,6 +68989,7 @@ class WebStandardStreamableHTTPServerTransport {
68203
68989
  this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;
68204
68990
  this._retryInterval = options.retryInterval;
68205
68991
  this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS;
68992
+ this._maxRequestBodySize = resolveMaxRequestBodySize(options.maxRequestBodySize);
68206
68993
  }
68207
68994
  startKeepAlive(controller, encoder) {
68208
68995
  if (this._closed)
@@ -68519,12 +69306,22 @@ data:
68519
69306
  rawMessage = options.parsedBody;
68520
69307
  } else {
68521
69308
  try {
68522
- rawMessage = await req.json();
69309
+ const body = await readRequestBody(req, this._maxRequestBodySize);
69310
+ if (body.tooLarge) {
69311
+ const message = requestBodyTooLargeMessage(this._maxRequestBodySize);
69312
+ this.onerror?.(new Error(message));
69313
+ return this.createJsonErrorResponse(413, -32000, message);
69314
+ }
69315
+ rawMessage = JSON.parse(body.text);
68523
69316
  } catch {
68524
69317
  this.onerror?.(new Error("Parse error: Invalid JSON"));
68525
69318
  return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON");
68526
69319
  }
68527
69320
  }
69321
+ if (Array.isArray(rawMessage) && rawMessage.length > MAX_BATCH_SIZE) {
69322
+ this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${MAX_BATCH_SIZE} messages`));
69323
+ return this.createJsonErrorResponse(400, -32600, `Invalid Request: Batch must not exceed ${MAX_BATCH_SIZE} messages`);
69324
+ }
68528
69325
  let messages;
68529
69326
  try {
68530
69327
  if (Array.isArray(rawMessage)) {
@@ -76545,7 +77342,7 @@ async function runHttp(mcp) {
76545
77342
  if (existing)
76546
77343
  return existing;
76547
77344
  const transport = new WebStandardStreamableHTTPServerTransport({
76548
- sessionIdGenerator: () => randomUUID4(),
77345
+ sessionIdGenerator: () => randomUUID5(),
76549
77346
  enableJsonResponse: true,
76550
77347
  ...security,
76551
77348
  onsessioninitialized: (id) => {