casita
Latest: v1.0.1
casita 1.0.1: https://github.com/igrigorik/casita/releases/tag/v1.0.1
casita
Casita is a structured way to read a Home Assistant home. It reads live state and structure, answers "why did this happen", and runs ONLY the scripts the owner has allowed. It is not a general Home Assistant remote — it cannot call arbitrary services, and the owner's deny rules refuse some scripts by name regardless of exposure.
Setup
Check that the CLI is installed and can reach the house before anything else:
casita --version # not found? install it: npm install -g casita (needs Node 22.16+)
casita doctor # "ok": true means the config, the token and Home Assistant all check out
If doctor reports a failed check, casita is not configured yet. Configuring it takes three things only the owner can provide. Ask for them; do not guess:
- the Home Assistant URL:
casita init --url <url>writes~/.casita/config.yaml, and never replaces an existing one - a long-lived access token, set as
CASITA_HA_TOKENin the environment casita runs in. Never print it, log it or write it to a file. - which entities casita may read: the owner exposes them in Home Assistant under Settings, Voice assistants, Expose
Running scripts is off until the owner adds an allow prefix to config.yaml. Do not edit the policy yourself.
Mental model
- Home Assistant exposure is the master gate. Casita is purely SUBTRACTIVE:
it can only ever be MORE restrictive than what you exposed to Assist, never
less. It cannot read the state of, or run, anything you have not exposed.
readable? = exposed AND not read-denywritable? = exposed AND matches an allow-prefix AND not deny-floor
- Casita reads via structured JSON, not prose. A command that reads or acts on
the home returns an envelope
{ ha, result }. Project it with--view. Three answers have their own shape:doctor({ ok, checks }) andinittake no--view, and a barecasita viewlists the views as{ views }. - Writes are a closed vocabulary. Only exposed scripts the owner has allowed
(by convention
script.casita_*), previewed and audited. Everything else returns a structured denial.
How to decide what to do
| User says… | Run |
|---|---|
| "Is the porch light on?" / "how warm is the bedroom?" | casita find "<thing>" or casita state <entity_id> |
| "What's in the garage?" | casita area "Garage" |
| "What's going on in the house?" | casita overview |
| "What's been happening lately?" | casita log --since 6 (house-wide activity) |
| "Why did the backyard lights turn on?" | casita log <entity_id> --since 24 |
| "Which batteries are low?" | casita find --device-class battery --below 20 |
| "What needs attention?" / "anything wrong?" | the attention sweep — casita view :maintenance + :health + :stale (see §Attention sweep) |
| "Is anything drawing power abnormally right now?" | casita stats --device-class power (current vs hour-of-day baseline) |
| "Has our energy use shifted? where?" | casita stats --platform emporia_vue --trend (week-over-week + attribution) |
| A cross-cutting question fixed filters can't express | casita view "<SELECT …>" (read-only SQL view) |
| "Turn off the backyard lights" | casita actions → if a matching action exists: casita run <name> --execute; else explain it isn't an approved action |
Reading the house
casita find "kitchen light" # text search (name/id/alias/area)
casita find --area Garage --domain sensor # structured filters
casita find --device-class battery --below 20
casita find --domain light --state on
casita state sensor.thermostat_temperature # one entity + attributes
casita area "Front Porch"
casita overview
casita log --since 6 # house-wide recent activity
casita log light.front_porch --since 24 # one entity: history + logbook
For a point-in-time question ("is X on right now?"), narrow and force
freshness: bare text find spans domains (it can pull in automations, scenes, or
update entities that merely mention the word) and may serve state up to the ~30s
cache TTL. Add --domain to isolate the physical thing and --fresh to request a
live re-pull:
casita find porch --domain light --fresh # only lights, live state, no noise
Then verify the freshness you asked for rather than assuming it: confirm the
envelope reports state_stale:false (low state_age_s) before answering as
definitively current. If it still reads stale, the live pull hasn't landed —
re-query, or tell the user you couldn't confirm live state and lean on
last_changed. (Freshness honesty is load-bearing for exactly this class of
question; never assert "on right now" off a snapshot the envelope flags as stale.)
Attention sweep (the ambient job)
Casita is an attention layer, not just Q&A. To proactively surface what's worth the owner's notice, run a sweep and report ONLY the exceptions (don't echo the whole house):
# The three curated exception views — pre-muted (normal_states), deduped, context-aware.
# Run all three: each catches a class the others can't.
casita view :maintenance # low battery / offline / pending updates
casita view :health # devices reporting THEMSELVES offline (connectivity sensors)
casita view :stale # streaming sensors gone SILENT — a dead/stuck probe inside an
# otherwise-alive device; invisible to :maintenance/:health
# Plus the "left in an undesirable state" checks no view covers (not malfunctions):
casita find --domain lock --state unlocked # left unlocked
casita find --domain cover --state open # left open (corroborate w/ :active before alarming)
casita log --since 6 # notable recent events (scope it; the firehose buries signal)
:maintenance + :health + :stale are the heart of the sweep — don't run just
one. :maintenance catches unavailable / low battery / updates, :health catches
a device that says it's offline, and :stale catches a sensor that's gone silent
while its device looks fine (the failure mode nothing else sees). Reason over the
results, dedupe against what you already surfaced, and raise only the deltas that matter. Two heuristics keep an attention sweep from crying
wolf:
unavailable≠unknown.overview's headline "unavailable" count conflates truly offline devices (state='unavailable') with merely idle ones (state='unknown'— buttons, EV/event entities, things waiting for a trigger). Onlyunavailableis an offline signal; don't alarm onunknown. For a clean offline list, filterstate='unavailable'(and excludedevice_class='timestamp'), or useview :maintenance.- Frozen ≠ wrong, and
last_reportedis how you tell. A value stuck far past its expected cadence is usually a sleeping/stale integration (a car asleep, a dropped device) frozen at its last value, not a live condition. The tell is thelast_reportedcolumn (HA's heartbeat: bumped on every write even when the value is unchanged) vslast_changed/last_updated(only move on a value change). A steady reading with a FRESHlast_reportedis alive; one whoselast_reportedis cold has gone silent.view :staleis built on exactly this (a streaming sensor gone silent);view :activedrops egregiously-frozen states so a sleeping car's "open" trunk doesn't read as live. - Normal states are pre-muted — and annotated. Some devices are fully
operational while HA reports a state that looks like a fault: a printer that
sleeps when idle goes
unavailable; a smart bulb on a switched circuit goesunavailablewhen the switch cuts its power; a deep-sleep battery sensor's*_onlinereadsoffbetween wake cycles. These are recorded incontext.yamlwith anormal_stateslist ("normal" in the monitoring sense — the opposite of alert), and the attention views (view :maintenance,view :stale,view :health) already DROP a row when its live state matches — so by design you won't see them and shouldn't hunt for them. The mute can be ALIVE-AWARE (max_silence_h): a deep-sleep sensor's benign state is muted only while it keeps reporting, so a dead one still surfaces. A mute with nomax_silence_hnever lifts, however long the device has been silent. To see the full suppressed set on demand,view :muted(the audit hatch: what's hidden, why, and how long since each reported). Anything that does surface in a view may carry acontextnote (thecontextcolumn /context ->> '$.text') telling you what's normal for it — read it before you raise the alarm. Meta-rule: if you find yourself re-explaining the same benign state to the owner sweep after sweep, that's the signal to record it incontext.yaml(one deterministic entry) rather than re-adjudicating it every time — noise should die at the data layer, not in the prompt. - The house-wide log is a firehose. An unscoped
log --since Nis dominated by routine telemetry and polling (timestamp/heartbeat sensors, recurring automations) and will bury the signal — and can crowd out other output. For a sweep, scopelogto a relevant entity/domain, or project/filter it for unusual transitions; don't read unbounded house-wide raw activity unless the user explicitly wants a forensic timeline. Start the sweep fromoverview/view :maintenance/find, and reach forlogto explain a specific thing.
Every read is filtered to read-allowed (exposed ∩ policy) entities. A
non-exposed entity returns READ_NOT_ALLOWED; an unknown one ENTITY_UNKNOWN.
Numeric trends + anomalies (stats) — over recorder history
view/find see only the CURRENT state. stats reaches into HA's recorder
long-term statistics to answer "is this number unusual?" and "has it drifted?".
It returns FACTS (distribution, deviation, deltas), never verdicts — you decide
what's significant.
# Point anomaly: current reading vs flat AND same-hour-of-day baseline.
casita stats --device-class power # all power circuits, most-anomalous first
casita stats --id sensor.oven_power_minute_average
# dev_hour is the signal: a value can be normal vs the daily average (dev_all~0)
# but high for THIS hour (dev_hour>2). A circuit stuck at 0 -> dev null (no variance), honest.
# Trend drift: trailing window vs the prior window, with attribution.
casita stats --platform emporia_vue --trend # 7d vs prior 7d, energy by circuit
casita stats --device-class temperature --trend --days 30 # month-over-month
- Selection:
--id(repeatable),--device-class, or--platform(resolved against the readable catalog; capped at 60 entities). --days Nwindow (default 7);--period hour|5minute|day.- Entities without recorder stats come back
no_baseline: true— never faked. - Attribution caveat:
shareapportions each delta against the set's total. Don't pool an aggregate meter (whole-housevue) WITH its own sub-circuits — that double-counts. Trend the circuits as peers, or the main alone.
SQL views (view) — arbitrary questions, read-only
When find's fixed filters can't express the question (joins across
device_class + state + area, aggregations, time-since, "things needing
attention"), use view: a read-only SELECT over the local house DB. It
cannot mutate anything (it runs on a read-only connection).
casita view # list built-in views: alias, doc, default params
casita view :maintenance # low battery / offline / pending-update triage
casita view :maintenance --param bat=30 # override a default param
casita view :active # everything "on"-like right now
casita view :stale # streaming sensors gone SILENT (dead/wedged); last_reported-based
casita view :stale --param silent_h=12 # tighten the silence cutoff (default 24h)
casita view :rollup # per-area counts (entities / on / offline)
casita view :sensors --param class=temperature # numeric readings for a device_class, high→low
casita view :consumables # refill/replace/battery, de-conflated (real signal, not the battery lie)
casita view :energy --param min=50 # live per-circuit watts, biggest first
casita view :comfort # climate zones: current vs setpoint, signed drift
casita view :air # pm2.5/pm10/voc/aqi by metric, worst first
casita view :grounds # irrigation zones + plant health, active/ailing first
casita view :fleet # vehicle status, awake-gated (asleep cars suppressed)
casita view :health # devices reporting themselves offline (connectivity)
casita view :muted # AUDIT HATCH: what the attention views currently suppress, + why
Built-in views (generic, parameterized)
| Alias | Answers | Params |
|---|---|---|
:maintenance | What needs attention (low battery, offline, pending updates); skips a device's declared normal_states and carries the context note | bat=20 |
:active | What's doing something right now (on/playing/open/…) | — |
:stale | A streaming sensor (temp/power/humidity/air) gone SILENT — dead/wedged. Keyed on last_reported (not value-change); excludes slow/change-driven classes (battery/energy/connectivity) + sleeping vehicles; honors normal_states | silent_h=24 |
:rollup | Per-area summary: entity / on / offline counts | — |
:sensors | Numeric readings for a device_class, highest first | class=battery |
:consumables | Things to refill/replace/swap, de-conflating the device_class=battery lie (water tanks, filters, wicks, real batteries; Tesla excluded) | — |
:energy | Live per-circuit power draw (Emporia), biggest first; names suffix-cleaned | min=0 |
:comfort | Each climate zone's current temp vs setpoint, with signed drift (0 = comfortable); idle/off zones get NULL drift; vehicles excluded | — |
:air | Indoor + outdoor air quality grouped by metric (pm2.5/pm10/voc/aqi), worst first; offline sensors sink | — |
:grounds | Irrigation (Rain Bird zones / rain-delay / sensor) + plant health; running/problem rows float to top | — |
:fleet | Vehicle status, awake-gated: an asleep car (unknown/unavailable) contributes no rows instead of phantom alarms | — |
:health | Devices reporting offline via a connectivity sensor (complements :maintenance unavailable); skips declared normal_states (alive-aware via max_silence_h, so a dead deep-sleeper still surfaces); longest-offline first | — |
:muted | Audit hatch: every entity the attention views currently suppress (state_normal=1), with the why note and silence age. "Walk the morgue" to verify nothing real is hidden | — |
Authoring your own
Write SQL against the entities table (one row per entity). Always filter
WHERE exposed = 1 (matches the read-exposure gate). Live values are also
redacted at the source: state, state_num, attrs, and the timestamps are
stored ONLY for readable entities (exposed ∩ not read-denied). Non-readable
entities keep metadata (id/domain/name/area) but have NULL state and {}
attrs — so a view can never surface a withheld camera, a person's GPS, or a
read-denied sensor, and a NULL state on such a row is expected. Columns:
entity_id, domain, name, aliases(JSON), area, floor, device_class, unit,
platform, exposed(0/1), state(TEXT), state_num(REAL or NULL),
state_normal(0/1 — 1 when state ∈ context.normal_states AND (alive-aware) still reporting; the attention views skip these),
last_changed, last_updated,
last_reported(TEXT — HA liveness heartbeat: every write even if unchanged; cold = silent/dead),
attrs(JSON — use json_extract(attrs,'$.key')),
context(JSON or NULL — {text?, normal_states?, max_silence_h?} resolved from context.yaml)
Liveness test in your own SQL: (julianday('now')-julianday(last_reported))*24 is the
hours since the entity last reported. Cold on a streaming sensor = dead (that's :stale);
fresh = alive even if the value is steady. The context column is per-entity editorial
annotation (from ~/.casita/context.yaml, resolved at catalog refresh): text is an
advisory note, normal_states lists the states that are NORMAL (non-alerting) for that
entity, and optional max_silence_h makes that mute alive-aware. Membership is precomputed
into the state_normal bool, which the :maintenance / :stale / :health views
already honor. In your own SQL, surface the note or replicate the mute — just filter
the plain bool, no JSON needed:
# Surface the editorial note alongside whatever you select
casita view "SELECT entity_id, name, state, context ->> '$.text' AS note
FROM entities WHERE exposed=1 AND context IS NOT NULL"
# Replicate the normal_states mute in a custom view (drop declared-normal states)
casita view "SELECT entity_id, name, state FROM entities
WHERE exposed=1 AND state='unavailable' AND NOT state_normal"
# Lights left on in bedrooms
casita view "SELECT entity_id, name, area FROM entities
WHERE exposed=1 AND domain='light' AND state='on' AND area LIKE '%bedroom%'"
# Any attribute via json_extract
casita view "SELECT entity_id, json_extract(attrs,'$.battery_level') AS bat
FROM entities WHERE exposed=1 AND json_extract(attrs,'$.battery_level') < 30"
Named params are :name; bind with --param name=value (numeric strings are
coerced). Results cap at 500 rows (truncated:true flags it; raise with --limit).
--fresh forces a live state re-pull before the query.
Projecting output (--view is different from view)
view(a command) selects rows via SQL.--view(a flag) reshapes the output envelope via JMESPath. They compose.
casita find "battery" --view 'result.entities[*].{id: entity_id, pct: state}'
casita view :maintenance --view "result.rows[?issue=='low_battery'].entity_id"
casita catalog show --view :compact # package-local compact view
casita overview --format md # incur renders a table
Running actions (rare, deliberate)
Actions are ONLY the scripts the owner has allowed (by convention
script.casita_*), created and exposed by the owner in HA.
casita actions # list approved actions + field schemas
casita run casita_turn_off_backyard_lights # PREVIEW (dry-run) by default
casita run casita_turn_off_backyard_lights --execute
casita run casita_set_porch_brightness --set /level=30 --execute
Behavior:
runpreviews by default (exact wire payload).--executefires.- Script name matches an owner deny rule →
WRITE_DENIED(never, regardless of exposure). - Non-allow-prefixed target →
WRITE_NOT_ALLOWED. - Allowlisted-but-nonexistent →
SCRIPT_UNKNOWN. - Allowlisted + exists but NOT exposed in HA →
NOT_EXPOSED(expose it to enable). - A field the script doesn't declare, or a
requiredfield left out →INVALID_INPUT(nothing is sent).casita actionslists each action's fields;--set /field=valuesets one of them. Input is limited to 16384 characters in total. - A
--viewthat fails on the result of an--executedoes not undo it: the result comes back whole with aview_errorbeside it. Readresult.fired, not the error. --executereturnschanged: the readable entities Home Assistant saw change, other than the script itself. An empty list does not mean nothing happened.RUN_OUTCOME_UNKNOWN→ the script WAS sent and may have run (it timed out or Home Assistant returned an error). Do NOT send it again. Check its effect withstate/log, and tell the user what you could and couldn't confirm. Casita cannot see why a script failed; the script's trace in Home Assistant shows it, so point the user there.- Attempts are appended to the audit log, refused ones included. A fire is always recorded before it is sent (if it can't be, it isn't sent); the other records are best effort.
casita actions also reports unexposed_candidates — allowlisted scripts that
exist and are loaded but aren't exposed yet. Exposing one in Home Assistant makes
it callable.
Never invent an action name. If casita actions doesn't list it, it doesn't
exist — tell the user it isn't an approved house action.
Health
casita doctor # config, token, catalog, HA reachability, AND access scope
casita catalog refresh # force a structural re-import (normally automatic)
casita doctor also reports the access scope — how the current policy
intersects HA exposure (exposed/readable/writable counts) and warns when
policy subtracts reads from what you exposed (read-denied drift).
Notes
- The house DB (
~/.casita/casita.db) is a refreshable cache with two clocks: structure/exposure (slow, stale-while-revalidate) and live-state snapshot (fast, ~30s TTL, re-pulled when stale). Every read reportsstate_age_s; use--freshto force a live re-pull when you need a hard freshness guarantee. - Config:
CASITA_HA_URL+CASITA_HA_TOKEN(or~/.casita/config.yaml). Token provisioning is out of scope — supply a token however you store secrets.
