@astrofoundry/pi-astro 0.40.70 → 0.40.72

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/agents/home.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
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.
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, any Home Assistant action, and through its WebSocket, REST, and Supervisor APIs everything its own interface can read or change (entities, devices, areas, integrations, automations, scripts, helpers, dashboards, add-ons). Use for what is wrong with the smart home, why a device or integration fails, installing an update, switching or checking a device, and creating or changing automations, dashboards, and settings.
4
4
  tools: home, subagent
5
5
  skills: home
6
6
  systemPromptMode: replace
@@ -16,7 +16,8 @@ Rules:
16
16
 
17
17
  - Read first: `status` or `problems` before you explain or change anything. Name what you read, not what you assume.
18
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.
19
+ - Change only what the task asks for. `update`, `restart`, `action`, `integration-remove`, `ws`, and every `rest` or `supervisor` call that is not a `get` ask an owner for approval in chat; say what you are about to send and why before you call them.
20
+ - Read before you write: fetch the current automation, dashboard, or options, change only what the task names, and send the whole object back. Read it again afterwards and report what changed.
20
21
  - 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
22
  - Never print a token, a password, or a URL that carries one; summarise such a log line.
22
23
  - 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:**`.
@@ -19,6 +19,14 @@ describe("approvals", () => {
19
19
  expect(isRisky("media", ["bazarr", "status"])).toBe(false);
20
20
  expect(isRisky("home", ["action", "light.turn_off", "{}"])).toBe(true);
21
21
  expect(isRisky("home", ["restart"])).toBe(true);
22
+ expect(isRisky("home", ["integration-remove", "01JABCDEFGHJKMNPQRSTVWXYZ0"])).toBe(true);
23
+ expect(isRisky("home", ["integrations", "--failed"])).toBe(false);
24
+ expect(isRisky("home", ["ws", "config/entity_registry/update", "{}"])).toBe(true);
25
+ expect(isRisky("home", ["ws-read", "config/entity_registry/list"])).toBe(false);
26
+ expect(isRisky("home", ["rest", "post", "/api/config/automation/config/1", "{}"])).toBe(true);
27
+ expect(isRisky("home", ["rest", "get", "/api/config"])).toBe(false);
28
+ expect(isRisky("home", ["supervisor", "post", "/host/reboot"])).toBe(true);
29
+ expect(isRisky("home", ["supervisor", "get", "/addons"])).toBe(false);
22
30
  expect(isRisky("home", ["problems"])).toBe(false);
23
31
  expect(isRisky("home", ["logs", "core", "50"])).toBe(false);
24
32
  expect(isRisky("identity", ["zitadel", "DELETE", "/v2/users/1"])).toBe(true);
@@ -50,8 +50,9 @@ 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
+ // Everything that changes Home Assistant: an update, a restart, any action (lights, locks, scenes), any
54
+ // WebSocket command outside the wrapper's read list, and every REST or Supervisor call that is not a GET.
55
+ home: [/^(update|restart|action|integration-remove)\b/, /^ws(\s|$)/, /^(rest|supervisor)\s+(post|put|delete)\b/],
55
56
  };
56
57
 
57
58
  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.70",
3
+ "version": "0.40.72",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -1,6 +1,6 @@
1
1
  ---
2
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.
3
+ description: How the home specialist reads Home Assistant's health, finds what is wrong, reads logs, installs updates, restarts Core, runs actions, and reads or changes anything else through Home Assistant's WebSocket, REST, and Supervisor APIs with the home tool.
4
4
  ---
5
5
 
6
6
  # Home specialist
@@ -14,11 +14,20 @@ Home Assistant OS runs as VM 112 `homeassistant` on SPACE-X at Mira, in the IoT
14
14
  | `["status"]` | versions, Supervisor health, integrations that did not load, repairs, waiting updates, backups, disk, add-ons, entity counts, and the problem list |
15
15
  | `["problems"]` | only what needs a person, one line each, plus the number of unavailable entities |
16
16
  | `["entities"]` | unavailable entities (50); `--state <state>`, `--domain light`, `--max 1..200` |
17
+ | `["integrations"]` | every integration entry with `entry_id`, `domain`, `title`, `state`, `reason`, `disabled_by`; `--failed` keeps those that did not load |
18
+ | `["integration-remove", "<entry_id>", "--confirm"]` | delete one integration entry with its devices and entities; asks an owner. For leftovers such as hardware that no longer exists, never for an integration that only fails for now |
17
19
  | `["logs", "core", "200"]` | the newest lines of Core's log; also `supervisor`, `host`; default 100, at most 400 |
18
20
  | `["logs", "addon", "core_matter_server"]` | one add-on's log, by the slug from `status` |
19
21
  | `["update", "update.home_assistant_core_update", "--confirm"]` | install one waiting update; asks an owner |
20
22
  | `["restart", "--confirm"]` | restart Home Assistant Core; asks an owner |
21
23
  | `["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 |
24
+ | `["check-config"]` | validate the configuration files; changes nothing |
25
+ | `["ws-read", "config/entity_registry/list"]` | a WebSocket command that only reads; the tool refuses any other type |
26
+ | `["ws", "config/entity_registry/update", "{\"entity_id\":\"light.x\",\"name\":\"Desk\"}"]` | any WebSocket command; asks an owner |
27
+ | `["rest", "get", "/api/config/automation/config/1699999999999"]` | GET any route under `/api/` |
28
+ | `["rest", "post", "/api/config/automation/config/1699999999999", "{...}"]` | any other REST call (`post`, `put`, `delete`); asks an owner |
29
+ | `["supervisor", "get", "/addons/core_matter_server/info"]` | GET a Supervisor endpoint |
30
+ | `["supervisor", "post", "/addons/core_matter_server/restart"]` | any other Supervisor call; asks an owner |
22
31
 
23
32
  ## Output
24
33
 
@@ -26,11 +35,37 @@ Home Assistant OS runs as VM 112 `homeassistant` on SPACE-X at Mira, in the IoT
26
35
  - `unread` names the parts Home Assistant did not answer; each is also in `problems`. Never report such a part as fine.
27
36
  - `problems`: `{ "problems": [...], "unavailable": n, "version": "..." }`. An empty list means nothing needs a person.
28
37
  - `entities`: `{ "total": n, "entities": [{ "entity", "name", "state" }] }`.
38
+ - `integrations`: `{ "total": n, "integrations": [{ "entry_id", "domain", "title", "state", "reason", "disabled_by" }] }`.
39
+ - `integration-remove`: `{ "status": "removed", "entry_id", "require_restart" }`; restart Core when `require_restart` is true.
29
40
  - `logs`: `{ "lines": [...] }`, newest last.
30
41
  - `update`: `{ "status": "update started", "entity" }`. The install runs in Home Assistant; read `status` again after a few minutes.
31
42
  - `restart`: `{ "status": "restart requested" }`. The tool cannot reach Home Assistant while it restarts.
32
43
  - `action`: `{ "status": "done", "action" }`.
33
44
 
45
+ ## Everything else: the three generic doors
46
+
47
+ Home Assistant's own web interface works through these same APIs, so what the interface can do, `ws`, `rest`, and `supervisor` can do. Reads are free; every change asks an owner, so say first what you will send and why. Answers above 60,000 characters are cut (a list keeps its first items and reports `total` and `shown`), and values under secret-looking keys read `[redacted]`. Names below were checked against Home Assistant 2026.11.1; when a call is refused, read the error and do not guess a second name.
48
+
49
+ | Task | Read | Change |
50
+ |---|---|---|
51
+ | Entities | `ws-read config/entity_registry/list`, `.../get {"entity_id"}` | `ws config/entity_registry/update {"entity_id", "name", "new_entity_id", "area_id", "disabled_by", "hidden_by", "icon"}`, `ws config/entity_registry/remove {"entity_id"}` |
52
+ | Devices | `ws-read config/device_registry/list` | `ws config/device_registry/update {"device_id", "name_by_user", "area_id", "disabled_by"}` |
53
+ | Areas, floors, labels | `ws-read config/area_registry/list` (also `floor_registry`, `label_registry`) | `ws config/area_registry/create {"name"}`, `.../update {"area_id", ...}`, `.../delete {"area_id"}` |
54
+ | Integrations | `integrations`; `rest get /api/config/config_entries/flow_handlers` | reload: `rest post /api/config/config_entries/entry/<entry_id>/reload`; add: `rest post /api/config/config_entries/flow {"handler": "<domain>"}`, then `rest post /api/config/config_entries/flow/<flow_id> {...the fields its form asks for}`; options: the same under `/api/config/config_entries/options/flow`; delete: `integration-remove` |
55
+ | Automations | `ws-read automation/config {"entity_id"}`, `rest get /api/config/automation/config/<id>`, runs: `ws-read trace/list {"domain": "automation"}` then `trace/get {"domain", "item_id", "run_id"}` | `rest post /api/config/automation/config/<id> {...the whole automation}`, `rest delete` the same path; turn on or off with `action automation.turn_on` |
56
+ | Scripts, scenes | `rest get /api/config/script/config/<key>`, `/api/config/scene/config/<id>` | `rest post` or `rest delete` the same path |
57
+ | Helpers | `ws-read input_boolean/list` (also `input_number`, `input_select`, `input_text`, `input_datetime`, `counter`, `timer`, `schedule`) | `ws input_boolean/create {"name"}`, `.../update {"input_boolean_id", ...}`, `.../delete {"input_boolean_id"}` |
58
+ | Dashboards | `ws-read lovelace/dashboards/list`, `ws-read lovelace/config {"url_path": null}` (null is the default dashboard) | `ws lovelace/config/save {"url_path", "config"}`; read the whole config first, change it, send it whole |
59
+ | Repairs | `ws-read repairs/list_issues` | `ws repairs/ignore_issue {"domain", "issue_id", "ignore": true}` |
60
+ | Backups | `ws-read backup/info`, `ws-read backup/agents/info` | `ws backup/generate_with_automatic_settings`, `ws backup/delete {"backup_id"}`; never `backup/restore` without the owner's explicit request |
61
+ | History and log book | `ws-read history/history_during_period {"start_time", "end_time", "entity_ids": [...]}`, `ws-read logbook/get_events {"start_time", "entity_ids": [...]}`, `ws-read system_log/list` | |
62
+ | Core settings | `ws-read get_config` | `ws config/core/update {"location_name", "time_zone", "unit_system", ...}` |
63
+ | Add-ons (the interface calls them Apps) | `supervisor get /addons`, `/addons/<slug>/info`, `/addons/<slug>/stats`, `/store/addons` | `supervisor post /addons/<slug>/start`, `/stop`, `/restart`, `/update`, `/uninstall`; `supervisor post /store/addons/<slug>/install`; options: `supervisor post /addons/<slug>/options {"options": {...all options}}` |
64
+ | Supervisor, system, host | `supervisor get /supervisor/info`, `/core/info`, `/os/info`, `/host/info`, `/network/info`, `/resolution/info`, `/jobs/info`, `/mounts` | `supervisor post /core/update`, `/os/update`, `/supervisor/update`, `/core/restart`, `/host/reboot`, `/host/shutdown`, `/supervisor/repair`, `/resolution/healthcheck` |
65
+ | Templates | | `rest post /api/template {"template": "{{ states('sun.sun') }}"}` renders one; it is a POST, so it asks |
66
+
67
+ Limits: no API reads or writes files, so `configuration.yaml` and other YAML stay with the owner (File editor add-on); run `check-config` after he changes one, then `restart`. `ws-read` knows registries, lists, history, traces, and dashboards; a read it does not know goes through `ws` and asks. Never read `backup/config/info`, `application_credentials`, or Thread credentials on your own: they hold secrets.
68
+
34
69
  ## Finding a cause
35
70
 
36
71
  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.
@@ -50,5 +85,6 @@ Short and factual. Name devices and integrations by their Home Assistant names.
50
85
  ## When to stop and report
51
86
 
52
87
  - 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.
88
+ - The task needs a file edit in Home Assistant's configuration, or a pairing that needs a button press, a code, or a login in a browser: say what the owner has to open or press.
89
+ - A change you cannot undo (deleting an integration, an automation, a dashboard, a backup; uninstalling an add-on; a host shutdown): name what will be lost in the approval text, and stop when the owner did not ask for exactly that.
54
90
  - The task would restore a backup or reset Home Assistant: stop and ask the owner.
@@ -63,7 +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
+ - `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`, `action` (any Home Assistant action with `target` and `data`), and `integration-remove` (since 0.40.71: `DELETE /api/config/config_entries/entry/<id>`, for leftovers such as the Pi's Bluetooth adapter after the move to a VM) change things and are in `RISKY`; all but `action` also need `--confirm`. Since 0.40.72 three generic doors reach everything Home Assistant's own interface can do, the model of the community's ha-mcp server without a second server that holds an administrator token: `ws <type> [json]` (any WebSocket command), `rest <get|post|put|delete> <path> [json]` (any route under `/api/`; dot segments, escapes, and `/api/websocket` refused), and `supervisor <get|post|put|delete> <endpoint> [json]` (through `supervisor/api`; logs and downloads refused because they are not JSON). Reads need no approval: `rest get`, `supervisor get`, and `ws-read`, which sends only the types in `READ_COMMANDS` of `lib/home-assistant.ts` (registries, lists, history, traces, dashboards, the helpers' `<domain>/list`; never `backup/config/info`, `application_credentials`, or `auth`, which return credentials). Everything else is in `RISKY` (`/^ws(\s|$)/` so that `ws-read` stays free). Generic answers pass `redactSecrets` and `bounded` (60,000 characters; a list keeps its first items). `restart` treats a connection Core closes as started, because Core often closes the socket before it sends the result. No Home Assistant API reads or writes files: YAML edits stay with the owner (ha-mcp needs its own component inside Home Assistant for that). The skill's table of commands was checked against Core 2026.11.1 and the Supervisor's route table. 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.
67
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.
68
68
 
69
69
  ## Gate
@@ -15,7 +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
+ | `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>>`, `integrations`, `check-config`, `ws-read <type> [json]`, `rest get <path>`, `supervisor get <endpoint>`; with approval `integration-remove <entry_id> --confirm`, `update <update.entity> --confirm`, `restart --confirm`, `action <domain.action> [json]`, `ws <type> [json]`, `rest <post\|put\|delete> <path> [json]`, `supervisor <post\|put\|delete> <endpoint> [json]`; generic answers are redacted and cut to 60,000 characters |
19
19
 
20
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.
21
21
 
@@ -1,9 +1,10 @@
1
1
  import { readConfig } from "../lib/config.ts";
2
2
  import { ServiceError, UsageError } from "../lib/errors.ts";
3
- import { backupSummary, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, openRepairs, pendingUpdates, tailLines } from "../lib/home-assistant.ts";
3
+ import { backupSummary, bounded, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, integrationRows, isReadCommand, openRepairs, pendingUpdates, tailLines } from "../lib/home-assistant.ts";
4
4
  import type { HaCall, HomeSnapshot } from "../lib/home-assistant.ts";
5
5
  import { main } from "../lib/main.ts";
6
6
  import { printJson, printRaw } from "../lib/output.ts";
7
+ import { redactSecrets } from "../lib/sanitize.ts";
7
8
  import { readSecret } from "../lib/secrets.ts";
8
9
 
9
10
  const SERVICE = "home";
@@ -17,31 +18,52 @@ const SHAPE = { homeAssistantUrl: "string" } as const;
17
18
 
18
19
  const MAX_ENTITIES = 200;
19
20
  const MAX_LOG_LINES = 400;
21
+ /** The most JSON one generic answer prints; a longer list keeps its first items. */
22
+ const MAX_ANSWER_CHARS = 60_000;
20
23
  const ENTITY_ID = /^[a-z0-9_]+\.[a-z0-9_]+$/;
21
24
  const ACTION = /^[a-z0-9_]+\.[a-z0-9_]+$/;
22
25
  const ADDON_SLUG = /^[a-z0-9_]+$/;
26
+ const ENTRY_ID = /^[0-9A-Za-z]{20,64}$/;
27
+ const WS_TYPE = /^[a-z0-9_]+(?:\/[a-z0-9_]+)*$/;
28
+ const SUPERVISOR_ENDPOINT = /^(?:\/[A-Za-z0-9_-][A-Za-z0-9_.-]*)+$/;
23
29
  const LOG_SOURCES = ["core", "supervisor", "host"];
30
+ const WRITE_METHODS = ["post", "put", "delete"] as const;
31
+ type Method = "get" | (typeof WRITE_METHODS)[number];
24
32
 
25
- const HELP = `home specialist (Home Assistant at Mira, through its WebSocket API and log routes)
33
+ const HELP = `home specialist (Home Assistant at Mira, through its WebSocket API, REST API, and Supervisor)
26
34
 
27
35
  status versions, Supervisor health, integrations that did not load, repairs, updates,
28
36
  backups, disk, add-ons, and the number of unavailable entities
29
37
  problems what needs a person, one line each; a part that cannot be read is a problem too
30
38
  entities [--state <state>] [--domain <domain>] [--max N]
31
39
  entity ids, names, and states (default: state unavailable, 50 of them)
40
+ integrations [--failed] every integration entry with its id, state, and reason
32
41
  logs <core|supervisor|host> [lines]
33
42
  logs addon <slug> [lines] the newest log lines (default 100, at most ${MAX_LOG_LINES})
43
+ check-config validate the configuration files
44
+ ws-read <type> [json] a WebSocket command that only reads: registries, lists, history, traces, dashboards
45
+ rest get <path> GET any route under /api/
46
+ supervisor get <endpoint> GET a Supervisor endpoint, such as /addons/core_matter_server/info
47
+
48
+ Changes; each needs an owner's approval in chat:
49
+ integration-remove <entry_id> --confirm
50
+ delete one integration entry, with its devices and entities
34
51
  update <update.entity_id> --confirm
35
52
  install the update of one update entity
36
53
  restart --confirm restart Home Assistant Core
37
54
  action <domain.action> [json]
38
- run any Home Assistant action with {"target": {...}, "data": {...}}; in chat it asks an owner
55
+ run any Home Assistant action with {"target": {...}, "data": {...}}
56
+ ws <type> [json] any WebSocket command, such as config/entity_registry/update or lovelace/config/save
57
+ rest <post|put|delete> <path> [json]
58
+ any other call under /api/, such as /api/config/automation/config/<id>
59
+ supervisor <post|put|delete> <endpoint> [json]
60
+ any other Supervisor call, such as /addons/<slug>/restart or /host/reboot
39
61
 
40
- status, problems, and entities change nothing.`;
62
+ Answers longer than ${MAX_ANSWER_CHARS} characters are cut, and values under secret-looking keys are redacted.`;
41
63
 
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" });
64
+ /** The Supervisor's answer to a call, through Core's `supervisor/api` command. */
65
+ function supervisorCall(call: HaCall, method: Method, endpoint: string, data?: unknown): Promise<unknown> {
66
+ return call("supervisor/api", { endpoint, method, ...(data === undefined ? {} : { data }) });
45
67
  }
46
68
 
47
69
  async function snapshot(call: HaCall): Promise<HomeSnapshot> {
@@ -60,12 +82,12 @@ async function snapshot(call: HaCall): Promise<HomeSnapshot> {
60
82
  read("integration list", call("config_entries/get")),
61
83
  read("repair list", call("repairs/list_issues")),
62
84
  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")),
85
+ read("Supervisor state", supervisorCall(call, "get", "/supervisor/info")),
86
+ read("Core version", supervisorCall(call, "get", "/core/info")),
87
+ read("operating system state", supervisorCall(call, "get", "/os/info")),
88
+ read("host state", supervisorCall(call, "get", "/host/info")),
89
+ read("Supervisor checks", supervisorCall(call, "get", "/resolution/info")),
90
+ read("add-on list", supervisorCall(call, "get", "/addons")),
69
91
  ]);
70
92
  return { config, states, entries, repairs, backups, supervisor, core, os, host, resolution, addons, unread };
71
93
  }
