@astrofoundry/pi-astro 0.40.68 → 0.40.70

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/README.md CHANGED
@@ -69,7 +69,7 @@ pi # launch; confirm [Extensions] lists astro-subagents, grimoire
69
69
  - `gemini-image` - registers `gemini_image` tool (requires a Gemini API key; prompts and saves on first use)
70
70
  - `security-guard` - blocks/prompts destructive bash commands and sensitive file access; configure at `~/.pi/agent/security-guard.json` (example written on first run); `/security-guard status|reload|test`
71
71
  - `astro-discord` - Discord access to the specialists: in the configured channels, `<specialist> <task>` runs `astro.<specialist>` and posts the answer as a reply (⏳ running, 🔒 waiting for an owner's approval of a risky call, ✅ done, ❌ failed). Owners may use every specialist and approve risky calls with buttons; other users only the specialists listed for them; everyone else is ignored. Where the `media` specialist is present, `/trending`, `/search`, and `/downloads` answer without a model, with an Add button beside each title. A channel with `threads` (such as #research) opens a thread on each addressed message, which the specialist names; later messages there need no mention, and `everyone` lets any member use it. Scheduled reports (`reports` in its config): the Arcane Daily Report, with a release-notes verdict on major versions and an Update button per stack that only owners can press, the Cortex Tools Report, which lists every tool on Cortex with a newer version, a release-notes verdict for the tools the specialists build on, and an Update button that only owners can press, and the Security Daily and Weekly Reports (CrowdSec, Wazuh, vulnerabilities, patches, health, backups), whose channel also gets urgent Wazuh alerts within two minutes, with Investigate (the security specialist answers in a thread) and Acknowledge buttons for owners, and the weekly media picks (Fridays: three movies and three series that TMDB recommends for your library, IMDb 7.0 or higher, each with Add and Not interested buttons; an ignored pick may return after six months, a dismissed one never). Inert unless the headless host sets `ASTRO_DISCORD=1`; setup with `d=$(mktemp -d) && cp ~/.pi/agent/npm/node_modules/@astrofoundry/pi-astro/extensions/astro-discord/*.ts "$d" && node --disable-warning=ExperimentalWarning "$d/setup.ts"` (Node refuses to strip types inside `node_modules`, hence the copy), which prompts for the bot token and ids, checks them against Discord, and writes the LaunchAgent. See [specialists/README.md](specialists/README.md#discord).
72
- - `specialist-gate` - gives each specialist agent (`astro.arcane`, `astro.identity`, `astro.network`, `astro.dns`, `astro.edge`, `astro.security`, `astro.backup`, `astro.proxmox`, `astro.inference`, `astro.media`, `astro.research`) its single tool, which runs the matching CLI wrapper as a dedicated macOS user through `sudo`, and blocks every other agent from calling those CLIs or reading their credentials. Inactive until the host has `~/.pi/agent/specialists.json`. `/specialists` prints the status. Host setup is described in [specialists/README.md](specialists/README.md).
72
+ - `specialist-gate` - gives each specialist agent (`astro.arcane`, `astro.identity`, `astro.network`, `astro.dns`, `astro.edge`, `astro.security`, `astro.backup`, `astro.proxmox`, `astro.inference`, `astro.media`, `astro.home`, `astro.research`) its single tool, which runs the matching CLI wrapper as a dedicated macOS user through `sudo`, and blocks every other agent from calling those CLIs or reading their credentials. Inactive until the host has `~/.pi/agent/specialists.json`. `/specialists` prints the status. Host setup is described in [specialists/README.md](specialists/README.md).
73
73
  - `notify-on-stop` - runs a shell command when the agent finishes a turn (sound, voice, desktop notification). **Default: off.** Enable with `/notify on` (state persists in `~/.pi/agent/notify-on-stop.json`); disable with `/notify off`. macOS default command: plays the Glass system sound and speaks "Agent done" via `say` using the **`Samantha (Enhanced)`** voice. Linux default: `notify-send "pi" "Agent done"`. Override the voice with `PI_STOP_NOTIFY_VOICE=<voice-name>` (macOS only; e.g. `Alex`, `Karen`, `Daniel (Enhanced)`). Replace the full command with `PI_STOP_NOTIFY='afplay /System/Library/Sounds/Glass.aiff && say "Done"'`. Hard-kill (overrides `/notify on`) with `PI_STOP_NOTIFY_OFF=1`. Commands: `/notify [on|off|status|test]`. See [extensions/notify-on-stop/README.md](extensions/notify-on-stop/README.md) for full details.
74
74
  - **macOS voice install (required once for the default):** open **System Settings, Accessibility, Spoken Content, System Voice, Manage Voices...**, expand **English**, check **Samantha (Enhanced)**, click **Done** to download (~500 MB to 1 GB). Verify with `say -v "Samantha (Enhanced)" hi`. If the voice is missing, `say` errors silently and you'll only hear the Glass sound.
75
75
  - `vscode-image` - only active inside VS Code's integrated terminal (`TERM_PROGRAM=vscode`). Switches pi-tui's image output to the **Kitty graphics protocol** so images returned by tools like `gemini_image` render as real pixels instead of the `[Image: ...]` text fallback. **Requires enabling `Terminal > Integrated: Enable Images` in VS Code settings** (off by default); restart the integrated terminal after flipping it. Disable with `PI_VSCODE_IMAGE_OFF=1`. `/vscode-image` prints current status.
@@ -80,13 +80,13 @@ pi # launch; confirm [Extensions] lists astro-subagents, grimoire
80
80
 
81
81
  **Bundled subagents** (call them as `astro.<name>`):
82
82
  - General-purpose: `code-reviewer`, `google-tech-lead`, `spec-writer`, `tester-api`, `tester-ui`, `ui-architect`, `ui-design-system`, `ui-frontend-developer`
83
- - Specialists (one homelab area each, need the host setup in [specialists/README.md](specialists/README.md)): `arcane` (Arcane container platform, GitOps first; sanitized host checks, Mealie and Paperless dumps, stack image updates with rollback, and the documented manager upgrade, both with buttons on the daily report), `identity` (Zitadel, Pomerium routes through the homelab repository, certificates), `network` (UniFi consoles of sites 37 and Mira: reads and every Network API write, through the cloud with local fallback; FreeRADIUS, Tailscale), `dns` (Technitium resolvers, Cloudflare zones), `edge` (Frontdoor VPS over IAP, nginx SNI allowlist through the homelab repository, public route checks), `security` (Wazuh, CrowdSec, log archive, read-only), `backup` (vzdump, Restic layers, GCS offsite, restore tests), `proxmox` (guest lifecycle, snapshots, resources; no create or destroy), `inference` (llama.cpp on Nexus, Europa health), `media` (trendarr: trending titles, recommendations from the library, Radarr and Sonarr adds, SABnzbd pause), `research` (internet research in a thread per request in #research: numbered questions first, then facts checked in a sandbox Chrome at Mira with a UAE address, per-category defaults, captchas solved by an owner in a live view)
83
+ - Specialists (one homelab area each, need the host setup in [specialists/README.md](specialists/README.md)): `arcane` (Arcane container platform, GitOps first; sanitized host checks, Mealie and Paperless dumps, stack image updates with rollback, and the documented manager upgrade, both with buttons on the daily report), `identity` (Zitadel, Pomerium routes through the homelab repository, certificates), `network` (UniFi consoles of sites 37 and Mira: reads and every Network API write, through the cloud with local fallback; FreeRADIUS, Tailscale), `dns` (Technitium resolvers, Cloudflare zones), `edge` (Frontdoor VPS over IAP, nginx SNI allowlist through the homelab repository, public route checks), `security` (Wazuh, CrowdSec, log archive, read-only), `backup` (vzdump, Restic layers, GCS offsite, restore tests), `proxmox` (guest lifecycle, snapshots, resources; no create or destroy), `inference` (llama.cpp on Nexus, Europa health), `media` (trendarr: trending titles, recommendations from the library, Radarr and Sonarr adds, SABnzbd pause), `research` (internet research in a thread per request in #research: numbered questions first, then facts checked in a sandbox Chrome at Mira with a UAE address, per-category defaults, captchas solved by an owner in a live view), `home` (Home Assistant: health, problems, logs, updates, and actions)
84
84
  - Release notes: `release-reviewer` (no tools; judges whether an update could break how we use a tool or image, for the Cortex Tools Report and the Arcane Daily Report)
85
85
  - Supervision: `foreman` (read only; diagnoses an unattended update that failed its check, through the specialists)
86
86
  - Flourish pipeline: `flourish-input-vision` (image to spec), `flourish-input-narrative` (text to spec), `flourish-input-codebase` (HTML to spec), `flourish-architect` (spec to plan), `flourish-template-developer` (plan to SDK template, needs `@flourish/sdk`), `flourish-example-builder` (template to realistic example), `flourish-preview-runner` (multi-breakpoint preview + screenshots, needs `@flourish/sdk`), `flourish-reviewer` (audit)
87
87
 
88
88
  **Skills** (loadable via `/skill:<name>`):
89
- - `playwright-cli`, `postman-cli`, `raycast-script-creator`, `caveman`, `flourish-chart-spec`, `arcane`, `identity`, `network`, `dns`, `edge`, `security`, `backup`, `proxmox`, `inference`, `media`, `research` (the last eleven are injected into their specialist agents)
89
+ - `playwright-cli`, `postman-cli`, `raycast-script-creator`, `caveman`, `flourish-chart-spec`, `arcane`, `identity`, `network`, `dns`, `edge`, `security`, `backup`, `proxmox`, `inference`, `media`, `research`, `home` (the last twelve are injected into their specialist agents)
90
90
 
91
91
  **Theme:**
92
92
  - `astro` - dark, gold accent, GitHub-dark-inspired
package/agents/home.md ADDED
@@ -0,0 +1,23 @@
1
+ ---
2
+ name: home
3
+ description: Watches and operates Home Assistant through the home tool, covering versions and Supervisor health, integrations that did not load, repairs, waiting updates, backups, disk space, unavailable entities, logs, updates, restarts, and any Home Assistant action. Use for what is wrong with the smart home, why a device or integration fails, installing a Home Assistant update, and switching or checking a device.
4
+ tools: home, subagent
5
+ skills: home
6
+ systemPromptMode: replace
7
+ inheritProjectContext: false
8
+ inheritSkills: false
9
+ maxSubagentDepth: 1
10
+ model: openai-codex/gpt-6-astra
11
+ thinking: xhigh
12
+ ---
13
+ You are the home specialist. The `home` tool is your only way to reach Home Assistant, which runs as a virtual machine at Mira. You have no shell, no web, and no file access; if a task needs anything else, say so and stop.
14
+
15
+ Rules:
16
+
17
+ - Read first: `status` or `problems` before you explain or change anything. Name what you read, not what you assume.
18
+ - A part that could not be read is a finding, never a pass. Say which part.
19
+ - Change only what the task asks for. `update`, `restart`, and `action` ask an owner for approval in chat; say what you are about to run and why before you call them.
20
+ - Find the cause before you restart. Read `logs core` or the add-on's log for a failing integration; a restart is the last step, not the first.
21
+ - Never print a token, a password, or a URL that carries one; summarise such a log line.
22
+ - Keep replies short: the finding, the cause when you know it, and the one next step. When the owner must act, start with `**Needs you:**`.
23
+ - The virtual machine itself (stop, start, memory, snapshots) is `astro.proxmox`'s area (`space-x`, VM 112); the network path is `astro.network`'s. Delegate through `subagent` only to another specialist and only for that specialist's own area.
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import type { ArcaneReport } from "./daily-report.ts";
3
3
  import type { ToolsReport } from "./tools-report.ts";
4
- import { type AreaStatus, agoSeconds, arcaneSummary, guestOwner, backupStatus, dnsStatus, macosStatus, edgeStatus, identityStatus, pomeriumButtonId, wazuhRelease, inferenceStatus, mediaStatus, networkStatus, pendingPackageLines, problemSpecialist, problemsToPost, problemText, proxmoxStatus, summaryText, technitiumPlan, toolsSummary, updatesStatus } from "./daily-run.ts";
4
+ import { type AreaStatus, agoSeconds, arcaneSummary, guestOwner, backupStatus, dnsStatus, homeStatus, macosStatus, edgeStatus, identityStatus, pomeriumButtonId, wazuhRelease, inferenceStatus, mediaStatus, networkStatus, pendingPackageLines, problemSpecialist, problemsToPost, problemText, proxmoxStatus, summaryText, technitiumPlan, toolsSummary, updatesStatus } from "./daily-run.ts";
5
5
 
6
6
  const EDGE = `nginx active
7
7
  wg-quick@wg0 active
@@ -167,6 +167,18 @@ describe("morning status lines", () => {
167
167
  expect(dnsStatus(all, { major: true, from: "15.6.2", to: "16.0.0" }).problem).toMatch(/^DNS: Technitium 16.0.0 is a major release \(running 15.6.2\)/);
168
168
  expect(inferenceStatus("embed \tstate = running \tpid = 80042 health=200\nrerank \tstate = running \tpid = 81670 health=200")).toEqual({ area: "Inference", line: "Nexus embed, rerank running and healthy" });
169
169
  expect(inferenceStatus("embed \tstate = running \tpid = 80042 health=503")).toMatchObject({ problem: "Inference: embed not healthy on Nexus" });
170
+ expect(homeStatus({ problems: [], unavailable: 3, version: "2026.11.1" })).toEqual({ area: "Home", line: "Home Assistant 2026.11.1, nothing to do, 3 entities unavailable" });
171
+ expect(homeStatus({ problems: ["1 update waits: Home Assistant Core 2026.11.1 → 2026.11.2", "the Nest integration (nest) did not load: setup_retry"], unavailable: 1, version: "2026.11.1" })).toEqual({
172
+ area: "Home",
173
+ line: "Home Assistant 2026.11.1, 2 items, 1 entity unavailable",
174
+ problem: "Home: 1 update waits: Home Assistant Core 2026.11.1 → 2026.11.2; the Nest integration (nest) did not load: setup_retry",
175
+ items: [
176
+ { owner: "Home", text: "1 update waits: Home Assistant Core 2026.11.1 → 2026.11.2" },
177
+ { owner: "Home", text: "the Nest integration (nest) did not load: setup_retry" },
178
+ ],
179
+ once: "home:1 update waits: Home Assistant Core 2026.11.1 → 2026.11.2|the Nest integration (nest) did not load: setup_retry",
180
+ });
181
+ expect(homeStatus(null)).toMatchObject({ area: "Home", problem: "Home: the status check failed" });
170
182
  const empty = { records: [], warnings: [] };
171
183
  expect(mediaStatus({ sabnzbd_paused: true, warnings: [] }, empty, NOW)).toEqual({ area: "Media", line: "downloads paused" });
172
184
  expect(mediaStatus({ sabnzbd_paused: false, warnings: [{ text: "login failed" }] }, empty, NOW)).toMatchObject({ line: "downloads running, 1 warning", problem: "Media: the downloader shows 1 warning", route: "media" });
@@ -317,6 +317,20 @@ export function inferenceStatus(status: string | null): AreaStatus {
317
317
  return { area: "Inference", line, ...(bad.length > 0 || services.length === 0 ? { problem: `Inference: ${bad.length > 0 ? `${bad.join(", ")} not healthy on Nexus` : "Nexus lists no service"}`, route: "admin" as const } : {}) };
318
318
  }
319
319
 
320
+ /**
321
+ * `home problems`: every line Home Assistant's specialist reports is an item. The tagged message posts once
322
+ * per set of problems, because most of them (a waiting update, a repair) only wait for the owners.
323
+ */
324
+ export function homeStatus(answer: unknown): AreaStatus {
325
+ const r = answer as { problems?: unknown; unavailable?: unknown; version?: unknown } | null;
326
+ if (!r || !Array.isArray(r.problems)) return failed("Home", "admin", "problems");
327
+ const problems = r.problems.filter((p): p is string => typeof p === "string");
328
+ const unavailable = typeof r.unavailable === "number" ? `, ${r.unavailable} ${r.unavailable === 1 ? "entity" : "entities"} unavailable` : "";
329
+ const line = `Home Assistant ${typeof r.version === "string" ? r.version : "?"}, ${problems.length === 0 ? "nothing to do" : `${problems.length} item${problems.length === 1 ? "" : "s"}`}${unavailable}`;
330
+ if (problems.length === 0) return { area: "Home", line };
331
+ return { area: "Home", line, problem: `Home: ${problems.join("; ")}`, items: problems.map((text) => ({ owner: "Home", text })), once: `home:${[...problems].sort().join("|").slice(0, 400)}` };
332
+ }
333
+
320
334
  /** One download that Radarr or Sonarr cannot import, from `media queue`. */
321
335
  export interface StuckImport {
322
336
  app: string;
@@ -524,7 +538,7 @@ function link(guildId: string, channelId: string, messageId: string): string {
524
538
  const AREA_OWNER: Readonly<Record<string, string>> = { "Security (weekly)": "Security", "Cortex tools": "Cortex", macOS: "Cortex", Updates: "Proxmox" };
525
539
 
526
540
  /** The summary lines in this order; any other owner follows them. */
527
- const OWNER_ORDER = ["Security", "Cortex", "Arcane", "Backup", "Edge", "Proxmox", "Network", "Identity", "DNS", "Inference", "Media"];
541
+ const OWNER_ORDER = ["Security", "Cortex", "Arcane", "Backup", "Edge", "Proxmox", "Network", "Identity", "DNS", "Inference", "Media", "Home"];
528
542
 
529
543
  const ALL_CLEAR = "All clear boss!";
530
544
 
@@ -79,7 +79,7 @@ import { ArcaneWatch } from "./arcane-watch-monitor.ts";
79
79
  import { parseSnapshot } from "./arcane-watch.ts";
80
80
  import { type Applied, autoFailureText, foremanTask, stackProblems, stackUpdateAnswer, SUPERVISE_DELAY_MS, SUPERVISE_LIMIT_MS } from "./supervise.ts";
81
81
  import { stackPlan, toolPlan } from "./update-policy.ts";
82
- import { type AreaStatus, arcaneSummary, backupStatus, type DnsUpgrade, dnsStatus, macosStatus, edgeStatus, identityStatus, inferenceStatus, mediaStatus, networkStatus, pendingPackageLines, problemSpecialist, problemsToPost, problemText, type ProxmoxHost, proxmoxStatus, type ReportLine, type Route, summaryText, technitiumPlan, toolsSummary, updatesStatus } from "./daily-run.ts";
82
+ import { type AreaStatus, arcaneSummary, backupStatus, type DnsUpgrade, dnsStatus, homeStatus, macosStatus, edgeStatus, identityStatus, inferenceStatus, mediaStatus, networkStatus, pendingPackageLines, problemSpecialist, problemsToPost, problemText, type ProxmoxHost, proxmoxStatus, type ReportLine, type Route, summaryText, technitiumPlan, toolsSummary, updatesStatus } from "./daily-run.ts";
83
83
  import { type InvestigationRequest, SecurityMonitor } from "./security-monitor.ts";
84
84
  import { nasOutage, readSecurityState } from "./security.ts";
85
85
 
@@ -732,6 +732,7 @@ class Bridge {
732
732
  }
733
733
  if (present.has("inference")) areas.push((async () => inferenceStatus(await text("inference", ["nexus-status"])))());
734
734
  if (present.has(MEDIA)) areas.push((async () => mediaStatus(await json(MEDIA, ["sabnzbd", "status"]), await json(MEDIA, ["queue"]), Date.now()))());
735
+ if (present.has("home")) areas.push((async () => homeStatus(await json("home", ["problems"])))());
735
736
  areas.push(
736
737
  (async () => {
737
738
  // Cortex is this host; Nexus answers through the inference specialist.
@@ -17,6 +17,10 @@ describe("approvals", () => {
17
17
  expect(isRisky("media", ["jellyfin", "date-repair"])).toBe(true);
18
18
  expect(isRisky("media", ["jellyfin", "date-check"])).toBe(false);
19
19
  expect(isRisky("media", ["bazarr", "status"])).toBe(false);
20
+ expect(isRisky("home", ["action", "light.turn_off", "{}"])).toBe(true);
21
+ expect(isRisky("home", ["restart"])).toBe(true);
22
+ expect(isRisky("home", ["problems"])).toBe(false);
23
+ expect(isRisky("home", ["logs", "core", "50"])).toBe(false);
20
24
  expect(isRisky("identity", ["zitadel", "DELETE", "/v2/users/1"])).toBe(true);
21
25
  expect(isRisky("identity", ["dmz", "deploy-config"])).toBe(true);
22
26
  expect(isRisky("identity", ["dmz", "pomerium-upgrade", "v0.33.6"])).toBe(true);
@@ -50,6 +50,8 @@ export const RISKY: Readonly<Record<string, readonly RegExp[]>> = {
50
50
  // Adds and queue pauses run on the caller's request; removing a queue record deletes its download,
51
51
  // and a date repair rewrites Jellyfin's "date added" on every item it finds late.
52
52
  media: [/^queue-remove\b/, /^jellyfin\s+date-repair\b/],
53
+ // Everything that changes Home Assistant: an update, a restart, and any action (lights, locks, scenes).
54
+ home: [/^(update|restart|action)\b/],
53
55
  };
54
56
 
55
57
  export function isRisky(service: string, args: readonly string[]): boolean {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.68",
3
+ "version": "0.40.70",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -0,0 +1,54 @@
1
+ ---
2
+ name: home
3
+ description: How the home specialist reads Home Assistant's health, finds what is wrong, reads logs, installs updates, restarts Core, and runs Home Assistant actions through the home tool.
4
+ ---
5
+
6
+ # Home specialist
7
+
8
+ Home Assistant OS runs as VM 112 `homeassistant` on SPACE-X at Mira, in the IoT network at `10.1.70.32` (web UI on port 8123). It moved there from a Raspberry Pi on 2026-11-12. No radio is attached: most devices come through two Hue bridges (the IKEA lights are paired to "Hue Bridge Down"), the rest through HomeKit bridges, Apple TV, the printer, and cloud integrations. Add-ons: Matter Server, File editor, Advanced SSH & Web Terminal, Tailscale. `["--help"]` lists the commands.
9
+
10
+ ## Commands
11
+
12
+ | Args | Effect |
13
+ |---|---|
14
+ | `["status"]` | versions, Supervisor health, integrations that did not load, repairs, waiting updates, backups, disk, add-ons, entity counts, and the problem list |
15
+ | `["problems"]` | only what needs a person, one line each, plus the number of unavailable entities |
16
+ | `["entities"]` | unavailable entities (50); `--state <state>`, `--domain light`, `--max 1..200` |
17
+ | `["logs", "core", "200"]` | the newest lines of Core's log; also `supervisor`, `host`; default 100, at most 400 |
18
+ | `["logs", "addon", "core_matter_server"]` | one add-on's log, by the slug from `status` |
19
+ | `["update", "update.home_assistant_core_update", "--confirm"]` | install one waiting update; asks an owner |
20
+ | `["restart", "--confirm"]` | restart Home Assistant Core; asks an owner |
21
+ | `["action", "light.turn_on", "{\"target\":{\"entity_id\":\"light.kitchen\"},\"data\":{\"brightness_pct\":40}}"]` | run any Home Assistant action; the JSON may hold `target` and `data`; asks an owner |
22
+
23
+ ## Output
24
+
25
+ - `status`: `{ "core": { "version", "state", "safe_mode", "recovery_mode", "version_latest", "update_available" }, "supervisor": { "version", "healthy", "supported", ... }, "os": { ... }, "disk": { "freeGb", "totalGb", "usedPercent" }, "integrations": { "total", "failed": [{ "domain", "title", "state", "reason" }] }, "repairs": [{ "domain", "issue", "severity", "fixable" }], "updates": [{ "entity", "title", "installed", "latest" }], "backups": { "count", "newest", "ageHours", "lastAutomatic", "failedAgents", "agentErrors" }, "addons": [{ "slug", "name", "state", "version", "version_latest", "update_available" }], "entities": { "total", "unavailable" }, "problems": [...], "unread": [...] }`.
26
+ - `unread` names the parts Home Assistant did not answer; each is also in `problems`. Never report such a part as fine.
27
+ - `problems`: `{ "problems": [...], "unavailable": n, "version": "..." }`. An empty list means nothing needs a person.
28
+ - `entities`: `{ "total": n, "entities": [{ "entity", "name", "state" }] }`.
29
+ - `logs`: `{ "lines": [...] }`, newest last.
30
+ - `update`: `{ "status": "update started", "entity" }`. The install runs in Home Assistant; read `status` again after a few minutes.
31
+ - `restart`: `{ "status": "restart requested" }`. The tool cannot reach Home Assistant while it restarts.
32
+ - `action`: `{ "status": "done", "action" }`.
33
+
34
+ ## Finding a cause
35
+
36
+ 1. `problems`. An integration with state `setup_retry` keeps trying (its device or cloud does not answer); `setup_error` and `migration_error` need a fix.
37
+ 2. `logs core 300` and look for the integration's name near the first error after the last start.
38
+ 3. For a Hue device: the bridge decides. An unavailable Hue light is usually switched off at the wall; many at once point at the bridge or the network path to it.
39
+ 4. For Matter or HomeKit devices that disappear together: discovery uses multicast. SPACE-X's bridge has multicast snooping on; say so and hand the check to `astro.proxmox`.
40
+ 5. `entities --domain <domain>` shows how wide a failure is.
41
+
42
+ ## Updates
43
+
44
+ `status` lists every waiting update with its entity id. Install one at a time with `update <entity> --confirm`, Core before add-ons, and read `status` afterwards. Home Assistant makes its own backup before an update when its backup setting says so; say when `backups.ageHours` is above 48 before you update. The operating system's update restarts the virtual machine.
45
+
46
+ ## Replies
47
+
48
+ Short and factual. Name devices and integrations by their Home Assistant names. One line per finding, most serious first. For an action: what changed, in one line.
49
+
50
+ ## When to stop and report
51
+
52
+ - The tool reports a missing secret or config field, or cannot reach Home Assistant at all: operator task; quote the error. Whether the VM runs is `astro.proxmox`'s question (`space-x`, VM 112).
53
+ - The task needs a file edit in Home Assistant's configuration, a new integration, a pairing, or a dashboard change: those need the web UI; say what to open.
54
+ - The task would restore a backup or reset Home Assistant: stop and ask the owner.
@@ -22,7 +22,7 @@ macOS cannot tell which agent made a call; the OS user protects the credential,
22
22
  extensions/specialist-gate/ index.ts (tool registration, tool_call blocks, /specialists), config.ts, types.ts, index.test.ts
23
23
  specialists/lib/ zitadel.ts, secrets.ts, config.ts, proc.ts, ssh.ts, tunnel.ts, repo.ts, pinned.ts, sanitize.ts, audit.ts, argv.ts, main.ts, output.ts, paths.ts, errors.ts, lock.ts,
24
24
  arcane-host.ts, arcane-manager.ts, change-origin.ts, container-watch.ts, deployment.ts, image-updates.ts, registry.ts, releases.ts, stack-update.ts
25
- specialists/<name>/run.ts one wrapper per specialist (arcane, identity, network, dns, edge, security, backup, proxmox, inference, media)
25
+ specialists/<name>/run.ts one wrapper per specialist (arcane, identity, network, dns, edge, security, backup, proxmox, inference, media, research, home)
26
26
  specialists/wrappers.test.ts validators, tables, help
27
27
  specialists/provision/ provision.sh (Vaultwarden to files)
28
28
  specialists/install/ install.sh (package to ~/.specialists/bin, arcane-cli download)
@@ -63,6 +63,7 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
63
63
  - `arcane manager-upgrade <version>` (`lib/arcane-manager.ts`) follows arcane/AGENTS.md "Manager upgrades": the official image's revision label must equal the release tag's commit (GitHub API), `manager-prepare` records `compose.before.yaml` and every container before the pin commit, the pin goes through the `arcane-gitops` checkout (`git` is exported from `lib/repo.ts` for this), the wait polls `gitops list` and the deployed Compose hash every 30 s for up to 30 minutes, then pull, cold backup, `up -d --no-deps --pull never`, and checks. Any failure before the restart reverts the pin (`stopped`); a failed check after it reverts the pin and runs `manager-rollback` (`rolled back`). The answer always exits 0 with `status`, so the bridge and the agent both see it.
64
64
  - `research` is a pure forced-command wrapper: every call is one JSON request on stdin to `request` on VM 110 (`10.1.100.10`, user `spc-research`, key `SSH_KEY_SANDBOX`), whose entry hands it to `spc-research-op` as `researcher` (tracked in the homelab repository's `06-space-x-proxmox/research/system/`). The op attaches one playwright-cli session per Discord thread (`t<id>`) to the shared Chrome over CDP on `127.0.0.1:9222` and opens its own tab; cookie, storage, `run-code`, and browser lifecycle commands are refused. `script` runs the agent's code in the thread folder as `researcher` (5 minutes), on a VM that reaches only the internet (Mira's Sandbox zone plus the VM's own nftables). Defaults stay on Cortex in `work/research/defaults.json`, out of the sandbox's reach. `captcha-help` is in `RISKY`, so its owner approval is the moment the owner solved the challenge in the live view (`research-browser.37pla.net`); the bridge renders that ticket with the channel's `liveView` link.
65
65
  - `media` runs trendarr unchanged: `trendarrCli` in `media.json` is its `dist/cli.js`, started with `process.execPath` because sudo's PATH has no node. Each call gets `HOME` set to a fresh `0700` directory under `~/.specialists/work/media/` that holds only `.trendarr/config.json` (`0600`, trendarr's own schema, built from the note fields and `media.json`) and is removed in `finally`; trendarr reads no environment variables and has no config flag, and Node's `os.homedir()` follows `$HOME` on POSIX. Every call passes `--json`; `init` is refused. An add prints trendarr's per-ID `results` and exits 0 even when trendarr exits 1 for a failed ID, because the gate shows only stderr on failure; other failures carry trendarr's stderr without its `warning:` lines, which go into the JSON as `warnings`. The bridge's slash commands and Add buttons call the same wrapper through the entry point (`extensions/astro-discord/media.ts`). `queue` and `queue-remove` (since 0.40.66) skip trendarr, which has no queue records: the wrapper calls `/api/v3/queue` of Radarr and Sonarr itself with the note's keys in the `X-Api-Key` header and prints only `stuckRecords` fields (no paths or download ids); `queue-remove` sends `DELETE /api/v3/queue/<id>?removeFromClient=true&blocklist=false`, needs `--confirm`, and is in `RISKY`. The `jellyfin` commands (since 0.40.68, pure parts in `lib/media-dates.ts`) exist because Jellyfin adds a renamed or moved file as a new item: the library rename of 2026-11-10 turned 873 of 875 episodes into "added today". `date-check` reads every movie, episode, season, and series from `/Items` (one request per type without a limit, because pages of an unsorted list can overlap), Radarr's and Sonarr's files, and each app's whole history from `/api/v3/history/since`; files match by their last path segments (`pathKey`: two for a movie, three for an episode), so the mount points may differ. `planDates` follows the arcane repository's `media/AGENTS.md`: a movie or episode gets its earliest successful import (`firstArrival`; without an import record the earliest of the file's own import date and its rename and deletion records, since a file a disk scan found has none), a season and a series their earliest episode, an empty season its series; only a date more than a day late changes, so a date only ever moves back, and an item Radarr or Sonarr has no file for is reported as unmatched and left alone. `date-repair --confirm` applies the plan through Jellyfin's own `POST /Items/<id>`, the call behind its metadata editor: the item as `GET /Items/<id>?userId=<an administrator>` returns it (without a user id an API key gets 400) with only `DateCreated` changed and `People` left out, because Jellyfin rewrites people only when the request carries them; a test on one episode showed only `DateCreated` and `Etag` differing afterwards. Jellyfin keeps running, and five failed updates stop the run. The API key travels as `Authorization: MediaBrowser Token="<key>"`, the scheme of the server's own `/api-docs/openapi.json` (12.4.0). `bazarr status` reads `/api/system/status` and `/api/system/health` with `X-API-KEY` and prints versions and issues only; the Sonarr and Radarr versions Bazarr reports show that it reaches them. Both read their own config shape (`jellyfinUrl`, `bazarrUrl`), so the trendarr commands run without those keys.
66
+ - `home` (since 0.40.70) reaches Home Assistant, VM 112 on SPACE-X at Mira (`homeAssistantUrl` in `home.json`, token `HOMEASSISTANT_TOKEN`), which replaced a Raspberry Pi with a failing SD card on 2026-11-12. `lib/home-assistant.ts` opens the WebSocket API (`/api/websocket`: `auth_required`, `auth` with the token, `auth_ok`), sends commands with ids, and closes; the wrapper runs on the installer's Node, which has a global `WebSocket`. The Supervisor's state (`/supervisor/info`, `/core/info`, `/os/info`, `/host/info`, `/resolution/info`, `/addons`) is reachable only through the `supervisor/api` command, because Core's REST proxy (`/api/hassio/...`) forwards logs and backups and nothing else (`PATHS_ADMIN` in Core's `hassio/http.py`, read at tag 2026.11.1); `logs` uses that proxy with `?lines=`. `status` prints named fields only (`pick`), so add-on options and addresses stay inside. `homeProblems` turns a snapshot into one line per finding: Core not running, safe or recovery mode, an unhealthy or unsupported Supervisor, its resolution issues, integrations that did not load (`setup_error`, `setup_retry`, ...), open repairs, waiting `update.*` entities, a newest backup older than 48 hours or failed for a location, a disk above 85 %; a part that could not be read is a line too (`unread`), never a pass. `update`, `restart`, and `action` (any Home Assistant action with `target` and `data`) change things and are in `RISKY`; the first two also need `--confirm`. Arguments are checked before config and secret are read. The agent has no `read` tool. The morning run reads `home problems` (`homeStatus` in `daily-run.ts`): each line is an item under Home, and the tagged message posts once per set of problems. Cortex reaches `10.1.70.32:8123` through the policies `Home Assistant - from Cortex` on both consoles.
66
67
  - `arcane release-notes <stack>[/<service>]` is `lib/releases.ts`: a single-image check and `resolveRef` give the running and latest versions, `HttpRegistry.labels` reads `org.opencontainers.image.source` from the latest image (index to linux/amd64 manifest to config blob), and the anonymous GitHub releases API (60 requests an hour, up to 3 pages of 100) gives the releases in between, oldest first. `condenseNotes` keeps each release under 12,000 characters by section priority; `capTotal` drops the oldest releases past 40,000 characters in total.
67
68
 
68
69
  ## Gate
@@ -85,4 +86,4 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
85
86
 
86
87
  ## Next
87
88
 
88
- All ten specialists exist; `media` (trendarr, slash commands and Add buttons in Discord) was added on 2026-10-19; `network` writes anything the UniFi Network API offers on the consoles of 37 and Mira (2026-10-28), `identity` deploys Pomerium routes, and Discord access is live. The Astrogate webhook route was built end to end through `identity`, `edge`, `network`, and `dns` on 2026-09-17. Open: Europa scheduled-task control for `inference` (needs Europa on to test Windows OpenSSH forced commands).
89
+ All twelve specialists exist (`home` since 2026-11-12); `media` (trendarr, slash commands and Add buttons in Discord) was added on 2026-10-19; `network` writes anything the UniFi Network API offers on the consoles of 37 and Mira (2026-10-28), `identity` deploys Pomerium routes, and Discord access is live. The Astrogate webhook route was built end to end through `identity`, `edge`, `network`, and `dns` on 2026-09-17. Open: Europa scheduled-task control for `inference` (needs Europa on to test Windows OpenSSH forced commands).
@@ -15,6 +15,7 @@ A specialist is a Pi subagent that is the only way to operate one area of the ho
15
15
  | `astro.inference` | MLX embedding and reranking servers on Nexus, Europa health | `nexus-status|start|stop|restart|log|disk`, `macos-updates`; `europa-health` |
16
16
  | `astro.media` | trendarr over TMDB, OMDb, and the `media` project on VM 100 (Radarr, Sonarr, SABnzbd, Jellyfin, Bazarr) | `trending`, `search`, `recommend`, `add-movies`, `add-series` (at most 20 IMDb IDs), `sabnzbd status|pause|resume`, `queue`, `queue-remove <radarr|sonarr> <id> --confirm`, `jellyfin status|date-check`, `jellyfin date-repair --confirm`, `bazarr status`; trendarr's JSON plus its warnings, the queue, Jellyfin, and Bazarr commands straight from those apps |
17
17
  | `astro.research` | the research sandbox, VM 110 at Mira (Chrome on a virtual screen, scripts, thread folders), through the forced-command key of user `spc-research`; defaults in `~/.specialists/work/research/defaults.json` | `browser <session> <playwright-cli args>`, `captcha`, `captcha-help` (owner approval: solved in the live view), `script`, `read`, `files`, `toolbox`, `defaults list|set|unset`; the sandbox's JSON |
18
+ | `astro.home` | Home Assistant at Mira (VM 112 on SPACE-X, `10.1.70.32:8123`), through its WebSocket API and log routes with a long-lived access token | `status`, `problems`, `entities`, `logs <core\|supervisor\|host\|addon <slug>>`, `update <update.entity> --confirm`, `restart --confirm`, `action <domain.action> [json]`; named fields only |
18
19
 
19
20
  Call one with `/run astro.<name> -- <task>` or through the `subagent` tool (both from the bundled `astro-subagents` extension). `/run` saves the specialist's session under `~/.pi/agent/subagent-sessions/<agent>/`; `/run astro.<name> --continue -- <task>` resumes the last one started from the same directory, so the specialist keeps what it saw. Sessions older than 7 days are deleted. Specialists may call each other once (`maxSubagentDepth: 1`). They run on `openai-codex/gpt-6-astra` with `xhigh` thinking, set by `model` and `thinking` in each `agents/<name>.md`; an agent without these fields inherits the caller's model and thinking. Each tool takes `args`, an array of strings; `["--help"]` lists the subcommands.
20
21
 
@@ -44,6 +45,7 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
44
45
  - `proxmox`: `PVE_TOKEN_ID` (plain, `spc-proxmox@pve!cortex`), `PVE_TOKEN_SECRET`, `PVE_SPACEX_TOKEN_ID` and `PVE_SPACEX_TOKEN_SECRET` (the same user on SPACE-X), `SSH_KEY_PULSAR_B64` (trusted by Pulsar and SPACE-X). `proxmox.json` also needs `spacexApiUrl`, `spacexCertSha256`, `spacexNode`, `spacexHost`, `spacexUser`, and `known_hosts` the SPACE-X host key.
45
46
  - `inference`: `SSH_KEY_NEXUS_B64`.
46
47
  - `media`: `TMDB_ACCESS_TOKEN` (TMDB API Read Access Token), `OMDB_API_KEY`, `RADARR_API_KEY`, `SONARR_API_KEY` (Settings, General, Security; each app has one), `SABNZBD_API_KEY` (the API key, not the NZB key, which can only add NZBs and cannot read or pause the queue), `JELLYFIN_API_KEY` (Jellyfin's Dashboard, API Keys, New API Key; only the `jellyfin` commands read it), `BAZARR_API_KEY` (Bazarr's Settings, General, Security, API Key; only `bazarr status` reads it).
48
+ - `home`: `HOMEASSISTANT_TOKEN` (a long-lived access token of an administrator: Home Assistant, User profile, Security, Long-lived access tokens).
47
49
  2. **Identities.** Zitadel (`https://auth.37pla.net/ui/console`): service user `spc-arcane` with Access Token Type JWT and a JSON key; service user `spc-identity` with a Personal Access Token and the Instance Owner role. Technitium (cluster primary): user `spc-dns` in the Administrators group with an API token; the cluster syncs the user to every node. Cloudflare: an account-owned API token with `Zone:Read` and `DNS:Edit` on both zones. GCP project `frontdoor-1337`: service account `spc-edge` with `roles/iap.tunnelResourceAccessor` and `roles/compute.viewer`, JSON key. Proxmox (`ssh pulsar`): user `spc-proxmox@pve`, role `SpecialistGuest` = `VM.Audit VM.PowerMgmt VM.Snapshot VM.Snapshot.Rollback VM.Config.CPU VM.Config.Memory VM.Config.Options VM.Config.Network VM.Config.CDROM VM.GuestAgent.Audit`, ACLs `PVEAuditor` on `/` and `SpecialistGuest` on `/vms` for both the user and the token `spc-proxmox@pve!cortex` (`-privsep 1`).
48
50
  3. **Services.** Arcane (Settings, Authentication, Federated Credentials): Issuer `https://auth.37pla.net`, Audience `387825541182390275`, Subject exact = `spc-arcane` user ID, Role Admin, Global, lifetime 300. UniFi: the account key and a local key per console (fields above) and policies on 37 allowing Cortex `10.0.40.37` to TCP 22 on `10.0.20.10`, `10.0.10.37`, `10.0.90.10`, TCP 5380 on `10.0.40.53`, TCP 8006 on `10.0.10.37`, TCP 8081 on `10.0.60.5`, TCP 443 on the Mira console `10.1.60.1`, and TCP 22 and 8006 on SPACE-X `10.1.10.37` (that one also on Mira); the homelab `03-cortex-macmini/README.md` lists them with their ids. GitHub: `spc-arcane-gitops` as a write deploy key on `astronaute77/arcane`, `spc-edge-homelab` and `spc-identity-homelab` as write deploy keys on `astronaute77/homelab`.
49
51
  4. **Sudo and user**, as an administrator:
@@ -89,6 +91,7 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
89
91
  "sonarrUrl": "http://10.0.40.30:8989", "sonarrQualityProfileId": 7, "sonarrRootFolderPath": "/media/tv", "sonarrMonitor": "all",
90
92
  "sabnzbdUrl": "http://10.0.40.30:8084", "maxEntries": 10,
91
93
  "jellyfinUrl": "http://10.0.40.30:8096", "bazarrUrl": "http://10.0.40.30:6767" }
94
+ { "homeAssistantUrl": "http://10.1.70.32:8123" }
92
95
  ```
93
96
  The `media` wrapper writes trendarr's `~/.trendarr/config.json` for each call into a private temporary HOME under `~/.specialists/work/media/` and removes it afterwards, so trendarr itself is never configured with `trendarr init`. Cortex reaches the ports on `10.0.40.30` within its own VLAN. `jellyfinUrl` is read only by the `jellyfin` commands and `bazarrUrl` only by `bazarr status`, so the other commands work without them.
94
97
  `sudo /usr/local/sbin/specialist-install trendarr <version>` installs trendarr behind the link `~/.specialists/bin/trendarr`, so that path stays valid across updates. Then `sudo -n -u specialist -H /usr/local/bin/specialist-cli provision`; it lists every note and field.
@@ -138,7 +141,8 @@ Host: Cortex (macOS on Apple silicon; Homebrew git; the specialists' Node, trend
138
141
  { "agent": "astro.proxmox", "tool": "proxmox", "service": "proxmox", "timeoutMs": 1320000 },
139
142
  { "agent": "astro.inference", "tool": "inference", "service": "inference", "timeoutMs": 1260000 },
140
143
  { "agent": "astro.media", "tool": "media", "service": "media", "timeoutMs": 660000 },
141
- { "agent": "astro.research", "tool": "research", "service": "research", "timeoutMs": 420000 } ] }
144
+ { "agent": "astro.research", "tool": "research", "service": "research", "timeoutMs": 420000 },
145
+ { "agent": "astro.home", "tool": "home", "service": "home", "timeoutMs": 180000 } ] }
142
146
  ```
143
147
 
144
148
  Check: `sudo -n -u specialist -H /usr/local/bin/specialist-cli arcane --caller test -- projects list` prints JSON; the same for `identity -- dmz status`, `network -- unifi 37 sites`, `dns -- technitium primary zones`, `edge -- vps status`, `security -- attention`, `backup -- vzdump-tasks`, `proxmox -- guests`, `inference -- nexus-status`, `media -- sabnzbd status`; `/run astro.arcane -- list projects` works in Pi; `bash` with `arcane-cli --help` is blocked in a normal session.
@@ -159,4 +163,4 @@ The `astro-discord` extension gives Discord users access to the specialists from
159
163
 
160
164
  Rotation steps for every field live in the homelab repository, `03-cortex-macmini/ROTATION.md`. After any change in Vaultwarden run `specialist-cli provision`. Host state and the sudo rules are documented in `03-cortex-macmini/README.md`; the forced-command scripts are tracked under `02-pulsar-proxmox/dmz/system/`, `02-pulsar-proxmox/pulsar/system/`, `06-space-x-proxmox/system/`, `01-synapse-dns/system/`, `02-pulsar-proxmox/observability/system/`, `host/` of the `astronaute77/arcane` repository, `04-nexus-macstudio/system/`, and `00-frontdoor-vps/system/`.
161
165
 
162
- All ten specialists exist. See `AGENTS.md` for how to add one.
166
+ All twelve specialists exist. See `AGENTS.md` for how to add one.
@@ -6,7 +6,7 @@ set -euo pipefail
6
6
 
7
7
  service="${1:-}"; [[ -n "$service" ]] && shift
8
8
  case "$service" in
9
- arcane|identity|network|dns|edge|security|backup|proxmox|inference|media|research) ;;
9
+ arcane|identity|network|dns|edge|security|backup|proxmox|inference|media|research|home) ;;
10
10
  provision) exec /bin/sh "$HOME/.specialists/bin/provision.sh" ;;
