@usex/mikrotik-mcp 5.12.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.
@@ -11121,6 +11121,14 @@ var REPORT_VIEW_TOOLS = {
11121
11121
  "packet_capture_status"
11122
11122
  ],
11123
11123
  reports: [
11124
+ "diagnose_home_internet",
11125
+ "compare_home_paths",
11126
+ "get_home_internet",
11127
+ "refresh_home_devices",
11128
+ "name_home_device",
11129
+ "preview_home_policy",
11130
+ "apply_home_policy",
11131
+ "undo_home_policy",
11124
11132
  "diagnose",
11125
11133
  "trace_path",
11126
11134
  "correlate_events",
@@ -15298,12 +15306,892 @@ var investigationTools = [
15298
15306
  })
15299
15307
  ];
15300
15308
 
15301
- // src/tools/service-contracts.ts
15302
- import { randomUUID as randomUUID3 } from "crypto";
15309
+ // src/home/model.ts
15310
+ var macInput = string().regex(/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i);
15311
+ var diagnosisInput = object({
15312
+ client: ipv42(),
15313
+ target: string().max(253).regex(/^[a-z\d](?:[a-z\d.-]*[a-z\d])?$/i).default("example.com")
15314
+ });
15315
+ var compareInput = object({
15316
+ target: ipv42(),
15317
+ tables: array(string().min(1).max(64)).min(1).max(3),
15318
+ goal: _enum(["calls", "gaming", "download"]).default("calls")
15319
+ });
15320
+ var policyInput = object({
15321
+ mac: macInput,
15322
+ action: _enum(["pause", "priority", "route"]),
15323
+ minutes: number().int().min(5).max(120).default(30),
15324
+ startInMinutes: number().int().min(0).max(1440).default(0),
15325
+ table: string().min(1).max(64).optional()
15326
+ });
15327
+ function enabled2(row) {
15328
+ return !isYes(row.disabled) && !/[XI]/.test(row.flags ?? "");
15329
+ }
15330
+ function activeRoute(row) {
15331
+ return enabled2(row) && (isYes(row.active) || /A/.test(row.flags ?? ""));
15332
+ }
15333
+ function milliseconds(text) {
15334
+ if (!text)
15335
+ return null;
15336
+ const units = [...text.matchAll(/(\d+(?:\.\d+)?)(us|ms|s)/g)];
15337
+ if (!units.length || units.map((m) => m[0]).join("") !== text)
15338
+ return null;
15339
+ return units.reduce((sum, m) => sum + Number(m[1]) * (m[2] === "s" ? 1000 : m[2] === "us" ? 0.001 : 1), 0);
15340
+ }
15341
+ function pingSample(table, raw) {
15342
+ const sent = Number(raw.match(/sent=(\d+)/)?.[1]);
15343
+ const received = Number(raw.match(/received=(\d+)/)?.[1]);
15344
+ const rtt = (key) => milliseconds(raw.match(new RegExp(`${key}-rtt=([^\\s]+)`))?.[1]);
15345
+ const min = rtt("min"), max = rtt("max");
15346
+ if (!Number.isFinite(sent) || sent < 1 || !Number.isFinite(received) || received > sent)
15347
+ return {
15348
+ table,
15349
+ state: "unknown",
15350
+ loss: null,
15351
+ latency: null,
15352
+ spread: null,
15353
+ note: "No usable ICMP summary. This RouterOS version may not support table-scoped ping."
15354
+ };
15355
+ return {
15356
+ table,
15357
+ state: "observed",
15358
+ loss: (sent - received) * 100 / sent,
15359
+ latency: rtt("avg"),
15360
+ spread: min === null || max === null ? null : Math.max(0, max - min),
15361
+ note: "Five router-originated ICMP probes; RTT range is not a client jitter or throughput measurement."
15362
+ };
15363
+ }
15364
+ function recommendPath(paths, goal) {
15365
+ if (goal === "download")
15366
+ return null;
15367
+ const usable = paths.filter((p) => p.state === "observed" && p.loss !== null && p.loss < 100 && p.latency !== null && p.spread !== null);
15368
+ const score = (p) => p.loss * 1000 + p.latency + p.spread * (goal === "calls" ? 2 : 1);
15369
+ return usable.sort((a, b) => score(a) - score(b))[0]?.table ?? null;
15370
+ }
15371
+ function tagSelector(tag) {
15372
+ return `[find where comment=${quoteValue(tag)}]`;
15373
+ }
15374
+ function temporaryCommands(id, input, ip, setup, activate, revert) {
15375
+ const tag = `mcp-home-${id}`;
15376
+ const clearMarkers = new Cmd(`/ip firewall address-list remove ${tagSelector(tag)}`).build();
15377
+ const clearScheduler = new Cmd(`/system scheduler remove ${tagSelector(tag)}`).build();
15378
+ const undo = [...revert, clearMarkers, clearScheduler];
15379
+ const leaseMatch = `[/ip dhcp-server lease find where mac-address=${quoteValue(input.mac)} address=${quoteValue(ip)} dynamic=no status=bound]`;
15380
+ const expired = `([:len [/ip firewall address-list find where list=${quoteValue(`${tag}-end`)}]] = 0 || [:len ${leaseMatch}] != 1)`;
15381
+ const waiting = `[:len [/ip firewall address-list find where list=${quoteValue(`${tag}-start`)}]] = 0`;
15382
+ const tick = `:if (${expired}) do={ ${undo.join("; ")} } else={ :if (${waiting}) do={ ${activate.join("; ")} } }`;
15383
+ const commands = [
15384
+ ...setup,
15385
+ 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(),
15386
+ ...input.startInMinutes ? [
15387
+ new Cmd("/ip firewall address-list add").set("list", `${tag}-start`).set("address", ip).set("timeout", `${input.startInMinutes}m`).set("comment", tag).build()
15388
+ ] : [],
15389
+ 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(),
15390
+ 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(),
15391
+ ...!input.startInMinutes ? activate : []
15392
+ ];
15393
+ return { commands, undo };
15394
+ }
15395
+
15396
+ // src/home/read.ts
15397
+ async function checkedRead(command, ctx, read = executeMikrotikCommand2) {
15398
+ const raw = await read(command, ctx, { maxMs: 8000 });
15399
+ if (looksLikeError(raw) || raw.length > 512000)
15400
+ throw new Error("Router rejected the command or returned too much data; its outcome was not confirmed.");
15401
+ return raw;
15402
+ }
15403
+ async function rows(path, fields, ctx, read = executeMikrotikCommand2) {
15404
+ const raw = await checkedRead(new Cmd(`${path} print detail without-paging`).build(), ctx, read);
15405
+ const result = parseRecords(raw).rows;
15406
+ if (!result.length && !isEmpty(raw) && !/^\s*(?:Flags:.*)?\s*$/.test(raw) || result.length > 1000)
15407
+ throw new Error(`Cannot safely interpret ${path}.`);
15408
+ const keys = new Set(["#", "flags", ...fields.split(",")]);
15409
+ return result.map((row) => Object.fromEntries(Object.entries(row).filter(([key]) => keys.has(key))));
15410
+ }
15411
+ async function diagnoseInternet(input, ctx, read = executeMikrotikCommand2) {
15412
+ const a = diagnosisInput.parse(input), device = resolveDeviceName2(ctx.device);
15413
+ assertDeviceAccess([device], "diagnose_home_internet", "READ");
15414
+ const findings = [];
15415
+ const capture = async (area, work) => {
15416
+ try {
15417
+ findings.push(await work());
15418
+ } catch {
15419
+ findings.push({
15420
+ area,
15421
+ state: "unknown",
15422
+ title: `${area} could not be measured`,
15423
+ detail: "The router query failed or is unsupported. Missing evidence is not a healthy result.",
15424
+ next: "Check permissions and device support, then retry."
15425
+ });
15426
+ }
15427
+ };
15428
+ await capture("Router", async () => {
15429
+ const resource = parseKeyValues(await checkedRead("/system resource print", ctx, read));
15430
+ const cpu = Number(resource["cpu-load"]?.replace("%", ""));
15431
+ const free = parseSize(resource["free-memory"]), total = parseSize(resource["total-memory"]);
15432
+ if (!Number.isFinite(cpu) || !total || free === undefined)
15433
+ throw new Error("No resources");
15434
+ const memory = Math.round((1 - free / total) * 100), hot = cpu >= 85 || memory >= 90;
15435
+ return {
15436
+ area: "Router",
15437
+ state: hot ? "suspected" : "observed",
15438
+ title: hot ? "The router may be under pressure" : "Router resources have headroom in this sample",
15439
+ detail: `CPU ${cpu}% \xB7 memory ${memory}%. One sample does not establish a bottleneck.`,
15440
+ next: "Repeat while the slow download is running; compare with the Devices page."
15441
+ };
15442
+ });
15443
+ await capture("DNS", async () => {
15444
+ const start = Date.now();
15445
+ const resolved = (await checkedRead(`:put [:resolve ${new Cmd("").set("domain-name", a.target).build().trim()}]`, ctx, read)).trim();
15446
+ if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(resolved))
15447
+ throw new Error("Not an IPv4 result");
15448
+ return {
15449
+ area: "DNS",
15450
+ state: "observed",
15451
+ title: "The router resolved this destination",
15452
+ detail: `${a.target} \u2192 ${resolved}. Query plus SSH round trip: ${Date.now() - start} ms (not pure DNS latency).`,
15453
+ next: "If only one device is affected, compare its DNS and secure-DNS settings."
15454
+ };
15455
+ });
15456
+ await capture("Internet", async () => {
15457
+ const result = pingSample("main", await checkedRead(new Cmd("/ping").set("address", a.target).set("count", 5).set("interval", "200ms").build(), ctx, read));
15458
+ if (result.state === "unknown")
15459
+ throw new Error("No ping");
15460
+ return {
15461
+ area: "Internet",
15462
+ state: result.loss > 0 ? "suspected" : "observed",
15463
+ title: result.loss > 0 ? "Some router probes did not return" : "All router probes returned",
15464
+ detail: `${result.loss}% loss \xB7 average RTT ${result.latency ?? "unknown"} ms. ICMP can be deprioritized; this does not locate a failing hop.`,
15465
+ next: "Compare paths below. Router probes do not test the client's firewall path or application."
15466
+ };
15467
+ });
15468
+ await capture("Wi-Fi", async () => {
15469
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,active-address", ctx, read);
15470
+ const mac = leases.find((r) => r.address === a.client || r["active-address"] === a.client)?.["mac-address"];
15471
+ if (!mac)
15472
+ throw new Error("No attachment");
15473
+ let registrations;
15474
+ try {
15475
+ registrations = await rows("/interface wifi registration-table", "mac-address,signal,tx-rate,rx-rate", ctx, read);
15476
+ } catch {
15477
+ registrations = await rows("/interface wireless registration-table", "mac-address,signal-strength,tx-rate,rx-rate", ctx, read);
15478
+ }
15479
+ const entry = registrations.find((r) => r["mac-address"]?.toUpperCase() === mac.toUpperCase());
15480
+ const signal = Number.parseFloat(entry?.signal ?? entry?.["signal-strength"] ?? "");
15481
+ if (!entry || !Number.isFinite(signal))
15482
+ throw new Error("No Wi-Fi measurement");
15483
+ return {
15484
+ area: "Wi-Fi",
15485
+ state: signal < -70 ? "suspected" : "observed",
15486
+ title: signal < -70 ? "Weak Wi-Fi signal may be slowing this device" : "Wi-Fi signal is not weak in this sample",
15487
+ detail: `${signal} dBm \xB7 PHY transmit rate ${entry["tx-rate"] ?? "unknown"}. PHY rate is not download speed.`,
15488
+ next: "Move closer to the access point and compare; interference and airtime remain unmeasured."
15489
+ };
15490
+ });
15491
+ await capture("Bandwidth", async () => {
15492
+ const queues = await rows("/queue simple", "name,target,max-limit,disabled", ctx, read);
15493
+ const matches = queues.filter((q) => enabled2(q) && q.target?.split(",").some((t) => t === a.client || t === `${a.client}/32`));
15494
+ return {
15495
+ area: "Bandwidth",
15496
+ state: matches.length ? "observed" : "unknown",
15497
+ title: matches.length ? "A per-device bandwidth policy exists" : "Available bandwidth has not been measured",
15498
+ 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.",
15499
+ next: "Run an endpoint speed test before and during the problem. These checks do not download test files or change MTU."
15500
+ };
15501
+ });
15502
+ return {
15503
+ device,
15504
+ client: a.client,
15505
+ target: a.target,
15506
+ at: Date.now(),
15507
+ applicationHealth: "unverified",
15508
+ findings
15509
+ };
15510
+ }
15511
+ async function comparePaths(input, ctx, read = executeMikrotikCommand2) {
15512
+ const a = compareInput.parse(input), device = resolveDeviceName2(ctx.device);
15513
+ assertDeviceAccess([device], "compare_home_paths", "READ");
15514
+ const tables = await rows("/routing table", "name,fib,disabled", ctx, read);
15515
+ const names = [...new Set(a.tables)];
15516
+ if (names.some((name) => !tables.some((t) => t.name === name && enabled2(t) && (t.fib === "yes" || t.fib === "true"))))
15517
+ throw new Error("Choose an existing enabled FIB routing table.");
15518
+ const paths = [];
15519
+ for (const table of names) {
15520
+ try {
15521
+ 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)));
15522
+ } catch {
15523
+ paths.push(pingSample(table, ""));
15524
+ }
15525
+ }
15526
+ return {
15527
+ device,
15528
+ at: Date.now(),
15529
+ target: a.target,
15530
+ goal: a.goal,
15531
+ paths,
15532
+ recommended: recommendPath(paths, a.goal),
15533
+ 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."
15534
+ };
15535
+ }
15303
15536
 