@@ -157,19 +179,21 @@ function record(value: unknown, name: string): Record<string, unknown> | undefin
157
179
  return value as Record<string, unknown>;
158
180
  }
159
181
 
182
+ function parseJson(json: string | undefined): unknown {
183
+ if (json === undefined) return undefined;
184
+ try {
185
+ return JSON.parse(json) as unknown;
186
+ } catch {
187
+ throw new UsageError("the body must be JSON");
188
+ }
189
+ }
190
+
160
191
  /** `action <domain.action> [json]`: the JSON may carry `target` and `data`, nothing else. */
161
192
  export function parseAction(args: string[]): ActionCall {
162
193
  const usage = 'action <domain.action> [{"target": {...}, "data": {...}}]';
163
194
  const [name, json, ...extra] = args;
164
195
  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
- }
196
+ const body = record(parseJson(json), "the body") ?? {};
173
197
  if (Object.keys(body).some((key) => key !== "target" && key !== "data")) throw new UsageError(usage);
174
198
  const [domain, service] = name.split(".");
175
199
  const target = record(body.target, "target");
@@ -177,6 +201,47 @@ export function parseAction(args: string[]): ActionCall {
177
201
  return { domain, service, ...(target ? { target } : {}), ...(data ? { data } : {}) };
178
202
  }