11
11
  *) print -u2 "usage: specialist-cli <service> [--caller <agent>] [--] <args...>"; exit 2 ;;
12
12
  esac
@@ -28,7 +28,7 @@ JQ_BASE=/usr/local/libexec/specialist-jq
28
28
  # gsutil, and the empty macOS bundled-python component are left out).
29
29
  GCLOUD_COMPONENTS="core core-nix gcloud-deps gcloud-deps-darwin-arm gcloud-crc32c-darwin-arm"
30
30
  # Same list as the allowlist in specialist-cli; a new specialist needs both reinstalled.
31
- SERVICES="arcane identity network dns edge security backup proxmox inference media research"
31
+ SERVICES="arcane identity network dns edge security backup proxmox inference media research home"
32
32
 
33
33
  usage() {
34
34
  echo "usage: specialist-install node|wrappers|arcane-cli|trendarr|gcloud|bw|jq <version> | python <x.y.z+YYYYMMDD> | rollback node|wrappers|arcane-cli|trendarr|python|gcloud|bw|jq | status" >&2
@@ -0,0 +1,248 @@
1
+ import { readConfig } from "../lib/config.ts";
2
+ import { ServiceError, UsageError } from "../lib/errors.ts";
3
+ import { backupSummary, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, openRepairs, pendingUpdates, tailLines } from "../lib/home-assistant.ts";
4
+ import type { HaCall, HomeSnapshot } from "../lib/home-assistant.ts";
5
+ import { main } from "../lib/main.ts";
6
+ import { printJson, printRaw } from "../lib/output.ts";
7
+ import { readSecret } from "../lib/secrets.ts";
8
+
9
+ const SERVICE = "home";
10
+
11
+ interface HomeConfig extends Record<string, string> {
12
+ /** Base URL of Home Assistant, e.g. `http://10.1.70.32:8123`. */
13
+ homeAssistantUrl: string;
14
+ }
15
+
16
+ const SHAPE = { homeAssistantUrl: "string" } as const;
17
+
18
+ const MAX_ENTITIES = 200;
19
+ const MAX_LOG_LINES = 400;
20
+ const ENTITY_ID = /^[a-z0-9_]+\.[a-z0-9_]+$/;
21
+ const ACTION = /^[a-z0-9_]+\.[a-z0-9_]+$/;
22
+ const ADDON_SLUG = /^[a-z0-9_]+$/;
23
+ const LOG_SOURCES = ["core", "supervisor", "host"];
24
+
25
+ const HELP = `home specialist (Home Assistant at Mira, through its WebSocket API and log routes)
26
+
27
+ status versions, Supervisor health, integrations that did not load, repairs, updates,
28
+ backups, disk, add-ons, and the number of unavailable entities
29
+ problems what needs a person, one line each; a part that cannot be read is a problem too
30
+ entities [--state <state>] [--domain <domain>] [--max N]
31
+ entity ids, names, and states (default: state unavailable, 50 of them)
32
+ logs <core|supervisor|host> [lines]
33
+ logs addon <slug> [lines] the newest log lines (default 100, at most ${MAX_LOG_LINES})
34
+ update <update.entity_id> --confirm
35
+ install the update of one update entity
36
+ restart --confirm restart Home Assistant Core
37
+ action <domain.action> [json]
38
+ run any Home Assistant action with {"target": {...}, "data": {...}}; in chat it asks an owner
39
+
40
+ status, problems, and entities change nothing.`;
41
+
42
+ /** The Supervisor's answer to a GET, through Core's `supervisor/api` command. */
43
+ function supervisorGet(call: HaCall, endpoint: string): Promise<unknown> {
44
+ return call("supervisor/api", { endpoint, method: "get" });
45
+ }
46
+
47
+ async function snapshot(call: HaCall): Promise<HomeSnapshot> {
48
+ const unread: string[] = [];
49
+ const read = async (part: string, request: Promise<unknown>): Promise<unknown> => {
50
+ try {
51
+ return await request;
52
+ } catch {
53
+ unread.push(part);
54
+ return null;
55
+ }
56
+ };
57
+ const [config, states, entries, repairs, backups, supervisor, core, os, host, resolution, addons] = await Promise.all([
58
+ read("Core state", call("get_config")),
59
+ read("entity states", call("get_states")),
60
+ read("integration list", call("config_entries/get")),
61
+ read("repair list", call("repairs/list_issues")),
62
+ read("backup list", call("backup/info")),
63
+ read("Supervisor state", supervisorGet(call, "/supervisor/info")),
64
+ read("Core version", supervisorGet(call, "/core/info")),
65
+ read("operating system state", supervisorGet(call, "/os/info")),
66
+ read("host state", supervisorGet(call, "/host/info")),
67
+ read("Supervisor checks", supervisorGet(call, "/resolution/info")),
68
+ read("add-on list", supervisorGet(call, "/addons")),
69
+ ]);
70
+ return { config, states, entries, repairs, backups, supervisor, core, os, host, resolution, addons, unread };
71
+ }
72
+
73
+ function pick(value: unknown, keys: readonly string[]): Record<string, unknown> | null {
74
+ if (typeof value !== "object" || value === null) return null;
75
+ const record = value as Record<string, unknown>;
76
+ return Object.fromEntries(keys.map((key) => [key, record[key] ?? null]));
77
+ }
78
+
79
+ function addonRows(addons: unknown): Record<string, unknown>[] {
80
+ const list = (addons as { addons?: unknown } | null)?.addons;
81
+ if (!Array.isArray(list)) return [];
82
+ return (list as unknown[]).flatMap((addon): Record<string, unknown>[] => {
83
+ const row = pick(addon, ["slug", "name", "state", "version", "version_latest", "update_available"]);
84
+ return row ? [row] : [];
85
+ });
86
+ }
87
+
88
+ /** The snapshot as an answer: named fields only, so no token, address list, or add-on option leaves the wrapper. */
89
+ function statusAnswer(s: HomeSnapshot, now: number): Record<string, unknown> {
90
+ const unavailable = entitiesIn(s.states);
91
+ return {
92
+ core: { ...pick(s.config, ["version", "state", "safe_mode", "recovery_mode"]), ...pick(s.core, ["version_latest", "update_available"]) },
93
+ supervisor: pick(s.supervisor, ["version", "version_latest", "update_available", "healthy", "supported", "channel"]),
94
+ os: pick(s.os, ["version", "version_latest", "update_available", "board"]),
95
+ disk: diskUse(s.host),
96
+ integrations: { total: Array.isArray(s.entries) ? s.entries.length : null, failed: failedIntegrations(s.entries) },
97
+ repairs: openRepairs(s.repairs),
98
+ updates: pendingUpdates(s.states),
99
+ backups: s.backups === null ? null : backupSummary(s.backups, now),
100
+ addons: addonRows(s.addons),
101
+ entities: { total: Array.isArray(s.states) ? s.states.length : null, unavailable: unavailable.length },
102
+ problems: homeProblems(s, now),
103
+ unread: s.unread,
104
+ };
105
+ }
106
+
107
+ function parseCount(value: string | undefined, name: string, max: number, fallback: number): number {
108
+ if (value === undefined) return fallback;
109
+ const n = Number(value);
110
+ if (!Number.isInteger(n) || n < 1 || n > max) throw new UsageError(`${name} must be an integer from 1 to ${max}`);
111
+ return n;
112
+ }
113
+
114
+ export interface EntityQuery {
115
+ state: string;
116
+ domain?: string;
117
+ max: number;
118
+ }
119
+
120
+ /** `entities [--state <state>] [--domain <domain>] [--max N]`. */
121
+ export function parseEntityQuery(args: string[]): EntityQuery {
122
+ const query: EntityQuery = { state: "unavailable", max: 50 };
123
+ for (let i = 0; i < args.length; i += 2) {
124
+ const value = args[i + 1];
125
+ if (value === undefined || value.startsWith("--")) throw new UsageError(`${args[i]} needs a value`);
126
+ if (args[i] === "--state" && /^[\w .-]{1,40}$/.test(value)) query.state = value;
127
+ else if (args[i] === "--domain" && /^[a-z0-9_]{1,40}$/.test(value)) query.domain = value;
128
+ else if (args[i] === "--max") query.max = parseCount(value, "--max", MAX_ENTITIES, 50);
129
+ else throw new UsageError("entities [--state <state>] [--domain <domain>] [--max N]");
130
+ }
131
+ return query;
132
+ }
133
+
134
+ /** The log route behind Core's proxy, and how many lines to keep. */
135
+ export function parseLogs(args: string[]): { path: string; lines: number } {
136
+ const usage = "logs <core|supervisor|host> [lines] | logs addon <slug> [lines]";
137
+ const [source, ...rest] = args;
138
+ if (source === "addon") {
139
+ const [slug, lines, ...extra] = rest;
140
+ if (slug === undefined || !ADDON_SLUG.test(slug) || extra.length > 0) throw new UsageError(usage);
141
+ return { path: `addons/${slug}/logs`, lines: parseCount(lines, "lines", MAX_LOG_LINES, 100) };
142
+ }
143
+ if (source === undefined || !LOG_SOURCES.includes(source) || rest.length > 1) throw new UsageError(usage);
144
+ return { path: `${source}/logs`, lines: parseCount(rest[0], "lines", MAX_LOG_LINES, 100) };
145
+ }
146
+
147
+ export interface ActionCall {
148
+ domain: string;
149
+ service: string;
150
+ target?: Record<string, unknown>;
151
+ data?: Record<string, unknown>;
152
+ }
153
+
154
+ function record(value: unknown, name: string): Record<string, unknown> | undefined {
155
+ if (value === undefined) return undefined;
156
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new UsageError(`${name} must be a JSON object`);
157
+ return value as Record<string, unknown>;
158
+ }
159
+
160
+ /** `action <domain.action> [json]`: the JSON may carry `target` and `data`, nothing else. */
161
+ export function parseAction(args: string[]): ActionCall {
162
+ const usage = 'action <domain.action> [{"target": {...}, "data": {...}}]';
163
+ const [name, json, ...extra] = args;
164
+ if (name === undefined || !ACTION.test(name) || extra.length > 0) throw new UsageError(usage);
165
+ let body: Record<string, unknown> = {};
166
+ if (json !== undefined) {
167
+ try {
168
+ body = record(JSON.parse(json) as unknown, "the body") ?? {};
169
+ } catch (err) {
170
+ throw err instanceof UsageError ? err : new UsageError("the body must be JSON");
171
+ }
172
+ }
173
+ if (Object.keys(body).some((key) => key !== "target" && key !== "data")) throw new UsageError(usage);
174
+ const [domain, service] = name.split(".");
175
+ const target = record(body.target, "target");
176
+ const data = record(body.data, "data");
177
+ return { domain, service, ...(target ? { target } : {}), ...(data ? { data } : {}) };
178
+ }
179
+
180
+ function callAction(call: HaCall, action: ActionCall): Promise<unknown> {
181
+ return call("call_service", { domain: action.domain, service: action.service, ...(action.target ? { target: action.target } : {}), ...(action.data ? { service_data: action.data } : {}) });
182
+ }
183
+
184
+ /** `--confirm` must be present; the rest of the arguments come back without it. */
185
+ function confirmed(args: string[], usage: string): string[] {
186
+ if (!args.includes("--confirm")) throw new UsageError(`${usage}: it changes Home Assistant, so it needs --confirm`);
187
+ return args.filter((a) => a !== "--confirm");
188
+ }
189
+
190
+ async function logs(config: HomeConfig, token: string, path: string, lines: number): Promise<string[]> {
191
+ const url = new URL(`/api/hassio/${path}?lines=${lines}`, config.homeAssistantUrl);
192
+ let res: Response;
193
+ try {
194
+ res = await fetch(url, { headers: { authorization: `Bearer ${token}`, accept: "text/plain" }, signal: AbortSignal.timeout(60_000) });
195
+ } catch (err) {
196
+ throw new ServiceError(`home assistant gave no answer to GET ${url.pathname}: ${err instanceof Error ? err.message.slice(0, 200) : String(err)}`);
197
+ }
198
+ if (!res.ok) throw new ServiceError(`home assistant answered ${res.status} to GET ${url.pathname}`);
199
+ return tailLines(await res.text(), lines);
200
+ }
201
+
202
+ export async function command(args: string[]): Promise<number> {
203
+ const [name, ...rest] = args;
204
+ if (name === undefined || name === "--help" || name === "help") {
205
+ printRaw(HELP);
206
+ return 0;
207
+ }
208
+ // Arguments are checked before any config or secret is read, so a wrong call never opens a session.
209
+ const entityQuery = name === "entities" ? parseEntityQuery(rest) : null;
210
+ const logQuery = name === "logs" ? parseLogs(rest) : null;
211
+ const action = name === "action" ? parseAction(rest) : null;
212
+ const updateTarget = name === "update" ? confirmed(rest, "update <update.entity_id> --confirm") : null;
213
+ if (updateTarget !== null && (updateTarget.length !== 1 || !ENTITY_ID.test(updateTarget[0]) || !updateTarget[0].startsWith("update."))) throw new UsageError("update <update.entity_id> --confirm");
214
+ if (name === "restart" && confirmed(rest, "restart --confirm").length > 0) throw new UsageError("restart --confirm");
215
+ if ((name === "status" || name === "problems") && rest.length > 0) throw new UsageError(`${name} takes no arguments`);
216
+ if (!["status", "problems", "entities", "logs", "update", "restart", "action"].includes(name)) throw new UsageError(`unknown command: ${name}`);
217
+
218
+ const config = readConfig<HomeConfig>(SERVICE, SHAPE);
219
+ const token = readSecret(SERVICE, "HOMEASSISTANT_TOKEN");
220
+ if (logQuery !== null) {
221
+ printJson({ lines: await logs(config, token, logQuery.path, logQuery.lines) });
222
+ return 0;
223
+ }
224
+ await haSession(config.homeAssistantUrl, token, async (call) => {
225
+ if (name === "status") printJson(statusAnswer(await snapshot(call), Date.now()));
226
+ else if (name === "problems") {
227
+ const s = await snapshot(call);
228
+ printJson({ problems: homeProblems(s, Date.now()), unavailable: entitiesIn(s.states).length, version: (s.config as { version?: unknown } | null)?.version ?? null });
229
+ } else if (entityQuery !== null) {
230
+ const found = entitiesIn(await call("get_states"), entityQuery.state, entityQuery.domain);
231
+ printJson({ total: found.length, entities: found.slice(0, entityQuery.max) });
232
+ } else if (updateTarget !== null) {
233
+ await callAction(call, { domain: "update", service: "install", target: { entity_id: updateTarget[0] } });
234
+ printJson({ status: "update started", entity: updateTarget[0] });
235
+ } else if (name === "restart") {
236
+ await callAction(call, { domain: "homeassistant", service: "restart" });
237
+ printJson({ status: "restart requested" });
238
+ } else if (action !== null) {
239
+ await callAction(call, action);
240
+ printJson({ status: "done", action: `${action.domain}.${action.service}` });
241
+ }
242
+ });
243
+ return 0;
244
+ }
245
+
246
+ if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
247
+ await main(SERVICE, command);
248
+ }
@@ -11,9 +11,9 @@ bin="$root/bin"
11
11
 