15304
- // src/service-contracts/store.ts
15537
+ // src/home/policies.ts
15538
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
15539
+
15540
+ // src/snapshots/format.ts
15541
+ import { createHash } from "crypto";
15542
+ var TIMESTAMP_HEADER = /^#\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b.*by RouterOS/i;
15543
+ function parseExportMeta(body) {
15544
+ const head = body.slice(0, 600);
15545
+ const version = head.match(/by RouterOS ([^\s#]+)/i)?.[1];
15546
+ const exportedAt = head.match(/#\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1];
15547
+ return { rosVersion: version, exportedAt };
15548
+ }
15549
+ function normalizeExport(body) {
15550
+ return body.replace(/\r\n/g, `
15551
+ `).split(`
15552
+ `).filter((line) => !TIMESTAMP_HEADER.test(line)).join(`
15553
+ `).replace(/\n+$/, "");
15554
+ }
15555
+ function contentSha(normalizedBody) {
15556
+ return createHash("sha256").update(normalizedBody, "utf8").digest("hex").slice(0, 16);
15557
+ }
15558
+ function countLines(body) {
15559
+ const trimmed = body.replace(/\n+$/, "");
15560
+ return trimmed === "" ? 0 : trimmed.split(`
15561
+ `).length;
15562
+ }
15563
+
15564
+ // src/snapshots/store.ts
15305
15565
  import { mkdirSync as mkdirSync4 } from "fs";
15306
15566
  import { dirname as dirname4 } from "path";
15567
+ function rowToBaseline(r) {
15568
+ return {
15569
+ device: r.device,
15570
+ snapshotId: r.snapshot_id,
15571
+ setAt: r.set_at,
15572
+ setBy: r.set_by,
15573
+ label: r.label ?? undefined,
15574
+ notes: r.notes ?? undefined
15575
+ };
15576
+ }
15577
+ function rowToSnapshot(r, body) {
15578
+ return {
15579
+ id: r.id,
15580
+ device: r.device,
15581
+ ts: r.ts,
15582
+ label: r.label ?? undefined,
15583
+ rosVersion: r.ros_version ?? undefined,
15584
+ body,
15585
+ bytes: r.bytes,
15586
+ lines: r.lines,
15587
+ sha: r.sha
15588
+ };
15589
+ }
15590
+ var SCHEMA_STATEMENTS3 = [
15591
+ `CREATE TABLE IF NOT EXISTS snapshots (
15592
+ id TEXT PRIMARY KEY,
15593
+ device TEXT NOT NULL,
15594
+ ts INTEGER NOT NULL,
15595
+ label TEXT,
15596
+ ros_version TEXT,
15597
+ body TEXT NOT NULL,
15598
+ bytes INTEGER NOT NULL,
15599
+ lines INTEGER NOT NULL,
15600
+ sha TEXT NOT NULL
15601
+ )`,
15602
+ "CREATE INDEX IF NOT EXISTS idx_snapshots_device_ts ON snapshots(device, ts)",
15603
+ `CREATE TABLE IF NOT EXISTS baselines (
15604
+ device TEXT PRIMARY KEY,
15605
+ snapshot_id TEXT NOT NULL,
15606
+ set_at INTEGER NOT NULL,
15607
+ set_by TEXT NOT NULL DEFAULT 'agent',
15608
+ label TEXT,
15609
+ notes TEXT
15610
+ )`
15611
+ ];
15612
+
15613
+ class SqliteSnapshotStore {
15614
+ db;
15615
+ constructor(db) {
15616
+ this.db = db;
15617
+ db.run("PRAGMA journal_mode = WAL");
15618
+ db.run("PRAGMA synchronous = NORMAL");
15619
+ for (const stmt of SCHEMA_STATEMENTS3)
15620
+ db.run(stmt);
15621
+ }
15622
+ insert(s) {
15623
+ this.db.query(`INSERT OR REPLACE INTO snapshots
15624
+ (id, device, ts, label, ros_version, body, bytes, lines, sha)
15625
+ VALUES ($id,$device,$ts,$label,$ver,$body,$bytes,$lines,$sha)`).run({
15626
+ $id: s.id,
15627
+ $device: s.device,
15628
+ $ts: s.ts,
15629
+ $label: s.label ?? null,
15630
+ $ver: s.rosVersion ?? null,
15631
+ $body: s.body,
15632
+ $bytes: s.bytes,
15633
+ $lines: s.lines,
15634
+ $sha: s.sha
15635
+ });
15636
+ }
15637
+ get(id) {
15638
+ const row = this.db.query("SELECT * FROM snapshots WHERE id = $id").get({ $id: id });
15639
+ return row ? rowToSnapshot(row, row.body) : null;
15640
+ }
15641
+ latest(device) {
15642
+ const row = this.db.query("SELECT * FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT 1").get({ $d: device });
15643
+ return row ? rowToSnapshot(row, row.body) : null;
15644
+ }
15645
+ list(device, limit = 50, withBody = false) {
15646
+ const cols = withBody ? "*" : "id, device, ts, label, ros_version, bytes, lines, sha";
15647
+ const n = Math.min(Math.max(limit, 1), 500);
15648
+ const rows = this.db.query(`SELECT ${cols} FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT $n`).all({ $d: device, $n: n });
15649
+ return rows.map((r) => rowToSnapshot(r, withBody ? r.body : ""));
15650
+ }
15651
+ count(device) {
15652
+ const r = this.db.query("SELECT COUNT(*) AS n FROM snapshots WHERE device = $d").get({ $d: device });
15653
+ return r.n;
15654
+ }
15655
+ delete(ids) {
15656
+ if (ids.length === 0)
15657
+ return 0;
15658
+ const placeholders = ids.map((_, j) => `$id${j}`).join(",");
15659
+ const params = {};
15660
+ ids.forEach((id, j) => {
15661
+ params[`$id${j}`] = id;
15662
+ });
15663
+ const res = this.db.query(`DELETE FROM snapshots WHERE id IN (${placeholders})`).run(params);
15664
+ return Number(res.changes ?? 0);
15665
+ }
15666
+ setBaseline(device, snapshotId, setBy = "agent", label, notes) {
15667
+ this.db.query(`INSERT OR REPLACE INTO baselines (device, snapshot_id, set_at, set_by, label, notes)
15668
+ VALUES ($device, $snapId, $setAt, $setBy, $label, $notes)`).run({
15669
+ $device: device,
15670
+ $snapId: snapshotId,
15671
+ $setAt: Date.now(),
15672
+ $setBy: setBy,
15673
+ $label: label ?? null,
15674
+ $notes: notes ?? null
15675
+ });
15676
+ }
15677
+ getBaseline(device) {
15678
+ const row = this.db.query("SELECT * FROM baselines WHERE device = $d").get({ $d: device });
15679
+ return row ? rowToBaseline(row) : null;
15680
+ }
15681
+ removeBaseline(device) {
15682
+ const res = this.db.query("DELETE FROM baselines WHERE device = $d").run({ $d: device });
15683
+ return (res.changes ?? 0) > 0;
15684
+ }
15685
+ listBaselines() {
15686
+ const rows = this.db.query("SELECT * FROM baselines ORDER BY set_at DESC").all();
15687
+ return rows.map(rowToBaseline);
15688
+ }
15689
+ close() {
15690
+ this.db.close();
15691
+ }
15692
+ }
15693
+ async function openSnapshotStore(path) {
15694
+ if (path !== ":memory:") {
15695
+ try {
15696
+ mkdirSync4(dirname4(path), { recursive: true });
15697
+ } catch {}
15698
+ }
15699
+ const { Database } = await import("bun:sqlite");
15700
+ const db = new Database(path, { create: true });
15701
+ return new SqliteSnapshotStore(db);
15702
+ }
15703
+
15704
+ // src/snapshots/capture.ts
15705
+ var storePromise3 = null;
15706
+ function snapshots() {
15707
+ if (!storePromise3)
15708
+ storePromise3 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
15709
+ return storePromise3;
15710
+ }
15711
+ async function captureSnapshot(ctx, label, requireExport = false) {
15712
+ const device = resolveDeviceName2(ctx.device);
15713
+ const body = await executeMikrotikCommand2("/export terse", ctx);
15714
+ if (requireExport && (looksLikeError(body) || !/^\/[a-z]/m.test(body) || /#\s*error exporting/i.test(body)))
15715
+ throw new Error("A complete pre-change configuration export could not be captured; no policy was applied.");
15716
+ const meta = parseExportMeta(body);
15717
+ const sha = contentSha(normalizeExport(body));
15718
+ const ts = Date.now();
15719
+ const snap = {
15720
+ id: `snap_${ts}_${sha.slice(0, 8)}`,
15721
+ device,
15722
+ ts,
15723
+ label,
15724
+ rosVersion: meta.rosVersion,
15725
+ body,
15726
+ bytes: Buffer.byteLength(body, "utf8"),
15727
+ lines: countLines(body),
15728
+ sha
15729
+ };
15730
+ (await snapshots()).insert(snap);
15731
+ return snap.id;
15732
+ }
15733
+
15734
+ // src/home/store.ts
15735
+ import { mkdirSync as mkdirSync5 } from "fs";
15736
+ import { dirname as dirname5 } from "path";
15737
+ class HomeStore {
15738
+ db;
15739
+ constructor(db) {
15740
+ this.db = db;
15741
+ 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))");
15742
+ 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)");
15743
+ 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')");
15744
+ }
15745
+ clients(device) {
15746
+ return this.db.query("SELECT body FROM home_clients WHERE device=?").all(device).map((r) => JSON.parse(r.body));
15747
+ }
15748
+ saveClient(device, client) {
15749
+ 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));
15750
+ }
15751
+ savePlan(plan) {
15752
+ 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));
15753
+ }
15754
+ plan(id, device) {
15755
+ const row = this.db.query("SELECT body FROM home_plans WHERE id=? AND device=?").get(id, device);
15756
+ return row ? JSON.parse(row.body) : undefined;
15757
+ }
15758
+ claim(plan) {
15759
+ 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());
15760
+ if (result.changes !== 1)
15761
+ throw new Error("Preview expired or was already claimed by another process.");
15762
+ }
15763
+ unresolved(device) {
15764
+ 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));
15765
+ }
15766
+ plans(device) {
15767
+ 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));
15768
+ return [
15769
+ ...new Map([...recent, ...this.unresolved(device)].map((p) => [p.id, p])).values()
15770
+ ].sort((a, b) => b.createdAt - a.createdAt);
15771
+ }
15772
+ }
15773
+ var pending2;
15774
+ function homeStore() {
15775
+ return pending2 ??= (async () => {
15776
+ mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
15777
+ const { Database } = await import("bun:sqlite");
15778
+ const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
15779
+ db.run("PRAGMA journal_mode=WAL");
15780
+ db.run("PRAGMA busy_timeout=5000");
15781
+ return new HomeStore(db);
15782
+ })().catch((e) => {
15783
+ pending2 = undefined;
15784
+ throw e;
15785
+ });
15786
+ }
15787
+
15788
+ // src/home/policies.ts
15789
+ function buildPolicy(id, input, facts) {
15790
+ input = { ...input, mac: input.mac.toUpperCase() };
15791
+ if (!isYes(facts.deviceMode.scheduler))
15792
+ throw new Error("Router device-mode must explicitly allow scheduler execution for automatic expiry.");
15793
+ const candidates = facts.leases.filter((l) => l["mac-address"]?.toUpperCase() === input.mac);
15794
+ const lease = candidates[0];
15795
+ if (candidates.length !== 1 || !lease || isYes(lease.dynamic) || /D/.test(lease.flags ?? "") || !enabled2(lease) || lease.status !== "bound" || !lease.address)
15796
+ throw new Error("This control requires exactly one bound, static DHCP lease. Pin the client's IP in Clients first.");
15797
+ if (facts.leases.some((l) => l !== lease && (l.address === lease.address || l["active-address"] === lease.address)))
15798
+ throw new Error("The client IP is ambiguous.");
15799
+ if (lease["active-address"] && lease["active-address"] !== lease.address)
15800
+ throw new Error("The client lease changed; reconnect it before continuing.");
15801
+ if (lease["active-mac-address"] && lease["active-mac-address"].toUpperCase() !== input.mac)
15802
+ throw new Error("The active client MAC does not match its reservation.");
15803
+ if (facts.addresses.some((r) => r.address?.split("/")[0] === lease.address))
15804
+ throw new Error("Cannot target a router address.");
15805
+ if (facts.filters.some((r) => enabled2(r) && r.action === "fasttrack-connection") || facts.connections.some((r) => isYes(r.fasttrack) || /F/.test(r.flags ?? "")))
15806
+ 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.");
15807
+ if (input.action === "pause" && !isYes(facts.ipv6["disable-ipv6"]) && facts.ipv6.forward !== "no" && facts.ipv6.forward !== "false")
15808
+ throw new Error("IPv6 forwarding is enabled or unknown. An IPv4-only pause could be bypassed; use a dual-stack policy instead.");
15809
+ const tag = `mcp-home-${id}`, ip = lease.address;
15810
+ const setup = [], activate = [], revert = [];
15811
+ let queueBefore;
15812
+ const warnings = [
15813
+ "Only this reserved IPv4 client is targeted. Other configuration is left in place.",
15814
+ "The router expires this policy even when the dashboard is closed. Scheduler cleanup can take up to 30 seconds. Reboot ends the policy.",
15815
+ "Existing connections may disconnect. Review before applying; this is not a speed guarantee."
15816
+ ];
15817
+ const manage = (path) => {
15818
+ activate.push(new Cmd(`${path} enable ${tagSelector(tag)}`).build());
15819
+ revert.push(new Cmd(`${path} remove ${tagSelector(tag)}`).build());
15820
+ };
15821
+ if (input.action === "pause") {
15822
+ for (const direction of ["src", "dst"])
15823
+ 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());
15824
+ manage("/ip firewall filter");
15825
+ warnings.push("Pauses all routed traffic for this IP, including routed LAN traffic; router management and same-bridge traffic are not blocked.");
15826
+ } else if (input.action === "route") {
15827
+ 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)))
15828
+ throw new Error("Select an enabled FIB table with an active default route. This feature does not create WANs or VPNs.");
15829
+ if (facts.mangle.some((r) => enabled2(r) && r.action === "mark-routing"))
15830
+ throw new Error("Existing routing marks require an administrator review; this control will not override them.");
15831
+ const exclusions = new Set([
15832
+ "10.0.0.0/8",
15833
+ "172.16.0.0/12",
15834
+ "192.168.0.0/16",
15835
+ "100.64.0.0/10",
15836
+ "127.0.0.0/8",
15837
+ "169.254.0.0/16",
15838
+ "224.0.0.0/4",
15839
+ "255.255.255.255"
15840
+ ]);
15841
+ for (const a of facts.addresses)
15842
+ if (a.address)
15843
+ exclusions.add(a.address);
15844
+ for (const prefix of exclusions)
15845
+ setup.push(new Cmd("/ip firewall address-list add").set("list", `${tag}-local`).set("address", prefix).set("comment", tag).build());
15846
+ 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());
15847
+ manage("/ip firewall mangle");
15848
+ 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.");
15849
+ } else {
15850
+ const queues = facts.queues.filter((q) => q.target === `${ip}/32` && enabled2(q));
15851
+ const q = queues[0], parent = facts.queues.find((r) => r.name === q?.parent && enabled2(r));
15852
+ 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 ?? ""))
15853
+ 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.");
15854
+ if (facts.queues.some((r) => r.parent === q.name))
15855
+ throw new Error("Only leaf queues can receive meeting priority.");
15856
+ if (q.priority === "1/1")
15857
+ throw new Error("This client already has the highest queue priority.");
15858
+ queueBefore = { name: q.name, target: q.target, parent: q.parent, priority: q.priority };
15859
+ const selector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority=${quoteValue(q.priority)}]`;
15860
+ activate.push(new Cmd(`/queue simple set ${selector}`).set("priority", "1/1").build());
15861
+ const restoreSelector = `[find where name=${quoteValue(q.name)} target=[:tostr ${quoteValue(q.target)}] parent=${quoteValue(q.parent)} priority="1/1"]`;
15862
+ revert.push(new Cmd(`/queue simple set ${restoreSelector}`).set("priority", q.priority).build());
15863
+ 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.");
15864
+ }
15865
+ const generated = temporaryCommands(id, input, ip, setup, activate, revert);
15866
+ if (generated.commands.length > 40)
15867
+ throw new Error("This router needs too many policy objects for a bounded Safe Mode change. Ask an administrator to review it.");
15868
+ const stable = JSON.stringify(facts, (key, value) => key === "#" ? undefined : value);
15869
+ return {
15870
+ ip,
15871
+ ...generated,
15872
+ warnings,
15873
+ queueBefore,
15874
+ fingerprint: createHash2("sha256").update(stable).digest("hex")
15875
+ };
15876
+ }
15877
+ async function policyFacts(ctx, read = executeMikrotikCommand2) {
15878
+ const fasttrackCount = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx, read)).trim();
15879
+ if (!/^\d+$/.test(fasttrackCount))
15880
+ throw new Error("Cannot establish whether FastTrack connections remain active.");
15881
+ return {
15882
+ leases: await rows("/ip dhcp-server lease", "address,active-address,mac-address,active-mac-address,dynamic,disabled,status", ctx, read),
15883
+ filters: await rows("/ip firewall filter", "chain,action,disabled,comment", ctx, read),
15884
+ connections: Number(fasttrackCount) > 0 ? [{ fasttrack: "yes" }] : [],
15885
+ mangle: await rows("/ip firewall mangle", "chain,action,disabled,comment", ctx, read),
15886
+ queues: await rows("/queue simple", "name,target,parent,priority,max-limit,packet-marks,disabled", ctx, read),
15887
+ tables: await rows("/routing table", "name,fib,disabled", ctx, read),
15888
+ routes: await rows("/ip route", "dst-address,routing-table,active,disabled,gateway", ctx, read),
15889
+ addresses: await rows("/ip address", "address,interface", ctx, read),
15890
+ ipv6: parseKeyValues(await checkedRead("/ipv6 settings print", ctx, read)),
15891
+ deviceMode: parseKeyValues(await checkedRead("/system device-mode print", ctx, read))
15892
+ };
15893
+ }
15894
+ var busy3 = new Set;
15895
+ async function exclusive(device, work) {
15896
+ if (busy3.has(device))
15897
+ throw new Error("Another Home Internet operation is in progress for this router.");
15898
+ busy3.add(device);
15899
+ try {
15900
+ return await work();
15901
+ } finally {
15902
+ busy3.delete(device);
15903
+ }
15904
+ }
15905
+ async function previewPolicy(input, ctx) {
15906
+ const a = policyInput.parse(input), device = resolveDeviceName2(ctx.device);
15907
+ a.mac = a.mac.toUpperCase();
15908
+ assertDeviceAccess([device], "preview_home_policy", "WRITE");
15909
+ return exclusive(device, async () => {
15910
+ const id = randomUUID2();
15911
+ const plan = {
15912
+ id,
15913
+ device,
15914
+ input: a,
15915
+ createdAt: Date.now(),
15916
+ previewExpiresAt: Date.now() + 300000,
15917
+ status: "preview",
15918
+ ...buildPolicy(id, a, await policyFacts(ctx))
15919
+ };
15920
+ (await homeStore()).savePlan(plan);
15921
+ return plan;
15922
+ });
15923
+ }
15924
+ async function applyPolicy(id, confirm, ctx) {
15925
+ const device = resolveDeviceName2(ctx.device);
15926
+ assertDeviceAccess([device], "apply_home_policy", "WRITE");
15927
+ if (!confirm)
15928
+ throw new Error("Review the preview and explicitly confirm before applying.");
15929
+ return exclusive(device, async () => {
15930
+ const store = await homeStore(), plan = store.plan(id, device);
15931
+ if (!plan || plan.status !== "preview" || plan.previewExpiresAt < Date.now())
15932
+ throw new Error("Preview expired, already used, or belongs to another router.");
15933
+ if (store.unresolved(device).some((p) => p.input.mac === plan.input.mac && ["applying", "scheduled", "active", "uncertain"].includes(p.status)))
15934
+ throw new Error("Undo or reconcile the previous policy for this device first.");
15935
+ const fresh = buildPolicy(id, plan.input, await policyFacts(ctx));
15936
+ if (fresh.fingerprint !== plan.fingerprint)
15937
+ throw new Error("Router state changed after the preview. Create a fresh preview.");
15938
+ const safe = getSafeModeManager2(device);
15939
+ if (safe.isActive)
15940
+ throw new Error("An existing Safe Mode session is active; finish it before applying a Home Internet policy.");
15941
+ plan.snapshot = await captureSnapshot(ctx, `Before Home Internet ${plan.input.action}`, true);
15942
+ plan.status = "applying";
15943
+ store.claim(plan);
15944
+ let owned = false;
15945
+ try {
15946
+ const status = await safe.enable();
15947
+ if (!status.startsWith("Safe mode ENABLED"))
15948
+ throw new Error("Could not acquire a new Safe Mode session.");
15949
+ owned = true;
15950
+ const lockedFacts = await policyFacts(ctx);
15951
+ if (buildPolicy(id, plan.input, lockedFacts).fingerprint !== plan.fingerprint)
15952
+ throw new Error("Configuration changed while acquiring Safe Mode; create a new preview.");
15953
+ const started = Date.now();
15954
+ for (const command of plan.commands) {
15955
+ if (Date.now() - started > 120000)
15956
+ throw new Error("Policy apply exceeded its time budget.");
15957
+ await checkedRead(command, ctx);
15958
+ }
15959
+ const tag = `mcp-home-${id}`;
15960
+ const count = (await checkedRead(new Cmd("/system scheduler print count-only").raw(`where comment=${quoteValue(tag)}`).build(), ctx)).trim();
15961
+ if (count !== "2")
15962
+ throw new Error("Router-side expiry could not be verified.");
15963
+ const parsed = (await checkedRead(`:put [:typeof [:parse [/system scheduler get [find where name=${quoteValue(tag)}] on-event]]]`, ctx)).trim();
15964
+ if (parsed !== "code")
15965
+ throw new Error("Router could not compile the expiry script.");
15966
+ await verifyPolicyObjects(plan, lockedFacts, ctx);
15967
+ await checkedRead("/system identity print", ctx);
15968
+ const outcome = await safe.commit();
15969
+ if (!outcome.ok)
15970
+ throw new Error("Commit outcome is uncertain; inspect the router before retrying.");
15971
+ owned = false;
15972
+ plan.startsAt = started + plan.input.startInMinutes * 60000;
15973
+ plan.endsAt = plan.startsAt + plan.input.minutes * 60000;
15974
+ plan.status = plan.input.startInMinutes ? "scheduled" : "active";
15975
+ store.savePlan(plan);
15976
+ return plan;
15977
+ } catch (error) {
15978
+ if (owned)
15979
+ await safe.rollback().catch(() => {});
15980
+ plan.status = "uncertain";
15981
+ plan.error = error instanceof Error ? error.message : "Policy operation failed";
15982
+ store.savePlan(plan);
15983
+ throw new Error(`Policy not confirmed: ${plan.error}. Inspect/undo policy ${id}; do not blindly retry.`);
15984
+ }
15985
+ });
15986
+ }
15987
+ async function undoPolicy(id, confirm, ctx) {
15988
+ const device = resolveDeviceName2(ctx.device);
15989
+ assertDeviceAccess([device], "undo_home_policy", "WRITE");
15990
+ if (!confirm)
15991
+ throw new Error("Explicit confirmation is required to undo a policy.");
15992
+ return exclusive(device, async () => {
15993
+ const store = await homeStore(), plan = store.plan(id, device);
15994
+ if (!plan || plan.status === "preview")
15995
+ throw new Error("No applied policy on this router.");
15996
+ if (plan.status === "undone")
15997
+ return plan;
15998
+ const safe = getSafeModeManager2(device);
15999
+ if (safe.isActive)
16000
+ throw new Error("Finish the active Safe Mode session first.");
16001
+ const status = await safe.enable();
16002
+ if (!status.startsWith("Safe mode ENABLED"))
16003
+ throw new Error("Could not acquire Safe Mode.");
16004
+ try {
16005
+ await checkedRead(new Cmd(`/system scheduler disable ${tagSelector(`mcp-home-${id}`)}`).build(), ctx);
16006
+ for (const cmd of plan.undo)
16007
+ await checkedRead(cmd, ctx);
16008
+ if (plan.input.action === "priority") {
16009
+ const expected = plan.queueBefore;
16010
+ if (!expected)
16011
+ throw new Error("Missing queue restoration evidence; reconcile this policy manually.");
16012
+ const current = await rows("/queue simple", "name,target,parent,priority", ctx);
16013
+ const matching = current.filter((q) => q.name === expected.name && q.target === expected.target && q.parent === expected.parent);
16014
+ if (matching.length !== 1 || matching[0].priority !== expected.priority)
16015
+ throw new Error("Queue restoration was not verified. External queue changes require manual reconciliation.");
16016
+ }
16017
+ for (const path of [
16018
+ "/system scheduler",
16019
+ "/ip firewall address-list",
16020
+ "/ip firewall filter",
16021
+ "/ip firewall mangle"
16022
+ ]) {
16023
+ const remaining = (await checkedRead(new Cmd(`${path} print count-only`).raw(`where comment=${quoteValue(`mcp-home-${id}`)}`).build(), ctx)).trim();
16024
+ if (remaining !== "0")
16025
+ throw new Error("Policy cleanup could not be verified; the undo was not committed.");
16026
+ }
16027
+ const committed = await safe.commit();
16028
+ if (!committed.ok)
16029
+ throw new Error("Undo commit could not be confirmed");
16030
+ plan.status = "undone";
16031
+ store.savePlan(plan);
16032
+ return plan;
16033
+ } catch (e) {
16034
+ await safe.rollback().catch(() => {});
16035
+ throw e;
16036
+ }
16037
+ });
16038
+ }
16039
+ async function verifyPolicyObjects(plan, before, ctx) {
16040
+ const tag = `mcp-home-${plan.id}`;
16041
+ const marker = (await checkedRead(new Cmd("/ip firewall address-list print count-only").raw(`where list=${quoteValue(`${tag}-end`)}`).build(), ctx)).trim();
16042
+ if (marker !== "1")
16043
+ throw new Error("Expiry marker could not be verified.");
16044
+ if (plan.input.action === "priority") {
16045
+ const old = before.queues.find((q) => q.target === `${plan.ip}/32` && enabled2(q));
16046
+ const current = await rows("/queue simple", "name,target,parent,priority,max-limit,disabled", ctx);
16047
+ const q = current.find((r) => r.name === old.name && r.target === old.target && r.parent === old.parent);
16048
+ if (!q || q.priority !== (plan.input.startInMinutes ? old.priority : "1/1"))
16049
+ throw new Error("Meeting queue priority was not verified.");
16050
+ } else {
16051
+ const path = plan.input.action === "pause" ? "/ip firewall filter" : "/ip firewall mangle";
16052
+ 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);
16053
+ const owned = current.filter((r) => r.comment === tag);
16054
+ if (owned.length !== (plan.input.action === "pause" ? 2 : 1) || owned.some((r) => enabled2(r) === plan.input.startInMinutes > 0))
16055
+ throw new Error("Policy rules were not verified in their expected state.");
16056
+ if (plan.input.action === "pause") {
16057
+ 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)
16058
+ throw new Error("Pause rule targeting could not be verified.");
16059
+ } 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`)) {
16060
+ throw new Error("Path selection targeting could not be verified.");
16061
+ }
16062
+ }
16063
+ }
16064
+
16065
+ // src/tools/home-internet.ts
16066
+ var homeInternetTools = [
16067
+ defineTool2({
16068
+ name: "diagnose_home_internet",
16069
+ title: "Why Is My Internet Slow?",
16070
+ annotations: READ,
16071
+ 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.",
16072
+ inputSchema: diagnosisInput.shape,
16073
+ handler: async (a, ctx) => JSON.stringify(await diagnoseInternet(a, ctx))
16074
+ }),
16075
+ defineTool2({
16076
+ name: "compare_home_paths",
16077
+ title: "Compare Internet Paths",
16078
+ annotations: READ,
16079
+ 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.",
16080
+ inputSchema: compareInput.shape,
16081
+ handler: async (a, ctx) => JSON.stringify(await comparePaths(a, ctx))
16082
+ }),
16083
+ defineTool2({
16084
+ name: "get_home_internet",
16085
+ title: "Read Household Internet Workspace",
16086
+ annotations: READ,
16087
+ 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.",
16088
+ inputSchema: {},
16089
+ async handler(_a, ctx) {
16090
+ const device = resolveDeviceName2(ctx.device);
16091
+ assertDeviceAccess([device], "get_home_internet", "READ");
16092
+ const store = await homeStore();
16093
+ return JSON.stringify({
16094
+ device,
16095
+ clients: store.clients(device),
16096
+ policies: store.plans(device),
16097
+ statusNote: "Saved status only. A passed expiry time is not a verified cleanup result; Undo can reconcile owned objects."
16098
+ });
16099
+ }
16100
+ }),
16101
+ defineTool2({
16102
+ name: "refresh_home_devices",
16103
+ title: "Discover Household Devices",
16104
+ annotations: WRITE,
16105
+ 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.",
16106
+ inputSchema: {},
16107
+ async handler(_a, ctx) {
16108
+ const device = resolveDeviceName2(ctx.device);
16109
+ assertDeviceAccess([device], "refresh_home_devices", "WRITE");
16110
+ const leases = await rows("/ip dhcp-server lease", "address,mac-address,host-name,status", ctx);
16111
+ const tables = await rows("/routing table", "name,fib,disabled", ctx);
16112
+ const store = await homeStore(), old = store.clients(device), now = Date.now();
16113
+ const seen = new Set;
16114
+ for (const r of leases) {
16115
+ const parsed = macInput.safeParse(r["mac-address"]);
16116
+ if (!parsed.success)
16117
+ continue;
16118
+ const mac = parsed.data.toUpperCase(), prior = old.find((c) => c.mac === mac);
16119
+ seen.add(mac);
16120
+ store.saveClient(device, {
16121
+ mac,
16122
+ ip: r.address ?? "",
16123
+ hostname: r["host-name"] ?? "",
16124
+ name: prior?.name ?? "",
16125
+ person: prior?.person ?? "",
16126
+ firstSeen: prior?.firstSeen ?? now,
16127
+ lastSeen: now,
16128
+ acknowledged: prior?.acknowledged ?? old.length === 0,
16129
+ present: r.status === "bound"
16130
+ });
16131
+ }
16132
+ for (const client of old)
16133
+ if (!seen.has(client.mac))
16134
+ store.saveClient(device, { ...client, present: false });
16135
+ return JSON.stringify({
16136
+ device,
16137
+ clients: store.clients(device),
16138
+ tables: tables.filter((t) => enabled2(t) && ["yes", "true"].includes(t.fib)).map((t) => t.name)
16139
+ });
16140
+ }
16141
+ }),
16142
+ defineTool2({
16143
+ name: "name_home_device",
16144
+ title: "Name a Household Device",
16145
+ annotations: WRITE,
16146
+ 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.",
16147
+ inputSchema: {
16148
+ mac: macInput,
16149
+ name: string().trim().max(80),
16150
+ person: string().trim().max(80).default("")
16151
+ },
16152
+ async handler(a, ctx) {
16153
+ const device = resolveDeviceName2(ctx.device);
16154
+ assertDeviceAccess([device], "name_home_device", "WRITE");
16155
+ const store = await homeStore(), client = store.clients(device).find((c) => c.mac === a.mac.toUpperCase());
16156
+ if (!client)
16157
+ throw new Error("Refresh household devices first.");
16158
+ const result = { ...client, name: a.name, person: a.person, acknowledged: true };
16159
+ store.saveClient(device, result);
16160
+ return JSON.stringify(result);
16161
+ }
16162
+ }),
16163
+ defineTool2({
16164
+ name: "preview_home_policy",
16165
+ title: "Preview a Temporary Household Policy",
16166
+ annotations: WRITE,
16167
+ 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.",
16168
+ inputSchema: policyInput.shape,
16169
+ handler: async (a, ctx) => JSON.stringify(await previewPolicy(a, ctx))
16170
+ }),
16171
+ defineTool2({
16172
+ name: "apply_home_policy",
16173
+ title: "Apply an Approved Household Policy",
16174
+ annotations: WRITE,
16175
+ 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.",
16176
+ inputSchema: { id: uuid2(), confirm: boolean().default(false) },
16177
+ handler: async (a, ctx) => JSON.stringify(await applyPolicy(a.id, a.confirm, ctx))
16178
+ }),
16179
+ defineTool2({
16180
+ name: "undo_home_policy",
16181
+ title: "Undo a Household Policy",
16182
+ annotations: WRITE,
16183
+ 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.",
16184
+ inputSchema: { id: uuid2(), confirm: boolean().default(false) },
16185
+ handler: async (a, ctx) => JSON.stringify(await undoPolicy(a.id, a.confirm, ctx))
16186
+ })
16187
+ ];
16188
+
16189
+ // src/tools/service-contracts.ts
16190
+ import { randomUUID as randomUUID4 } from "crypto";
16191
+
16192
+ // src/service-contracts/store.ts
16193
+ import { mkdirSync as mkdirSync6 } from "fs";
16194
+ import { dirname as dirname6 } from "path";
15307
16195
  class ContractStore {
15308
16196
  db;
15309
16197
  constructor(db) {
@@ -15329,23 +16217,23 @@ class ContractStore {
15329
16217
  return this.db.query("SELECT body FROM service_contract_runs WHERE contract_id = ? ORDER BY started_at DESC LIMIT 100").all(id).map((r) => JSON.parse(r.body));
15330
16218
  }
15331
16219
  }
15332
- var pending2;
16220
+ var pending3;
15333
16221
  function contractStore() {
15334
- pending2 ??= (async () => {
15335
- mkdirSync4(dirname4(DEFAULT_SNAPSHOT_DB), { recursive: true });
16222
+ pending3 ??= (async () => {
16223
+ mkdirSync6(dirname6(DEFAULT_SNAPSHOT_DB), { recursive: true });
15336
16224
  const { Database } = await import("bun:sqlite");
15337
16225
  const db = new Database(DEFAULT_SNAPSHOT_DB, { create: true });
15338
16226
  db.run("PRAGMA journal_mode = WAL");
15339
16227
  return new ContractStore(db);
15340
16228
  })().catch((e) => {
15341
- pending2 = undefined;
16229
+ pending3 = undefined;
15342
16230
  throw e;
15343
16231
  });
15344
- return pending2;
16232
+ return pending3;
15345
16233
  }
15346
16234
 
15347
16235
  // src/service-contracts/run.ts
15348
- import { randomUUID as randomUUID2 } from "crypto";
16236
+ import { randomUUID as randomUUID3 } from "crypto";
15349
16237
 
15350
16238
  // src/policy/parse.ts
15351
16239
  function normalizeSection(path) {
@@ -16652,8 +17540,8 @@ function diffTraces(before, after) {
16652
17540
  }
16653
17541
 
16654
17542
  // src/sim/suites.ts
16655
- import { mkdirSync as mkdirSync5 } from "fs";
16656
- import { dirname as dirname5 } from "path";
17543
+ import { mkdirSync as mkdirSync7 } from "fs";
17544
+ import { dirname as dirname7 } from "path";
16657
17545
  var SCHEMA = [
16658
17546
  `CREATE TABLE IF NOT EXISTS sim_suites (
16659
17547
  id TEXT PRIMARY KEY,
@@ -16699,16 +17587,16 @@ class SqliteSuiteStore {
16699
17587
  });
16700
17588
  }
16701
17589
  }
16702
- var storePromise3 = null;
17590
+ var storePromise4 = null;
16703
17591
  async function store2() {
16704
- storePromise3 ??= (async () => {
17592
+ storePromise4 ??= (async () => {
16705
17593
  try {
16706
- mkdirSync5(dirname5(DEFAULT_SNAPSHOT_DB), { recursive: true });
17594
+ mkdirSync7(dirname7(DEFAULT_SNAPSHOT_DB), { recursive: true });
16707
17595
  } catch {}
16708
17596
  const { Database } = await import("bun:sqlite");
16709
17597
  return new SqliteSuiteStore(new Database(DEFAULT_SNAPSHOT_DB, { create: true }));
16710
17598
  })();
16711
- return storePromise3;
17599
+ return storePromise4;
16712
17600
  }
16713
17601
  async function getSuite(id) {
16714
17602
  try {
@@ -16718,30 +17606,6 @@ async function getSuite(id) {
16718
17606
  }
16719
17607
  }
16720
17608
 
16721
- // src/snapshots/format.ts
16722
- import { createHash } from "crypto";
16723
- var TIMESTAMP_HEADER = /^#\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b.*by RouterOS/i;
16724
- function parseExportMeta(body) {
16725
- const head = body.slice(0, 600);
16726
- const version = head.match(/by RouterOS ([^\s#]+)/i)?.[1];
16727
- const exportedAt = head.match(/#\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)?.[1];
16728
- return { rosVersion: version, exportedAt };
16729
- }
16730
- function normalizeExport(body) {
16731
- return body.replace(/\r\n/g, `
16732
- `).split(`
16733
- `).filter((line) => !TIMESTAMP_HEADER.test(line)).join(`
16734
- `).replace(/\n+$/, "");
16735
- }
16736
- function contentSha(normalizedBody) {
16737
- return createHash("sha256").update(normalizedBody, "utf8").digest("hex").slice(0, 16);
16738
- }
16739
- function countLines(body) {
16740
- const trimmed = body.replace(/\n+$/, "");
16741
- return trimmed === "" ? 0 : trimmed.split(`
16742
- `).length;
16743
- }
16744
-
16745
17609
  // src/service-contracts/probe.ts
16746
17610
  import { Resolver } from "dns/promises";
16747
17611
  import { connect, isIP } from "net";
@@ -16904,7 +17768,7 @@ async function evaluateContract(contract, io, simulationExport) {
16904
17768
  }
16905
17769
  }
16906
17770
  return {
16907
- id: randomUUID2(),
17771
+ id: randomUUID3(),
16908
17772
  contractId: contract.id,
16909
17773
  device: contract.device,
16910
17774
  startedAt,
@@ -17029,7 +17893,7 @@ var serviceContractTools = [
17029
17893
  const args = contractInput.parse(a);
17030
17894
  if (args.checks.some((c) => !getConfig2().serviceProbes.targets[c.target]))
17031
17895
  throw new Error("Contract references an unapproved target. Ask the administrator to configure it.");
17032
- const contract = { ...args, id: randomUUID3(), device, createdAt: Date.now() };
17896
+ const contract = { ...args, id: randomUUID4(), device, createdAt: Date.now() };
17033
17897
  (await contractStore()).save(contract);
17034
17898
  return JSON.stringify(contract);
17035
17899
  }
@@ -17073,146 +17937,6 @@ var serviceContractTools = [
17073
17937
  })
17074
17938
  ];
17075
17939
 
17076
- // src/snapshots/store.ts
17077
- import { mkdirSync as mkdirSync6 } from "fs";
17078
- import { dirname as dirname6 } from "path";
17079
- function rowToBaseline(r) {
17080
- return {
17081
- device: r.device,
17082
- snapshotId: r.snapshot_id,
17083
- setAt: r.set_at,
17084
- setBy: r.set_by,
17085
- label: r.label ?? undefined,
17086
- notes: r.notes ?? undefined
17087
- };
17088
- }
17089
- function rowToSnapshot(r, body) {
17090
- return {
17091
- id: r.id,
17092
- device: r.device,
17093
- ts: r.ts,
17094
- label: r.label ?? undefined,
17095
- rosVersion: r.ros_version ?? undefined,
17096
- body,
17097
- bytes: r.bytes,
17098
- lines: r.lines,
17099
- sha: r.sha
17100
- };
17101
- }
17102
- var SCHEMA_STATEMENTS3 = [
17103
- `CREATE TABLE IF NOT EXISTS snapshots (
17104
- id TEXT PRIMARY KEY,
17105
- device TEXT NOT NULL,
17106
- ts INTEGER NOT NULL,
17107
- label TEXT,
17108
- ros_version TEXT,
17109
- body TEXT NOT NULL,
17110
- bytes INTEGER NOT NULL,
17111
- lines INTEGER NOT NULL,
17112
- sha TEXT NOT NULL
17113
- )`,
17114
- "CREATE INDEX IF NOT EXISTS idx_snapshots_device_ts ON snapshots(device, ts)",
17115
- `CREATE TABLE IF NOT EXISTS baselines (
17116
- device TEXT PRIMARY KEY,
17117
- snapshot_id TEXT NOT NULL,
17118
- set_at INTEGER NOT NULL,
17119
- set_by TEXT NOT NULL DEFAULT 'agent',
17120
- label TEXT,
17121
- notes TEXT
17122
- )`
17123
- ];
17124
-
17125
- class SqliteSnapshotStore {
17126
- db;
17127
- constructor(db) {
17128
- this.db = db;
17129
- db.run("PRAGMA journal_mode = WAL");
17130
- db.run("PRAGMA synchronous = NORMAL");
17131
- for (const stmt of SCHEMA_STATEMENTS3)
17132
- db.run(stmt);
17133
- }
17134
- insert(s) {
17135
- this.db.query(`INSERT OR REPLACE INTO snapshots
17136
- (id, device, ts, label, ros_version, body, bytes, lines, sha)
17137
- VALUES ($id,$device,$ts,$label,$ver,$body,$bytes,$lines,$sha)`).run({
17138
- $id: s.id,
17139
- $device: s.device,
17140
- $ts: s.ts,
17141
- $label: s.label ?? null,
17142
- $ver: s.rosVersion ?? null,
17143
- $body: s.body,
17144
- $bytes: s.bytes,
17145
- $lines: s.lines,
17146
- $sha: s.sha
17147
- });
17148
- }
17149
- get(id) {
17150
- const row = this.db.query("SELECT * FROM snapshots WHERE id = $id").get({ $id: id });
17151
- return row ? rowToSnapshot(row, row.body) : null;
17152
- }
17153
- latest(device) {
17154
- const row = this.db.query("SELECT * FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT 1").get({ $d: device });
17155
- return row ? rowToSnapshot(row, row.body) : null;
17156
- }
17157
- list(device, limit = 50, withBody = false) {
17158
- const cols = withBody ? "*" : "id, device, ts, label, ros_version, bytes, lines, sha";
17159
- const n = Math.min(Math.max(limit, 1), 500);
17160
- const rows = this.db.query(`SELECT ${cols} FROM snapshots WHERE device = $d ORDER BY ts DESC LIMIT $n`).all({ $d: device, $n: n });
17161
- return rows.map((r) => rowToSnapshot(r, withBody ? r.body : ""));
17162
- }
17163
- count(device) {
17164
- const r = this.db.query("SELECT COUNT(*) AS n FROM snapshots WHERE device = $d").get({ $d: device });
17165
- return r.n;
17166
- }
17167
- delete(ids) {
17168
- if (ids.length === 0)
17169
- return 0;
17170
- const placeholders = ids.map((_, j) => `$id${j}`).join(",");
17171
- const params = {};
17172
- ids.forEach((id, j) => {
17173
- params[`$id${j}`] = id;
17174
- });
17175
- const res = this.db.query(`DELETE FROM snapshots WHERE id IN (${placeholders})`).run(params);
17176
- return Number(res.changes ?? 0);
17177
- }
17178
- setBaseline(device, snapshotId, setBy = "agent", label, notes) {
17179
- this.db.query(`INSERT OR REPLACE INTO baselines (device, snapshot_id, set_at, set_by, label, notes)
17180
- VALUES ($device, $snapId, $setAt, $setBy, $label, $notes)`).run({
17181
- $device: device,
17182
- $snapId: snapshotId,
17183
- $setAt: Date.now(),
17184
- $setBy: setBy,
17185
- $label: label ?? null,
17186
- $notes: notes ?? null
17187
- });
17188
- }
17189
- getBaseline(device) {
17190
- const row = this.db.query("SELECT * FROM baselines WHERE device = $d").get({ $d: device });
17191
- return row ? rowToBaseline(row) : null;
17192
- }
17193
- removeBaseline(device) {
17194
- const res = this.db.query("DELETE FROM baselines WHERE device = $d").run({ $d: device });
17195
- return (res.changes ?? 0) > 0;
17196
- }
17197
- listBaselines() {
17198
- const rows = this.db.query("SELECT * FROM baselines ORDER BY set_at DESC").all();
17199
- return rows.map(rowToBaseline);
17200
- }
17201
- close() {
17202
- this.db.close();
17203
- }
17204
- }
17205
- async function openSnapshotStore(path) {
17206
- if (path !== ":memory:") {
17207
- try {
17208
- mkdirSync6(dirname6(path), { recursive: true });
17209
- } catch {}
17210
- }
17211
- const { Database } = await import("bun:sqlite");
17212
- const db = new Database(path, { create: true });
17213
- return new SqliteSnapshotStore(db);
17214
- }
17215
-
17216
17940
  // src/paths/round-trip.ts
17217
17941
  var hop = object({
17218
17942
  device: string().min(1).max(128),
@@ -17423,21 +18147,21 @@ import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
17423
18147
 
17424
18148
  // src/paths.ts
17425
18149
  import { existsSync } from "fs";
17426
- import { join as join2, dirname as dirname7 } from "path";
18150
+ import { join as join2, dirname as dirname8 } from "path";
17427
18151
  import { fileURLToPath } from "url";
17428
18152
  var meta3 = import.meta;
17429
- var HERE = meta3.dir ?? meta3.dirname ?? dirname7(fileURLToPath(import.meta.url));
18153
+ var HERE = meta3.dir ?? meta3.dirname ?? dirname8(fileURLToPath(import.meta.url));
17430
18154
  function findRoot(start) {
17431
18155
  let dir = start;
17432
18156
  for (let i = 0;i < 12; i++) {
17433
18157
  if (existsSync(join2(dir, "package.json")))
17434
18158
  return dir;
17435
- const parent = dirname7(dir);
18159
+ const parent = dirname8(dir);
17436
18160
  if (parent === dir)
17437
18161
  break;
17438
18162
  dir = parent;
17439
18163
  }
17440
- return dirname7(start);
18164
+ return dirname8(start);
17441
18165
  }
17442
18166
  var ROOT = findRoot(HERE);
17443
18167
  var PROMPTS_DIR = join2(ROOT, "prompts");
@@ -17694,7 +18418,7 @@ async function checkDiskSpace(ctx) {
17694
18418
  // src/backups/vault.ts
17695
18419
  import {
17696
18420
  existsSync as existsSync2,
17697
- mkdirSync as mkdirSync7,
18421
+ mkdirSync as mkdirSync8,
17698
18422
  readFileSync as readFileSync4,
17699
18423
  readdirSync,
17700
18424
  renameSync,
@@ -17741,7 +18465,7 @@ function readBackup(name) {
17741
18465
  }
17742
18466
  function writeBackup(name, content) {
17743
18467
  const dir = backupDir();
17744
- mkdirSync7(dir, { recursive: true });
18468
+ mkdirSync8(dir, { recursive: true });
17745
18469
  let final = safeName(name);
17746
18470
  if (existsSync2(join4(dir, final))) {
17747
18471
  const dot = final.lastIndexOf(".");
@@ -17757,7 +18481,7 @@ function writeBackup(name, content) {
17757
18481
  }
17758
18482
  function writeBinaryBackup(name, data) {
17759
18483
  const dir = backupDir();
17760
- mkdirSync7(dir, { recursive: true });
18484
+ mkdirSync8(dir, { recursive: true });
17761
18485
  let final = safeName(name);
17762
18486
  if (existsSync2(join4(dir, final))) {
17763
18487
  const dot = final.lastIndexOf(".");
@@ -20984,11 +21708,11 @@ No differences \u2014 the live configuration matches the golden baseline.`);
20984
21708
  }
20985
21709
 
20986
21710
  // src/tools/config-drift.ts
20987
- var storePromise4 = null;
21711
+ var storePromise5 = null;
20988
21712
  function store3() {
20989
- if (!storePromise4)
20990
- storePromise4 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
20991
- return storePromise4;
21713
+ if (!storePromise5)
21714
+ storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
21715
+ return storePromise5;
20992
21716
  }
20993
21717
  function buildExport(opts) {
20994
21718
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -21196,11 +21920,11 @@ New: ${describeBaseline(snap)}${notesLine}`;
21196
21920
  ];
21197
21921
 
21198
21922
  // src/tools/config-snapshot.ts
21199
- var storePromise5 = null;
21200
- function snapshots() {
21201
- if (!storePromise5)
21202
- storePromise5 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
21203
- return storePromise5;
21923
+ var storePromise6 = null;
21924
+ function snapshots2() {
21925
+ if (!storePromise6)
21926
+ storePromise6 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
21927
+ return storePromise6;
21204
21928
  }
21205
21929
  function exportCommand(opts) {
21206
21930
  const base = opts.section ? `/${opts.section} export` : "/export";
@@ -21257,7 +21981,7 @@ var configSnapshotTools = [
21257
21981
  });
21258
21982
  const meta = parseExportMeta(body);
21259
21983
  const sha = contentSha(normalizeExport(body));
21260
- const store = await snapshots();
21984
+ const store = await snapshots2();
21261
21985
  const prev = store.latest(device);
21262
21986
  if (prev && prev.sha === sha && !a.force) {
21263
21987
  return `No configuration change since the last snapshot \u2014 nothing stored.
@@ -21293,7 +22017,7 @@ ${drift}`;
21293
22017
  },
21294
22018
  async handler(a, ctx) {
21295
22019
  const device = resolveDeviceName2(ctx.device);
21296
- const store = await snapshots();
22020
+ const store = await snapshots2();
21297
22021
  const rows = store.list(device, a.limit, false);
21298
22022
  if (rows.length === 0) {
21299
22023
  return `No configuration snapshots stored for '${device}'. Capture one with capture_config_snapshot.`;
@@ -21316,7 +22040,7 @@ ${lines}`;
21316
22040
  include_body: boolean().default(true)
21317
22041
  },
21318
22042
  async handler(a, ctx) {
21319
- const store = await snapshots();
22043
+ const store = await snapshots2();
21320
22044
  const snap = store.get(a.id);
21321
22045
  if (!snap)
21322
22046
  return `Snapshot '${a.id}' not found.`;
@@ -21344,7 +22068,7 @@ ${snap.body}
21344
22068
  },
21345
22069
  async handler(a, ctx) {
21346
22070
  const device = resolveDeviceName2(ctx.device);
21347
- const store = await snapshots();
22071
+ const store = await snapshots2();
21348
22072
  const from = await resolveRef(store, a.from, device, ctx);
21349
22073
  const to = await resolveRef(store, a.to, device, ctx);
21350
22074
  const result = diffLines(normalizeExport(from.body), normalizeExport(to.body), {
@@ -21384,7 +22108,7 @@ ${result.unified}`;
21384
22108
  ids: array(string()).min(1)
21385
22109
  },
21386
22110
  async handler(a) {
21387
- const store = await snapshots();
22111
+ const store = await snapshots2();
21388
22112
  const removed = store.delete(a.ids);
21389
22113
  if (removed === 0)
21390
22114
  return `No snapshots removed (none of the given ids matched).`;
@@ -21695,10 +22419,10 @@ ${created.join(`
21695
22419
  import * as ipaddr2 from "ipaddr.js";
21696
22420
 
21697
22421
  // src/schedule/identity.ts
21698
- import { createHash as createHash2 } from "crypto";
22422
+ import { createHash as createHash3 } from "crypto";
21699
22423
  function stableId(prefix, parts) {
21700
22424
  const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
21701
- const digest = createHash2("sha256").update(material, "utf8").digest("hex").slice(0, 12);
22425
+ const digest = createHash3("sha256").update(material, "utf8").digest("hex").slice(0, 12);
21702
22426
  return `${prefix}:${digest}`;
21703
22427
  }
21704
22428
  function ruleFingerprint(rule) {
@@ -23024,7 +23748,7 @@ var cache2 = null;
23024
23748
  async function gateway() {
23025
23749
  if (cache2)
23026
23750
  return cache2;
23027
- const { moduleCatalog } = await import("./library-drn9gmjm.js");
23751
+ const { moduleCatalog } = await import("./library-56rhcw1r.js");
23028
23752
  const forIndex = [];
23029
23753
  const byName = new Map;
23030
23754
  for (const mod of moduleCatalog) {
@@ -25252,34 +25976,6 @@ No findings \u2014 the device passes every hardening check. \u2713`;
25252
25976
  ${body}`;
25253
25977
  }
25254
25978
 
25255
- // src/snapshots/capture.ts
25256
- var storePromise6 = null;
25257
- function snapshots2() {
25258
- if (!storePromise6)
25259
- storePromise6 = openSnapshotStore(DEFAULT_SNAPSHOT_DB);
25260
- return storePromise6;
25261
- }
25262
- async function captureSnapshot(ctx, label) {
25263
- const device = resolveDeviceName2(ctx.device);
25264
- const body = await executeMikrotikCommand2("/export terse", ctx);
25265
- const meta = parseExportMeta(body);
25266
- const sha = contentSha(normalizeExport(body));
25267
- const ts = Date.now();
25268
- const snap = {
25269
- id: `snap_${ts}_${sha.slice(0, 8)}`,
25270
- device,
25271
- ts,
25272
- label,
25273
- rosVersion: meta.rosVersion,
25274
- body,
25275
- bytes: Buffer.byteLength(body, "utf8"),
25276
- lines: countLines(body),
25277
- sha
25278
- };
25279
- (await snapshots2()).insert(snap);
25280
- return snap.id;
25281
- }
25282
-
25283
25979
  // src/tools/security-hardening.ts
25284
25980
  async function fetchSecurityState(ctx) {
25285
25981
  const [
@@ -26012,7 +26708,7 @@ function evaluatePolicies(policies, model, opts = {}) {
26012
26708
 
26013
26709
  // src/policy/load.ts
26014
26710
  import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
26015
- import { dirname as dirname8, isAbsolute, join as join5, resolve as resolve3 } from "path";
26711
+ import { dirname as dirname9, isAbsolute, join as join5, resolve as resolve3 } from "path";
26016
26712
 
26017
26713
  // src/policy/schema.ts
26018
26714
  var MAX_REGEX_LENGTH = 200;
@@ -26135,7 +26831,7 @@ function validatePolicyText(text) {
26135
26831
  var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
26136
26832
  function expand(pattern, cwd) {
26137
26833
  const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
26138
- const base = dirname8(absolute);
26834
+ const base = dirname9(absolute);
26139
26835
  const leaf = absolute.slice(base.length + 1);
26140
26836
  if (!leaf.includes("*")) {
26141
26837
  try {
@@ -42843,8 +43539,8 @@ function publishTxn(update) {
42843
43539
  }
42844
43540
 
42845
43541
  // src/txn/store.ts
42846
- import { mkdirSync as mkdirSync8 } from "fs";
42847
- import { dirname as dirname9 } from "path";
43542
+ import { mkdirSync as mkdirSync9 } from "fs";
43543
+ import { dirname as dirname10 } from "path";
42848
43544
  function toRecord(txn, ts, label) {
42849
43545
  return {
42850
43546
  id: txn.id,
@@ -42980,7 +43676,7 @@ class SqliteTxnStore {
42980
43676
  async function openTxnStore(path) {
42981
43677
  if (path !== ":memory:") {
42982
43678
  try {
42983
- mkdirSync8(dirname9(path), { recursive: true });
43679
+ mkdirSync9(dirname10(path), { recursive: true });
42984
43680
  } catch {}
42985
43681
  }
42986
43682
  const { Database } = await import("bun:sqlite");
@@ -43847,8 +44543,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
43847
44543
  }
43848
44544
 
43849
44545
  // src/rollout/store.ts
43850
- import { mkdirSync as mkdirSync9 } from "fs";
43851
- import { dirname as dirname10 } from "path";
44546
+ import { mkdirSync as mkdirSync10 } from "fs";
44547
+ import { dirname as dirname11 } from "path";
43852
44548
  function toRecord2(rollout, ts, opts = {}) {
43853
44549
  return {
43854
44550
  id: rollout.id,
@@ -43981,7 +44677,7 @@ class SqliteRolloutStore {
43981
44677
  async function openRolloutStore(path) {
43982
44678
  if (path !== ":memory:") {
43983
44679
  try {
43984
- mkdirSync9(dirname10(path), { recursive: true });
44680
+ mkdirSync10(dirname11(path), { recursive: true });
43985
44681
  } catch {}
43986
44682
  }
43987
44683
  const { Database } = await import("bun:sqlite");
@@ -44697,8 +45393,8 @@ var JobSchema = object({
44697
45393
  });
44698
45394
 
44699
45395
  // src/schedule/store.ts
44700
- import { mkdirSync as mkdirSync10 } from "fs";
44701
- import { dirname as dirname11 } from "path";
45396
+ import { mkdirSync as mkdirSync11 } from "fs";
45397
+ import { dirname as dirname12 } from "path";
44702
45398
  var SCHEMA2 = [
44703
45399
  `CREATE TABLE IF NOT EXISTS schedule_jobs (
44704
45400
  id TEXT PRIMARY KEY,
@@ -44840,7 +45536,7 @@ class SqliteScheduleStore {
44840
45536
  async function openScheduleStore(path) {
44841
45537
  if (path !== ":memory:") {
44842
45538
  try {
44843
- mkdirSync10(dirname11(path), { recursive: true });
45539
+ mkdirSync11(dirname12(path), { recursive: true });
44844
45540
  } catch {}
44845
45541
  }
44846
45542
  const { Database } = await import("bun:sqlite");
@@ -45002,7 +45698,7 @@ var riskByTool = null;
45002
45698
  async function riskIndex() {
45003
45699
  if (riskByTool)
45004
45700
  return riskByTool;
45005
- const { moduleCatalog } = await import("./library-drn9gmjm.js");
45701
+ const { moduleCatalog } = await import("./library-56rhcw1r.js");
45006
45702
  const index = new Map;
45007
45703
  for (const mod of moduleCatalog) {
45008
45704
  for (const tool of mod.tools)
@@ -47166,7 +47862,7 @@ async function readScanList(ctx, list = "port-scanners") {
47166
47862
  }
47167
47863
 
47168
47864
  // src/attack/correlate.ts
47169
- import { createHash as createHash3 } from "crypto";
47865
+ import { createHash as createHash4 } from "crypto";
47170
47866
  var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
47171
47867
  var STAGE_OF = {
47172
47868
  "port-scan": "recon",
@@ -47196,7 +47892,7 @@ var SEVERITY_RANK = {
47196
47892
  info: 4
47197
47893
  };
47198
47894
  function incidentId(source, dayBucket) {
47199
- const digest = createHash3("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
47895
+ const digest = createHash4("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
47200
47896
  return `atk_${digest}`;
47201
47897
  }
47202
47898
  function worst(values) {
@@ -47418,8 +48114,8 @@ function dedupe(events, seen) {
47418
48114
  }
47419
48115
 
47420
48116
  // src/attack/store.ts
47421
- import { mkdirSync as mkdirSync11 } from "fs";
47422
- import { dirname as dirname12 } from "path";
48117
+ import { mkdirSync as mkdirSync12 } from "fs";
48118
+ import { dirname as dirname13 } from "path";
47423
48119
  var SCHEMA3 = [
47424
48120
  `CREATE TABLE IF NOT EXISTS attack_incidents (
47425
48121
  id TEXT PRIMARY KEY,
@@ -47610,7 +48306,7 @@ class SqliteAttackStore {
47610
48306
  async function openAttackStore(path) {
47611
48307
  if (path !== ":memory:") {
47612
48308
  try {
47613
- mkdirSync11(dirname12(path), { recursive: true });
48309
+ mkdirSync12(dirname13(path), { recursive: true });
47614
48310
  } catch {}
47615
48311
  }
47616
48312
  const { Database } = await import("bun:sqlite");
@@ -48284,9 +48980,9 @@ ${result}`;
48284
48980
  ];
48285
48981
 
48286
48982
  // src/core/update-check.ts
48287
- import { existsSync as existsSync3, mkdirSync as mkdirSync12, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
48983
+ import { existsSync as existsSync3, mkdirSync as mkdirSync13, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "fs";
48288
48984
  import { homedir as homedir2 } from "os";
48289
- import { dirname as dirname13, join as join8 } from "path";
48985
+ import { dirname as dirname14, join as join8 } from "path";
48290
48986
 
48291
48987
  // src/version.ts
48292
48988
  import { readFileSync as readFileSync7 } from "fs";
@@ -48333,9 +49029,9 @@ function loadFileCacheSync() {
48333
49029
  }
48334
49030
  function saveFileCache(data) {
48335
49031
  try {
48336
- const dir = dirname13(CACHE_PATH);
49032
+ const dir = dirname14(CACHE_PATH);
48337
49033
  if (!existsSync3(dir))
48338
- mkdirSync12(dir, { recursive: true });
49034
+ mkdirSync13(dir, { recursive: true });
48339
49035
  writeFileSync2(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
48340
49036
  } catch {}
48341
49037
  }
@@ -53929,6 +54625,13 @@ ${lines.join(`
53929
54625
 
53930
54626
  // src/tools/index.ts
53931
54627
  var moduleCatalog2 = [
54628
+ {
54629
+ label: "Home Internet",
54630
+ slug: "home-internet",
54631
+ group: "System & Ops",
54632
+ description: "Plain-language internet diagnosis, household inventory and approved temporary client policies with bounded path comparisons.",
54633
+ tools: homeInternetTools
54634
+ },
53932
54635
  {
53933
54636
  label: "Multi-Router Round Trip",
53934
54637
  slug: "round-trip",