179
203
 
204
+ /** `ws-read <type> [json]` and `ws <type> [json]`: the command and its fields, without the id the session adds. */
205
+ export function parseWs(args: string[], readOnly: boolean): { type: string; fields: Record<string, unknown> } {
206
+ const usage = `${readOnly ? "ws-read" : "ws"} <type> [json]`;
207
+ const [type, json, ...extra] = args;
208
+ if (type === undefined || !WS_TYPE.test(type) || type === "auth" || extra.length > 0) throw new UsageError(usage);
209
+ if (readOnly && !isReadCommand(type)) throw new UsageError(`${type} is not a known read command; send it with ws, which asks an owner`);
210
+ const fields = record(parseJson(json), "the fields") ?? {};
211
+ if ("id" in fields || "type" in fields) throw new UsageError("the fields must not carry id or type");
212
+ return { type, fields };
213
+ }
214
+
215
+ function parseMethod(value: string | undefined, usage: string): Method {
216
+ if (value === "get") return "get";
217
+ const method = WRITE_METHODS.find((m) => m === value);
218
+ if (method === undefined) throw new UsageError(usage);
219
+ return method;
220
+ }
221
+
222
+ /** `rest <get|post|put|delete> <path> [json]`: any route under /api/ of Home Assistant itself. */
223
+ export function parseRest(args: string[]): { method: Method; path: string; body?: unknown } {
224
+ const usage = "rest get <path> | rest <post|put|delete> <path> [json]";
225
+ const [verb, path, json, ...extra] = args;
226
+ const method = parseMethod(verb, usage);
227
+ if (path === undefined || extra.length > 0 || (method === "get" && json !== undefined)) throw new UsageError(usage);
228
+ if (!path.startsWith("/api/") || /\.\.|\\|%|\s/.test(path.split("?")[0]) || path.startsWith("/api/websocket")) throw new UsageError("the path must start with /api/ and hold no dot segments, backslashes, or escapes");
229
+ const body = parseJson(json);
230
+ return { method, path, ...(body === undefined ? {} : { body }) };
231
+ }
232
+
233
+ /** `supervisor <get|post|put|delete> <endpoint> [json]`: one Supervisor endpoint; logs and downloads have their own commands. */
234
+ export function parseSupervisor(args: string[]): { method: Method; endpoint: string; body?: Record<string, unknown> } {
235
+ const usage = "supervisor get <endpoint> | supervisor <post|put|delete> <endpoint> [json]";
236
+ const [verb, endpoint, json, ...extra] = args;
237
+ const method = parseMethod(verb, usage);
238
+ if (endpoint === undefined || extra.length > 0 || (method === "get" && json !== undefined)) throw new UsageError(usage);
239
+ if (!SUPERVISOR_ENDPOINT.test(endpoint) || endpoint.includes("..")) throw new UsageError("the endpoint must look like /addons/<slug>/info");
240
+ if (method === "get" && /\/(?:logs|download)(?:\/|$)/.test(endpoint)) throw new UsageError("logs and downloads are not JSON: use the logs command");
241
+ const body = record(parseJson(json), "the body");
242
+ return { method, endpoint, ...(body === undefined ? {} : { body }) };
243
+ }
244
+
180
245
  function callAction(call: HaCall, action: ActionCall): Promise<unknown> {
181
246
  return call("call_service", { domain: action.domain, service: action.service, ...(action.target ? { target: action.target } : {}), ...(action.data ? { service_data: action.data } : {}) });
182
247
  }