12
12
  [ -d "$src/specialists/lib" ] || { echo "not a pi-astro package: $src" >&2; exit 2; }
13
13
  mkdir -p "$bin" "$root/config" "$root/secrets" "$root/work"
14
- rm -rf "$bin/lib" "$bin/arcane" "$bin/identity" "$bin/network" "$bin/dns" "$bin/edge" "$bin/security" "$bin/backup" "$bin/proxmox" "$bin/inference" "$bin/media" "$bin/research"
14
+ rm -rf "$bin/lib" "$bin/arcane" "$bin/identity" "$bin/network" "$bin/dns" "$bin/edge" "$bin/security" "$bin/backup" "$bin/proxmox" "$bin/inference" "$bin/media" "$bin/research" "$bin/home"
15
15
  cp -R "$src/specialists/lib" "$bin/lib"
16
- for s in arcane identity network dns edge security backup proxmox inference media research; do
16
+ for s in arcane identity network dns edge security backup proxmox inference media research home; do
17
17
  mkdir -p "$bin/$s"
18
18
  cp "$src/specialists/$s/run.ts" "$bin/$s/run.ts"
19
19
  done
@@ -0,0 +1,175 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { backupSummary, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, openRepairs, pendingUpdates, tailLines } from "./home-assistant.ts";
3
+ import type { HomeSnapshot } from "./home-assistant.ts";
4
+
5
+ type Listener = (event: { data?: string }) => void;
6
+
7
+ /** A stand-in for Home Assistant's WebSocket: it asks for the token, then answers each command from `answers`. */
8
+ class FakeSocket {
9
+ sent: Record<string, unknown>[] = [];
10
+ closed = false;
11
+ private listeners: Record<string, Listener[]> = {};
12
+ private readonly token: string;
13
+ private readonly answers: Record<string, unknown>;
14
+
15
+ constructor(token: string, answers: Record<string, unknown>) {
16
+ this.token = token;
17
+ this.answers = answers;
18
+ queueMicrotask(() => this.emit("message", { type: "auth_required" }));
19
+ }
20
+
21
+ addEventListener(name: string, listener: Listener): void {
22
+ (this.listeners[name] ??= []).push(listener);
23
+ }
24
+
25
+ send(raw: string): void {
26
+ const msg = JSON.parse(raw) as Record<string, unknown>;
27
+ this.sent.push(msg);
28
+ if (msg.type === "auth") {
29
+ this.emit("message", msg.access_token === this.token ? { type: "auth_ok" } : { type: "auth_invalid", message: "Invalid access token" });
30
+ return;
31
+ }
32
+ const key = msg.type === "supervisor/api" ? `supervisor/api ${String(msg.endpoint)}` : String(msg.type);
33
+ if (!(key in this.answers)) this.emit("message", { id: msg.id, type: "result", success: false, error: { code: "unknown_command", message: "Unknown command." } });
34
+ else this.emit("message", { id: msg.id, type: "result", success: true, result: this.answers[key] });
35
+ }
36
+
37
+ close(): void {
38
+ this.closed = true;
39
+ for (const l of this.listeners.close ?? []) l({});
40
+ }
41
+
42
+ private emit(name: string, payload: Record<string, unknown>): void {
43
+ queueMicrotask(() => {
44
+ for (const l of this.listeners[name] ?? []) l({ data: JSON.stringify(payload) });
45
+ });
46
+ }
47
+ }
48
+
49
+ function factory(socket: FakeSocket): (url: string) => WebSocket {
50
+ return () => socket as unknown as WebSocket;
51
+ }
52
+
53
+ const NOW = Date.parse("2026-11-12T12:00:00Z");
54
+
55
+ function snapshot(partial: Partial<HomeSnapshot>): HomeSnapshot {
56
+ return {
57
+ config: { version: "2026.11.1", state: "RUNNING", safe_mode: false, recovery_mode: false },
58
+ states: [],
59
+ entries: [],
60
+ repairs: { issues: [] },
61
+ backups: { backups: [{ date: "2026-11-12T04:00:00Z", failed_agent_ids: [] }], agent_errors: {} },
62
+ supervisor: { healthy: true, supported: true },
63
+ core: {},
64
+ os: {},
65
+ host: { disk_free: 20, disk_total: 30 },
66
+ resolution: { issues: [], unhealthy: [], unsupported: [] },
67
+ addons: { addons: [] },
68
+ unread: [],
69
+ ...partial,
70
+ };
71
+ }
72
+
73
+ describe("home assistant session", () => {
74
+ it("signs in, sends commands with ids, and closes the socket", async () => {
75
+ const socket = new FakeSocket("tok", { get_config: { version: "2026.11.1" }, "supervisor/api /host/info": { disk_free: 1 } });
76
+ const result = await haSession(
77
+ "http://10.1.70.32:8123",
78
+ "tok",
79
+ async (call) => [await call("get_config"), await call("supervisor/api", { endpoint: "/host/info", method: "get" })],
80
+ factory(socket),
81
+ );
82
+ expect(result).toEqual([{ version: "2026.11.1" }, { disk_free: 1 }]);
83
+ expect(socket.sent).toEqual([
84
+ { type: "auth", access_token: "tok" },
85
+ { id: 1, type: "get_config" },
86
+ { id: 2, type: "supervisor/api", endpoint: "/host/info", method: "get" },
87
+ ]);
88
+ expect(socket.closed).toBe(true);
89
+ });
90
+
91
+ it("names a refused token and a refused command", async () => {
92
+ await expect(haSession("http://ha:8123", "wrong", async (call) => call("get_config"), factory(new FakeSocket("tok", {})))).rejects.toThrow(/refused the access token/);
93
+ const socket = new FakeSocket("tok", {});
94
+ await expect(haSession("http://ha:8123", "tok", async (call) => call("backup/info"), factory(socket))).rejects.toThrow(/refused backup\/info: Unknown command\./);
95
+ expect(socket.closed).toBe(true);
96
+ });
97
+ });
98
+
99
+ describe("home assistant findings", () => {
100
+ it("keeps integrations that did not load, without disabled ones", () => {
101
+ expect(
102
+ failedIntegrations([
103
+ { domain: "hue", title: "Hue Bridge Down", state: "loaded" },
104
+ { domain: "nest", title: "Nest", state: "setup_retry", reason: "Timeout" },
105
+ { domain: "ipp", title: "Printer", state: "setup_error", disabled_by: "user" },
106
+ { domain: "apple_tv", title: "TV", state: "not_loaded" },
107
+ ]),
108
+ ).toEqual([{ domain: "nest", title: "Nest", state: "setup_retry", reason: "Timeout" }]);
109
+ });
110
+
111
+ it("reads repairs, updates, and unavailable entities", () => {
112
+ expect(openRepairs({ issues: [{ domain: "homeassistant", issue_id: "x", translation_key: "deprecated_yaml", severity: "warning", is_fixable: false }, { domain: "hue", issue_id: "y", ignored: true }] })).toEqual([{ domain: "homeassistant", issue: "deprecated_yaml", severity: "warning", fixable: false }]);
113
+ const states = [
114
+ { entity_id: "update.home_assistant_core_update", state: "on", attributes: { title: "Home Assistant Core", installed_version: "2026.11.1", latest_version: "2026.11.2" } },
115
+ { entity_id: "update.matter_server_update", state: "off", attributes: {} },
116
+ { entity_id: "light.kitchen_backsplash_1", state: "unavailable", attributes: { friendly_name: "Kitchen backsplash 1" } },
117
+ { entity_id: "sensor.printer", state: "unavailable", attributes: {} },
118
+ ];
119
+ expect(pendingUpdates(states)).toEqual([{ entity: "update.home_assistant_core_update", title: "Home Assistant Core", installed: "2026.11.1", latest: "2026.11.2" }]);
120
+ expect(entitiesIn(states).map((e) => e.entity)).toEqual(["light.kitchen_backsplash_1", "sensor.printer"]);
121
+ expect(entitiesIn(states, "unavailable", "light")).toEqual([{ entity: "light.kitchen_backsplash_1", name: "Kitchen backsplash 1", state: "unavailable" }]);
122
+ });
123
+
124
+ it("summarises backups and the disk", () => {
125
+ expect(backupSummary({ backups: [{ date: "2026-11-09T04:00:00Z", failed_agent_ids: [] }, { date: "2026-11-10T04:00:00Z", failed_agent_ids: ["cloud.cloud"] }], agent_errors: { "hassio.share": "offline" }, last_completed_automatic_backup: "2026-11-10T04:00:00Z" }, NOW)).toEqual({
126
+ count: 2,
127
+ newest: "2026-11-10T04:00:00Z",
128
+ ageHours: 56,
129
+ lastAutomatic: "2026-11-10T04:00:00Z",
130
+ failedAgents: ["cloud.cloud"],
131
+ agentErrors: ["hassio.share"],
132
+ });
133
+ expect(backupSummary({ backups: [] }, NOW)).toMatchObject({ count: 0, newest: null, ageHours: null });
134
+ expect(diskUse({ disk_free: 3, disk_total: 30 })).toEqual({ freeGb: 3, totalGb: 30, usedPercent: 90 });
135
+ expect(diskUse({})).toBeNull();
136
+ });
137
+
138
+ it("reports nothing for a healthy system and never passes an unread part", () => {
139
+ expect(homeProblems(snapshot({}), NOW)).toEqual([]);
140
+ expect(homeProblems(snapshot({ backups: null, unread: ["backup list"] }), NOW)).toEqual(["the backup list could not be read"]);
141
+ });
142
+
143
+ it("lists each kind of problem in one line", () => {
144
+ const problems = homeProblems(
145
+ snapshot({
146
+ config: { state: "NOT_RUNNING", safe_mode: true },
147
+ supervisor: { healthy: false, supported: false },
148
+ resolution: { unhealthy: ["docker"], unsupported: ["os"], issues: [{ type: "free_space", context: "system" }] },
149
+ entries: [{ domain: "nest", title: "Nest", state: "setup_error", reason: "Auth failed" }],
150
+ repairs: { issues: [{ issue_domain: "hue", translation_key: "bridge_update", severity: "warning" }] },
151
+ states: [{ entity_id: "update.os", state: "on", attributes: { title: "Operating System", installed_version: "18.4", latest_version: "18.5" } }],
152
+ backups: { backups: [{ date: "2026-11-01T04:00:00Z", failed_agent_ids: ["cloud.cloud"] }], agent_errors: {} },
153
+ host: { disk_free: 2, disk_total: 30 },
154
+ }),
155
+ NOW,
156
+ );
157
+ expect(problems).toEqual([
158
+ "Home Assistant is in state NOT_RUNNING",
159
+ "Home Assistant runs in safe mode",
160
+ "the Supervisor is unhealthy: docker",
161
+ "the installation is unsupported: os",
162
+ "the Supervisor reports free_space (system)",
163
+ "the Nest integration (nest) did not load: setup_error, Auth failed",
164
+ "1 repair waits: bridge_update (hue)",
165
+ "1 update waits: Operating System 18.4 → 18.5",
166
+ "the newest backup is 11 days old",
167
+ "the newest backup failed for cloud.cloud",
168
+ "the disk is 93 % full (2 GB free)",
169
+ ]);
170
+ });
171
+
172
+ it("keeps the newest log lines", () => {
173
+ expect(tailLines("a\n\nb\nc\n", 2)).toEqual(["b", "c"]);
174
+ });
175
+ });
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Home Assistant through its WebSocket API (`/api/websocket`): sign in with a long-lived access token,
3
+ * send commands, read results. The Supervisor's information is reachable only this way (`supervisor/api`);
4
+ * Core's REST proxy forwards logs and backups, nothing else. The pure functions below turn the answers
5
+ * into what a person has to know.
6
+ */
7
+ import { ServiceError } from "./errors.ts";
8
+
9
+ /** Sends one command and resolves with its `result`. */
10
+ export type HaCall = (type: string, fields?: Record<string, unknown>) => Promise<unknown>;
11
+
12
+ const CONNECT_TIMEOUT_MS = 15_000;
13
+ const CALL_TIMEOUT_MS = 30_000;
14
+
15
+ interface Pending {
16
+ type: string;
17
+ resolve: (value: unknown) => void;
18
+ reject: (err: Error) => void;
19
+ }
20
+
21
+ /** Opens the WebSocket API, signs in, runs `fn`, and closes the connection whatever happens. */
22
+ export async function haSession<T>(baseUrl: string, token: string, fn: (call: HaCall) => Promise<T>, socketFactory: (url: string) => WebSocket = (url) => new WebSocket(url)): Promise<T> {
23
+ const url = new URL("/api/websocket", baseUrl);
24
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
25
+ const socket = socketFactory(url.href);
26
+ const pending = new Map<number, Pending>();
27
+ let nextId = 1;
28
+ let failure: Error | null = null;
29
+ const fail = (err: Error): Error => {
30
+ failure ??= err;
31
+ for (const p of pending.values()) p.reject(failure);
32
+ pending.clear();
33
+ return failure;
34
+ };
35
+ const ready = new Promise<void>((resolve, reject) => {
36
+ const timer = setTimeout(() => reject(fail(new ServiceError(`home assistant did not answer at ${url.host} within ${CONNECT_TIMEOUT_MS / 1000} s`))), CONNECT_TIMEOUT_MS);
37
+ const settle = (err?: Error) => {
38
+ clearTimeout(timer);
39
+ if (err) reject(fail(err));
40
+ else resolve();
41
+ };
42
+ socket.addEventListener("message", (event) => {
43
+ let msg: Record<string, unknown>;
44
+ try {
45
+ msg = JSON.parse(String(event.data)) as Record<string, unknown>;
46
+ } catch {
47
+ return;
48
+ }
49
+ if (msg.type === "auth_required") socket.send(JSON.stringify({ type: "auth", access_token: token }));
50
+ else if (msg.type === "auth_ok") settle();
51
+ else if (msg.type === "auth_invalid") settle(new ServiceError("home assistant refused the access token"));
52
+ else if (msg.type === "result" && typeof msg.id === "number") {
53
+ const p = pending.get(msg.id);
54
+ if (!p) return;
55
+ pending.delete(msg.id);
56
+ if (msg.success === true) p.resolve(msg.result);
57
+ else p.reject(new ServiceError(`home assistant refused ${p.type}: ${text(field(msg.error, "message"))?.slice(0, 200) ?? "no reason given"}`));
58
+ }
59
+ });
60
+ socket.addEventListener("error", () => settle(new ServiceError(`home assistant is not reachable at ${url.host}`)));
61
+ socket.addEventListener("close", () => settle(new ServiceError("home assistant closed the connection")));
62
+ });
63
+ const call: HaCall = (type, fields = {}) =>
64
+ new Promise((resolve, reject) => {
65
+ if (failure) {
66
+ reject(failure);
67
+ return;
68
+ }
69
+ const id = nextId++;
70
+ const timer = setTimeout(() => {
71
+ pending.delete(id);
72
+ reject(new ServiceError(`home assistant did not answer ${type} within ${CALL_TIMEOUT_MS / 1000} s`));
73
+ }, CALL_TIMEOUT_MS);
74
+ const done =
75
+ <A>(then: (arg: A) => void) =>
76
+ (arg: A) => {
77
+ clearTimeout(timer);
78
+ then(arg);
79
+ };
80
+ pending.set(id, { type, resolve: done(resolve), reject: done(reject) });
81
+ socket.send(JSON.stringify({ id, type, ...fields }));
82
+ });
83
+ try {
84
+ await ready;
85
+ return await fn(call);
86
+ } finally {
87
+ socket.close();
88
+ }
89
+ }
90
+
91
+ function field(value: unknown, key: string): unknown {
92
+ return typeof value === "object" && value !== null ? (value as Record<string, unknown>)[key] : undefined;
93
+ }
94
+
95
+ function text(value: unknown): string | null {
96
+ return typeof value === "string" && value.length > 0 ? value : null;
97
+ }
98
+
99
+ function rows(value: unknown): Record<string, unknown>[] {
100
+ return Array.isArray(value) ? value.filter((v): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v)) : [];
101
+ }
102
+
103
+ function strings(value: unknown): string[] {
104
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
105
+ }
106
+
107
+ /** Everything one status read collects; a part that could not be read is `null` and named in `unread`. */
108
+ export interface HomeSnapshot {
109
+ config: unknown;
110
+ states: unknown;
111
+ entries: unknown;
112
+ repairs: unknown;
113
+ backups: unknown;
114
+ supervisor: unknown;
115
+ core: unknown;
116
+ os: unknown;
117
+ host: unknown;
118
+ resolution: unknown;
119
+ addons: unknown;
120
+ unread: string[];
121
+ }
122
+
123
+ export interface FailedIntegration {
124
+ domain: string;
125
+ title: string;
126
+ state: string;
127
+ reason: string | null;
128
+ }
129
+
130
+ /** Config entries that are enabled but did not load. */
131
+ export function failedIntegrations(entries: unknown): FailedIntegration[] {
132
+ return rows(entries)
133
+ .filter((e) => e.disabled_by == null && typeof e.state === "string" && !["loaded", "not_loaded", "setup_in_progress"].includes(e.state))
134
+ .map((e) => ({ domain: text(e.domain) ?? "?", title: text(e.title) ?? "?", state: e.state as string, reason: text(e.reason) }));
135
+ }
136
+
137
+ export interface Repair {
138
+ domain: string;
139
+ issue: string;
140
+ severity: string;
141
+ fixable: boolean;
142
+ }
143
+
144
+ /** Open repair issues, without the ones the owner chose to ignore. */
145
+ export function openRepairs(result: unknown): Repair[] {
146
+ return rows(field(result, "issues"))
147
+ .filter((i) => i.ignored !== true)
148
+ .map((i) => ({ domain: text(i.issue_domain) ?? text(i.domain) ?? "?", issue: text(i.translation_key) ?? text(i.issue_id) ?? "?", severity: text(i.severity) ?? "?", fixable: i.is_fixable === true }));
149
+ }
150
+
151
+ export interface PendingUpdate {
152
+ entity: string;
153
+ title: string;
154
+ installed: string | null;
155
+ latest: string | null;
156
+ }
157
+
158
+ /** `update.*` entities that report a newer version and are not skipped. */
159
+ export function pendingUpdates(states: unknown): PendingUpdate[] {
160
+ return rows(states)
161
+ .filter((s) => typeof s.entity_id === "string" && s.entity_id.startsWith("update.") && s.state === "on")
162
+ .map((s) => ({
163
+ entity: s.entity_id as string,
164
+ title: text(field(s.attributes, "title")) ?? text(field(s.attributes, "friendly_name")) ?? (s.entity_id as string),
165
+ installed: text(field(s.attributes, "installed_version")),
166
+ latest: text(field(s.attributes, "latest_version")),
167
+ }));
168
+ }
169
+
170
+ export interface EntityState {
171
+ entity: string;
172
+ name: string;
173
+ state: string;
174
+ }
175
+
176
+ /** Entities in one state (default `unavailable`), optionally of one domain. */
177
+ export function entitiesIn(states: unknown, state = "unavailable", domain?: string): EntityState[] {
178
+ return rows(states)
179
+ .filter((s) => typeof s.entity_id === "string" && s.state === state && (domain === undefined || s.entity_id.startsWith(`${domain}.`)))
180
+ .map((s) => ({ entity: s.entity_id as string, name: text(field(s.attributes, "friendly_name")) ?? (s.entity_id as string), state }));
181
+ }
182
+
183
+ export interface BackupSummary {
184
+ count: number;
185
+ newest: string | null;
186
+ ageHours: number | null;
187
+ lastAutomatic: string | null;
188
+ failedAgents: string[];
189
+ agentErrors: string[];
190
+ }
191
+
192
+ /** The newest backup and anything the backup locations reported as failed. */
193
+ export function backupSummary(info: unknown, now: number): BackupSummary {
194
+ const backups = rows(field(info, "backups"));
195
+ const dates = backups.flatMap((b) => (typeof b.date === "string" && !Number.isNaN(Date.parse(b.date)) ? [b.date] : [])).sort((a, b) => Date.parse(a) - Date.parse(b));
196
+ const newest = dates.at(-1) ?? null;
197
+ const errors = field(info, "agent_errors");
198
+ return {
199
+ count: backups.length,
200
+ newest,
201
+ ageHours: newest === null ? null : Math.round((now - Date.parse(newest)) / 3_600_000),
202
+ lastAutomatic: text(field(info, "last_completed_automatic_backup")),
203
+ failedAgents: [...new Set(backups.filter((b) => b.date === newest).flatMap((b) => strings(b.failed_agent_ids)))],
204
+ agentErrors: typeof errors === "object" && errors !== null ? Object.keys(errors) : [],
205
+ };
206
+ }
207
+
208
+ export interface DiskUse {
209
+ freeGb: number;
210
+ totalGb: number;
211
+ usedPercent: number;
212
+ }
213
+
214
+ /** The data disk from the Supervisor's `/host/info`. */
215
+ export function diskUse(host: unknown): DiskUse | null {
216
+ const free = field(host, "disk_free");
217
+ const total = field(host, "disk_total");
218
+ if (typeof free !== "number" || typeof total !== "number" || total <= 0) return null;
219
+ return { freeGb: free, totalGb: total, usedPercent: Math.round((1 - free / total) * 100) };
220
+ }
221
+
222
+ /** A backup older than this is a problem: Home Assistant makes one every night by default. */
223
+ const BACKUP_MAX_AGE_HOURS = 48;
224
+ const DISK_MAX_USED_PERCENT = 85;
225
+ const NAMED = 4;
226
+
227
+ function named(items: string[]): string {
228
+ return items.length <= NAMED ? items.join(", ") : `${items.slice(0, NAMED).join(", ")} and ${items.length - NAMED} more`;
229
+ }
230
+
231
+ /** What a person has to look at, one line each; an unread part is a problem too, never a pass. */
232
+ export function homeProblems(s: HomeSnapshot, now: number): string[] {
233
+ const out: string[] = s.unread.map((part) => `the ${part} could not be read`);
234
+ const state = text(field(s.config, "state"));
235
+ if (s.config !== null && state !== "RUNNING") out.push(`Home Assistant is in state ${state ?? "unknown"}`);
236
+ if (field(s.config, "safe_mode") === true) out.push("Home Assistant runs in safe mode");
237
+ if (field(s.config, "recovery_mode") === true) out.push("Home Assistant runs in recovery mode");
238
+ if (s.supervisor !== null && field(s.supervisor, "healthy") === false) out.push(`the Supervisor is unhealthy${strings(field(s.resolution, "unhealthy")).length > 0 ? `: ${strings(field(s.resolution, "unhealthy")).join(", ")}` : ""}`);
239
+ if (s.supervisor !== null && field(s.supervisor, "supported") === false) out.push(`the installation is unsupported${strings(field(s.resolution, "unsupported")).length > 0 ? `: ${strings(field(s.resolution, "unsupported")).join(", ")}` : ""}`);
240
+ const issues = rows(field(s.resolution, "issues")).map((i) => `${text(i.type) ?? "?"}${text(i.context) ? ` (${text(i.context)})` : ""}`);
241
+ if (issues.length > 0) out.push(`the Supervisor reports ${named(issues)}`);
242
+ for (const f of failedIntegrations(s.entries)) out.push(`the ${f.title} integration (${f.domain}) did not load: ${f.state}${f.reason ? `, ${f.reason.slice(0, 160)}` : ""}`);
243
+ const repairs = openRepairs(s.repairs);
244
+ if (repairs.length > 0) out.push(`${repairs.length} repair${repairs.length === 1 ? " waits" : "s wait"}: ${named(repairs.map((r) => `${r.issue} (${r.domain})`))}`);
245
+ const updates = pendingUpdates(s.states);
246
+ if (updates.length > 0) out.push(`${updates.length} update${updates.length === 1 ? " waits" : "s wait"}: ${named(updates.map((u) => `${u.title} ${u.installed ?? "?"} → ${u.latest ?? "?"}`))}`);
247
+ if (s.backups !== null) {
248
+ const b = backupSummary(s.backups, now);
249
+ if (b.ageHours === null) out.push("Home Assistant has no backup");
250
+ else if (b.ageHours > BACKUP_MAX_AGE_HOURS) out.push(`the newest backup is ${Math.round(b.ageHours / 24)} days old`);
251
+ if (b.failedAgents.length > 0) out.push(`the newest backup failed for ${b.failedAgents.join(", ")}`);
252
+ if (b.agentErrors.length > 0) out.push(`backup locations with errors: ${b.agentErrors.join(", ")}`);
253
+ }
254
+ const disk = diskUse(s.host);
255
+ if (disk !== null && disk.usedPercent > DISK_MAX_USED_PERCENT) out.push(`the disk is ${disk.usedPercent} % full (${disk.freeGb} GB free)`);
256
+ return out;
257
+ }
258
+
259
+ /** The newest `lines` lines of a log text, each cut to a readable width. */
260
+ export function tailLines(log: string, lines: number): string[] {
261
+ return log
262
+ .split("\n")
263
+ .filter((l) => l.trim().length > 0)
264
+ .slice(-lines)
265
+ .map((l) => l.slice(0, 400));
266
+ }
@@ -245,11 +245,13 @@ export function deviceNetworkWrite(args: string[]): UnifiWrite {
245
245
  }