@@ -187,38 +252,79 @@ function confirmed(args: string[], usage: string): string[] {
187
252
  return args.filter((a) => a !== "--confirm");
188
253
  }
189
254
 
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);
255
+ /** One call to Home Assistant's REST API; the answer is JSON when it parses, text otherwise. */
256
+ async function restRequest(config: HomeConfig, token: string, method: Method, path: string, body?: unknown): Promise<{ status: number; body: unknown }> {
257
+ const url = new URL(path, config.homeAssistantUrl);
258
+ const route = `${method.toUpperCase()} ${url.pathname}`;
192
259
  let res: Response;
260
+ let text: string;
193
261
  try {
194
- res = await fetch(url, { headers: { authorization: `Bearer ${token}`, accept: "text/plain" }, signal: AbortSignal.timeout(60_000) });
262
+ res = await fetch(url, {
263
+ method: method.toUpperCase(),
264
+ headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
265
+ body: body === undefined ? undefined : JSON.stringify(body),
266
+ signal: AbortSignal.timeout(60_000),
267
+ });
268
+ text = await res.text();
195
269
  } 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)}`);
270
+ throw new ServiceError(`home assistant gave no answer to ${route}: ${err instanceof Error ? err.message.slice(0, 200) : String(err)}`);
271
+ }
272
+ if (!res.ok) throw new ServiceError(`home assistant answered ${res.status} to ${route}${text.length > 0 ? `: ${text.slice(0, 300)}` : ""}`);
273
+ try {
274
+ return { status: res.status, body: JSON.parse(text) as unknown };
275
+ } catch {
276
+ return { status: res.status, body: text };
197
277
  }
198
- if (!res.ok) throw new ServiceError(`home assistant answered ${res.status} to GET ${url.pathname}`);
199
- return tailLines(await res.text(), lines);
200
278
  }
201
279
 
280
+ /** What a generic answer prints: secret-looking values redacted, then cut to a readable size. */
281
+ function answer(value: unknown): unknown {
282
+ return bounded(redactSecrets(value), MAX_ANSWER_CHARS);
283
+ }
284
+
285
+ const COMMANDS = ["status", "problems", "entities", "integrations", "integration-remove", "logs", "check-config", "update", "restart", "action", "ws-read", "ws", "rest", "supervisor"];
286
+
202
287
  export async function command(args: string[]): Promise<number> {
203
288
  const [name, ...rest] = args;
204
289
  if (name === undefined || name === "--help" || name === "help") {
205
290
  printRaw(HELP);
206
291
  return 0;
207
292
  }
208
- // Arguments are checked before any config or secret is read, so a wrong call never opens a session.
293
+ if (!COMMANDS.includes(name)) throw new UsageError(`unknown command: ${name}`);
294
+ // Every argument is checked before config or secret is read, so a wrong call never opens a session.
209
295
  const entityQuery = name === "entities" ? parseEntityQuery(rest) : null;
210
296
  const logQuery = name === "logs" ? parseLogs(rest) : null;
211
297
  const action = name === "action" ? parseAction(rest) : null;
298
+ const ws = name === "ws-read" || name === "ws" ? parseWs(rest, name === "ws-read") : null;
299
+ const restCall = name === "rest" ? parseRest(rest) : null;
300
+ const supervisor = name === "supervisor" ? parseSupervisor(rest) : null;
212
301
  const updateTarget = name === "update" ? confirmed(rest, "update <update.entity_id> --confirm") : null;
213
302
  if (updateTarget !== null && (updateTarget.length !== 1 || !ENTITY_ID.test(updateTarget[0]) || !updateTarget[0].startsWith("update."))) throw new UsageError("update <update.entity_id> --confirm");
214
303
  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}`);
304
+ const removeTarget = name === "integration-remove" ? confirmed(rest, "integration-remove <entry_id> --confirm") : null;
305
+ if (removeTarget !== null && (removeTarget.length !== 1 || !ENTRY_ID.test(removeTarget[0]))) throw new UsageError("integration-remove <entry_id> --confirm");
306
+ if (name === "integrations" && rest.some((a) => a !== "--failed")) throw new UsageError("integrations [--failed]");
307
+ if ((name === "status" || name === "problems" || name === "check-config") && rest.length > 0) throw new UsageError(`${name} takes no arguments`);
217
308
 
218
309
  const config = readConfig<HomeConfig>(SERVICE, SHAPE);
219
310
  const token = readSecret(SERVICE, "HOMEASSISTANT_TOKEN");
220
311
  if (logQuery !== null) {
221
- printJson({ lines: await logs(config, token, logQuery.path, logQuery.lines) });
312
+ const log = await restRequest(config, token, "get", `/api/hassio/${logQuery.path}?lines=${logQuery.lines}`);
313
+ printJson({ lines: tailLines(typeof log.body === "string" ? log.body : JSON.stringify(log.body), logQuery.lines) });
314
+ return 0;
315
+ }
316
+ if (removeTarget !== null) {
317
+ const removed = await restRequest(config, token, "delete", `/api/config/config_entries/entry/${removeTarget[0]}`);
318
+ printJson({ status: "removed", entry_id: removeTarget[0], require_restart: (removed.body as { require_restart?: unknown } | null)?.require_restart === true });
319
+ return 0;
320
+ }
321
+ if (name === "check-config") {
322
+ printJson(answer((await restRequest(config, token, "post", "/api/config/core/check_config")).body));
323
+ return 0;
324
+ }
325
+ if (restCall !== null) {
326
+ const result = await restRequest(config, token, restCall.method, restCall.path, restCall.body);
327
+ printJson({ status: result.status, body: answer(result.body) });
222
328
  return 0;
223
329
  }