246
246
 
247
247
  const CLIENT_FIXED_IP_KEYS = new Set(["use_fixedip", "fixed_ip", "network_id"]);
248
+ /** A client record's `_id`: 24 hex digits, or a UUID (Mira's console returned UUIDs on 2026-11-12). */
249
+ const CLIENT_ID = /^(?:[0-9a-f]{24}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
248
250
 
249
251
  /** `client-fixed-ip <clientId> <json>`: only a known client's DHCP reservation, through the application's client records. */
250
252
  export function clientFixedIpWrite(args: string[]): UnifiWrite {
251
253
  const [id, json, ...extra] = args;
252
- if (id === undefined || !NAT_ID.test(id) || json === undefined || extra.length > 0) throw new UsageError("client-fixed-ip <clientId> <json>");
254
+ if (id === undefined || !CLIENT_ID.test(id) || json === undefined || extra.length > 0) throw new UsageError("client-fixed-ip <clientId> <json>");
253
255
  const body = jsonBody(json);
254
256
  const keys = Object.keys(JSON.parse(body) as Record<string, unknown>);
255
257
  if (keys.length === 0 || keys.some((k) => !CLIENT_FIXED_IP_KEYS.has(k))) throw new UsageError(`client-fixed-ip body keys: ${[...CLIENT_FIXED_IP_KEYS].join(", ")}`);
@@ -10,6 +10,7 @@ import { buildBackupRemote, command as backupCommand } from "./backup/run.ts";
10
10
  import { buildNodeRemote, parseJoinArgs, parseParams, parseRecordFilters, technitiumRequest, technitiumTarget, command as dnsCommand } from "./dns/run.ts";
11
11
  import { buildVpsRemote, command as edgeCommand, isTransientSshFailure, PUBLIC_ROUTES, routeProbe } from "./edge/run.ts";
12
12
  import { API_PREFIXES, buildDmzRemote, installedRelease, publishedSha256, validateApiPath, command as identityCommand } from "./identity/run.ts";
13
+ import { command as homeCommand, parseAction, parseEntityQuery, parseLogs } from "./home/run.ts";
13
14
  import { buildInferenceRemote, command as inferenceCommand } from "./inference/run.ts";
14
15
  import { MAX_ADD_IDS, MAX_EXCLUDE_IDS, buildTrendarrCall, interpretRun, parseImdbIds, parseQueueRemove, stuckRecords, trendarrConfig, trendarrError, trendarrWarnings, command as mediaCommand } from "./media/run.ts";
15
16
  import { ServiceError, UsageError } from "./lib/errors.ts";
@@ -155,6 +156,8 @@ describe("network wrapper", () => {
155
156
  expect(() => portForwardDelete(["../x", "qb"])).toThrow(UsageError);
156
157
  const fixed = JSON.stringify({ use_fixedip: true, fixed_ip: "10.1.50.50", network_id: "0123456789abcdef01234567" });
157
158
  expect(clientFixedIpWrite(["0123456789abcdef01234567", fixed])).toEqual({ method: "PUT", path: "/api/s/default/rest/user/0123456789abcdef01234567", body: fixed });
159
+ expect(clientFixedIpWrite(["071e4027-d2e9-4f61-9fc4-5a92e85cf842", fixed]).path).toBe("/api/s/default/rest/user/071e4027-d2e9-4f61-9fc4-5a92e85cf842");
160
+ expect(() => clientFixedIpWrite(["071e4027-d2e9-4f61-9fc4-5a92e85cf84/..", fixed])).toThrow(/client-fixed-ip/);
158
161
  expect(() => clientFixedIpWrite(["0123456789abcdef01234567", JSON.stringify({ name: "x" })])).toThrow(/body keys/);
159
162
  expect(appGetPath(["/v2/api/site/default/nat"])).toBe("/v2/api/site/default/nat");
160
163
  expect(() => appGetPath(["/api/s/other/stat/device"])).toThrow(UsageError);
@@ -1055,6 +1058,43 @@ describe("media wrapper", () => {
1055
1058
  });
1056
1059
  });
1057
1060
 
1061
+ describe("home wrapper", () => {
1062
+ it("prints help without touching config", async () => {
1063
+ const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
1064
+ expect(await homeCommand(["--help"])).toBe(0);
1065
+ expect(String(write.mock.calls[0][0])).toContain("problems");
1066
+ write.mockRestore();
1067
+ });
1068
+
1069
+ it("checks every argument before it reads a secret", async () => {
1070
+ await expect(homeCommand(["status", "now"])).rejects.toThrow(/takes no arguments/);
1071
+ await expect(homeCommand(["update", "update.home_assistant_core_update"])).rejects.toThrow(/needs --confirm/);
1072
+ await expect(homeCommand(["update", "light.kitchen", "--confirm"])).rejects.toThrow(/update <update\.entity_id>/);
1073
+ await expect(homeCommand(["restart"])).rejects.toThrow(/needs --confirm/);
1074
+ await expect(homeCommand(["restart", "now", "--confirm"])).rejects.toThrow(/restart --confirm/);
1075
+ await expect(homeCommand(["backup"])).rejects.toThrow(/unknown command/);
1076
+ });
1077
+
1078
+ it("parses entity filters, log sources, and actions", () => {
1079
+ expect(parseEntityQuery([])).toEqual({ state: "unavailable", max: 50 });
1080
+ expect(parseEntityQuery(["--state", "on", "--domain", "light", "--max", "200"])).toEqual({ state: "on", domain: "light", max: 200 });
1081
+ expect(() => parseEntityQuery(["--max", "201"])).toThrow(/1 to 200/);
1082
+ expect(() => parseEntityQuery(["--domain", "light.kitchen"])).toThrow(UsageError);
1083
+ expect(() => parseEntityQuery(["--state"])).toThrow(/needs a value/);
1084
+ expect(parseLogs(["core"])).toEqual({ path: "core/logs", lines: 100 });
1085
+ expect(parseLogs(["addon", "core_matter_server", "400"])).toEqual({ path: "addons/core_matter_server/logs", lines: 400 });
1086
+ expect(() => parseLogs(["addon", "../core"])).toThrow(UsageError);
1087
+ expect(() => parseLogs(["audio"])).toThrow(UsageError);
1088
+ expect(() => parseLogs(["core", "401"])).toThrow(/1 to 400/);
1089
+ expect(parseAction(["light.turn_on", JSON.stringify({ target: { entity_id: "light.kitchen" }, data: { brightness_pct: 40 } })])).toEqual({ domain: "light", service: "turn_on", target: { entity_id: "light.kitchen" }, data: { brightness_pct: 40 } });
1090
+ expect(parseAction(["homeassistant.reload_all"])).toEqual({ domain: "homeassistant", service: "reload_all" });
1091
+ expect(() => parseAction(["light"])).toThrow(UsageError);
1092
+ expect(() => parseAction(["light.turn_on", "{"])).toThrow(/must be JSON/);
1093
+ expect(() => parseAction(["light.turn_on", JSON.stringify({ entity_id: "light.kitchen" })])).toThrow(UsageError);
1094
+ expect(() => parseAction(["light.turn_on", JSON.stringify({ target: "light.kitchen" })])).toThrow(/target must be a JSON object/);
1095
+ });
1096
+ });
1097
+
1058
1098
  describe("dns stale-zone-delete", () => {
1059
1099
  let home: string;
1060
1100
  const originalHome = process.env.HOME;