224
330
  await haSession(config.homeAssistantUrl, token, async (call) => {
@@ -226,6 +332,10 @@ export async function command(args: string[]): Promise<number> {
226
332
  else if (name === "problems") {
227
333
  const s = await snapshot(call);
228
334
  printJson({ problems: homeProblems(s, Date.now()), unavailable: entitiesIn(s.states).length, version: (s.config as { version?: unknown } | null)?.version ?? null });
335
+ } else if (name === "integrations") {
336
+ const all = integrationRows(await call("config_entries/get"));
337
+ const shown = rest.includes("--failed") ? all.filter((i) => i.disabled_by === null && !["loaded", "not_loaded", "setup_in_progress"].includes(i.state)) : all;
338
+ printJson({ total: all.length, integrations: shown });
229
339
  } else if (entityQuery !== null) {
230
340
  const found = entitiesIn(await call("get_states"), entityQuery.state, entityQuery.domain);
231
341
  printJson({ total: found.length, entities: found.slice(0, entityQuery.max) });
@@ -233,11 +343,20 @@ export async function command(args: string[]): Promise<number> {
233
343
  await callAction(call, { domain: "update", service: "install", target: { entity_id: updateTarget[0] } });
234
344
  printJson({ status: "update started", entity: updateTarget[0] });
235
345
  } else if (name === "restart") {
236
- await callAction(call, { domain: "homeassistant", service: "restart" });
346
+ try {
347
+ await callAction(call, { domain: "homeassistant", service: "restart" });
348
+ } catch (err) {
349
+ // Core closes the socket while it restarts, often before it sends the result (seen on 2026-11-12).
350
+ if (!(err instanceof ServiceError) || !err.message.includes("closed the connection")) throw err;
351
+ }
237
352
  printJson({ status: "restart requested" });
238
353
  } else if (action !== null) {
239
354
  await callAction(call, action);
240
355
  printJson({ status: "done", action: `${action.domain}.${action.service}` });
356
+ } else if (ws !== null) {
357
+ printJson({ result: answer(await call(ws.type, ws.fields)) });
358
+ } else if (supervisor !== null) {
359
+ printJson({ result: answer(await supervisorCall(call, supervisor.method, supervisor.endpoint, supervisor.body)) });
241
360
  }
242
361
  });
243
362
  return 0;
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { backupSummary, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, openRepairs, pendingUpdates, tailLines } from "./home-assistant.ts";
2
+ import { backupSummary, bounded, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, integrationRows, isReadCommand, openRepairs, pendingUpdates, tailLines } from "./home-assistant.ts";
3
3
  import type { HomeSnapshot } from "./home-assistant.ts";
4
4
 
5
5
  type Listener = (event: { data?: string }) => void;
@@ -108,6 +108,12 @@ describe("home assistant findings", () => {
108
108
  ).toEqual([{ domain: "nest", title: "Nest", state: "setup_retry", reason: "Timeout" }]);
109
109
  });
110
110
 
111
+ it("lists integration entries with their ids", () => {
112
+ expect(integrationRows([{ entry_id: "01JABCDEFGHJKMNPQRSTVWXYZ0", domain: "bluetooth", title: "Pi adapter", state: "setup_retry", reason: "not found", disabled_by: null }, { domain: "hue" }])).toEqual([
113
+ { entry_id: "01JABCDEFGHJKMNPQRSTVWXYZ0", domain: "bluetooth", title: "Pi adapter", state: "setup_retry", reason: "not found", disabled_by: null },
114
+ ]);
115
+ });
116
+
111
117
  it("reads repairs, updates, and unavailable entities", () => {
112
118
  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
119
  const states = [
@@ -169,6 +175,17 @@ describe("home assistant findings", () => {
169
175
  ]);
170
176
  });
171
177
 
178
+ it("knows which commands only read", () => {
179
+ for (const type of ["get_states", "config_entries/get", "config/device_registry/list", "repairs/list_issues", "backup/info", "lovelace/config", "trace/get", "person/list", "automation/config"]) expect(isReadCommand(type)).toBe(true);
180
+ for (const type of ["config/entity_registry/update", "lovelace/config/save", "backup/generate", "backup/config/info", "call_service", "application_credentials/list", "auth/refresh_tokens", "supervisor/api"]) expect(isReadCommand(type)).toBe(false);
181
+ });
182
+
183
+ it("cuts a long answer and says how much it kept", () => {
184
+ expect(bounded({ a: 1 }, 100)).toEqual({ a: 1 });
185
+ expect(bounded(["aaaa", "bbbb", "cccc"], 16)).toEqual({ truncated: true, total: 3, shown: 2, items: ["aaaa", "bbbb"] });
186
+ expect(bounded({ text: "x".repeat(50) }, 20)).toEqual({ truncated: true, text: '{"text":"xxxxxxxxxxx' });
187
+ });
188
+
172
189
  it("keeps the newest log lines", () => {
173
190
  expect(tailLines("a\n\nb\nc\n", 2)).toEqual(["b", "c"]);
174
191
  });
@@ -134,6 +134,22 @@ export function failedIntegrations(entries: unknown): FailedIntegration[] {
134
134
  .map((e) => ({ domain: text(e.domain) ?? "?", title: text(e.title) ?? "?", state: e.state as string, reason: text(e.reason) }));
135
135
  }
136
136
 
137
+ export interface Integration {
138
+ entry_id: string;
139
+ domain: string;
140
+ title: string;
141
+ state: string;
142
+ reason: string | null;
143
+ disabled_by: string | null;
144
+ }
145
+
146
+ /** Every config entry with the fields a person needs to pick one; `entry_id` is what `integration-remove` takes. */
147
+ export function integrationRows(entries: unknown): Integration[] {
148
+ return rows(entries).flatMap((e) =>
149
+ typeof e.entry_id === "string" ? [{ entry_id: e.entry_id, domain: text(e.domain) ?? "?", title: text(e.title) ?? "?", state: text(e.state) ?? "?", reason: text(e.reason), disabled_by: text(e.disabled_by) }] : [],
150
+ );
151
+ }
152
+
137
153
  export interface Repair {
138
154
  domain: string;
139
155
  issue: string;
@@ -256,6 +272,36 @@ export function homeProblems(s: HomeSnapshot, now: number): string[] {
256
272
  return out;
257
273
  }
258
274
 
275
+ /**
276
+ * WebSocket commands that only read: lists, registries, history, traces, dashboards, and the helpers'
277
+ * `<domain>/list`. Commands that return credentials stay out (`backup/config/info` holds the backup
278
+ * password, `application_credentials/list` client secrets, `thread/get_dataset_tlv` the network key).
279
+ */
280
+ const READ_COMMANDS =
281
+ /^(?:get_(?:states|config|services|panels)|config_entries\/(?:get|flow\/progress|subentries\/list)|config\/(?:entity|device|area|floor|label|category)_registry\/(?:list|get|get_entries|list_for_display)|repairs\/(?:list_issues|get_issue_data)|backup\/(?:info|details|agents\/info)|system_log\/list|logger\/log_info|logbook\/get_events|history\/history_during_period|recorder\/(?:info|list_statistic_ids|statistics_during_period|get_statistics_metadata)|trace\/(?:list|get|contexts)|lovelace\/(?:config|info|dashboards\/list|resources)|(?:automation|script)\/config|search\/related|blueprint\/list|update\/release_notes|manifest\/(?:list|get)|diagnostics\/list|energy\/get_prefs|[a-z_]+\/list)$/;
282
+ const NO_READ = /^(?:application_credentials|auth|cloud)\//;
283
+
284
+ /** True for a WebSocket command that changes nothing and returns no credential. */
285
+ export function isReadCommand(type: string): boolean {
286
+ return READ_COMMANDS.test(type) && !NO_READ.test(type);
287
+ }
288
+
289
+ /** An answer cut to `maxChars` of JSON: a long list keeps its first items and says how many it had. */
290
+ export function bounded(value: unknown, maxChars: number): unknown {
291
+ if (JSON.stringify(value ?? null).length <= maxChars) return value;
292
+ if (Array.isArray(value)) {
293
+ const kept: unknown[] = [];
294
+ let size = 2;
295
+ for (const item of value) {
296
+ size += JSON.stringify(item ?? null).length + 1;
297
+ if (size > maxChars) break;
298
+ kept.push(item);
299
+ }
300
+ return { truncated: true, total: value.length, shown: kept.length, items: kept };
301
+ }
302
+ return { truncated: true, text: JSON.stringify(value).slice(0, maxChars) };
303
+ }
304
+
259
305
  /** The newest `lines` lines of a log text, each cut to a readable width. */
260
306
  export function tailLines(log: string, lines: number): string[] {
261
307
  return log
@@ -10,7 +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
+ import { command as homeCommand, parseAction, parseEntityQuery, parseLogs, parseRest, parseSupervisor, parseWs } from "./home/run.ts";
14
14
  import { buildInferenceRemote, command as inferenceCommand } from "./inference/run.ts";
15
15
  import { MAX_ADD_IDS, MAX_EXCLUDE_IDS, buildTrendarrCall, interpretRun, parseImdbIds, parseQueueRemove, stuckRecords, trendarrConfig, trendarrError, trendarrWarnings, command as mediaCommand } from "./media/run.ts";
16
16
  import { ServiceError, UsageError } from "./lib/errors.ts";
@@ -1073,6 +1073,9 @@ describe("home wrapper", () => {
1073
1073
  await expect(homeCommand(["restart"])).rejects.toThrow(/needs --confirm/);
1074
1074
  await expect(homeCommand(["restart", "now", "--confirm"])).rejects.toThrow(/restart --confirm/);
1075
1075
  await expect(homeCommand(["backup"])).rejects.toThrow(/unknown command/);
1076
+ await expect(homeCommand(["integration-remove", "01JABCDEFGHJKMNPQRSTVWXYZ0"])).rejects.toThrow(/needs --confirm/);
1077
+ await expect(homeCommand(["integration-remove", "../x", "--confirm"])).rejects.toThrow(/integration-remove <entry_id>/);
1078
+ await expect(homeCommand(["integrations", "--all"])).rejects.toThrow(/integrations \[--failed\]/);
1076
1079
  });
1077
1080
 
1078
1081
  it("parses entity filters, log sources, and actions", () => {
@@ -1095,6 +1098,46 @@ describe("home wrapper", () => {
1095
1098
  });
1096
1099
  });
1097
1100
 
1101
+ describe("home wrapper, generic calls", () => {
1102
+ it("lets ws-read send only known read commands", () => {
1103
+ expect(parseWs(["config/entity_registry/list"], true)).toEqual({ type: "config/entity_registry/list", fields: {} });
1104
+ expect(parseWs(["input_boolean/list"], true).type).toBe("input_boolean/list");
1105
+ expect(parseWs(["trace/list", JSON.stringify({ domain: "automation" })], true)).toEqual({ type: "trace/list", fields: { domain: "automation" } });
1106
+ expect(() => parseWs(["config/entity_registry/update", "{}"], true)).toThrow(/not a known read command/);
1107
+ expect(() => parseWs(["backup/config/info"], true)).toThrow(/not a known read command/);
1108
+ expect(() => parseWs(["application_credentials/list"], true)).toThrow(/not a known read command/);
1109
+ expect(() => parseWs(["auth/refresh_tokens"], true)).toThrow(/not a known read command/);
1110
+ });
1111
+
1112
+ it("lets ws send any command but never the sign-in or its own id", () => {
1113
+ expect(parseWs(["lovelace/config/save", JSON.stringify({ url_path: null, config: { views: [] } })], false)).toEqual({ type: "lovelace/config/save", fields: { url_path: null, config: { views: [] } } });
1114
+ expect(() => parseWs(["auth", JSON.stringify({ access_token: "x" })], false)).toThrow(UsageError);
1115
+ expect(() => parseWs(["get_states", JSON.stringify({ id: 9 })], false)).toThrow(/must not carry id or type/);
1116
+ expect(() => parseWs(["Config/Core"], false)).toThrow(UsageError);
1117
+ expect(() => parseWs(["get_states", "[1]"], false)).toThrow(/JSON object/);
1118
+ });
1119
+
1120
+ it("keeps rest calls under /api/ and supervisor calls on plain endpoints", () => {
1121
+ expect(parseRest(["get", "/api/config/automation/config/1699999999999"])).toEqual({ method: "get", path: "/api/config/automation/config/1699999999999" });
1122
+ expect(parseRest(["post", "/api/config/config_entries/entry/01JF3GKX39K3WCDRZQADJVMDRH/reload"])).toEqual({ method: "post", path: "/api/config/config_entries/entry/01JF3GKX39K3WCDRZQADJVMDRH/reload" });
1123
+ expect(parseRest(["post", "/api/template", JSON.stringify({ template: "{{ now() }}" })]).body).toEqual({ template: "{{ now() }}" });
1124
+ expect(() => parseRest(["get", "/auth/providers"])).toThrow(/must start with \/api\//);
1125
+ expect(() => parseRest(["get", "/api/../auth/token"])).toThrow(UsageError);
1126
+ expect(() => parseRest(["get", "/api/%2e%2e/x"])).toThrow(UsageError);
1127
+ expect(() => parseRest(["get", "/api/websocket"])).toThrow(UsageError);
1128
+ expect(() => parseRest(["get", "/api/config", "{}"])).toThrow(UsageError);
1129
+ expect(() => parseRest(["patch", "/api/config"])).toThrow(UsageError);
1130
+ expect(() => parseRest(["POST", "/api/config"])).toThrow(UsageError);
1131
+ expect(parseSupervisor(["get", "/addons/core_matter_server/info"])).toEqual({ method: "get", endpoint: "/addons/core_matter_server/info" });
1132
+ expect(parseSupervisor(["post", "/addons/a0d7b954_ssh/options", JSON.stringify({ options: { authorized_keys: ["ssh-ed25519 AAAA"] } })]).body).toEqual({ options: { authorized_keys: ["ssh-ed25519 AAAA"] } });
1133
+ expect(() => parseSupervisor(["get", "/core/logs"])).toThrow(/use the logs command/);
1134
+ expect(() => parseSupervisor(["get", "/backups/c6bfb343/download"])).toThrow(/use the logs command/);
1135
+ expect(() => parseSupervisor(["get", "/addons/../core/info"])).toThrow(UsageError);
1136
+ expect(() => parseSupervisor(["get", "addons"])).toThrow(UsageError);
1137
+ expect(() => parseSupervisor(["post", "/host/reboot", "[]"])).toThrow(/JSON object/);
1138
+ });
1139
+ });
1140
+
1098
1141
  describe("dns stale-zone-delete", () => {
1099
1142
  let home: string;
1100
1143
  const originalHome = process.env.HOME;